package com.platform.modules.qk.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.platform.common.annotation.SysLog;
import com.platform.common.exception.RRException;
import com.platform.common.utils.R;
import com.platform.modules.app.annotation.Login;
import com.platform.modules.plm.entity.PlmVideoNewsEntity;
import com.platform.modules.plm.service.PlmVideoNewsService;
import com.platform.modules.qk.service.CloudClipsService;
import com.platform.modules.qk.utils.CloulClipsJwtUtils;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.modules.sys.service.SysUserService;
import com.platform.modules.sys.service.SysUserTokenService;

@RestController
@RequestMapping(value = "api/cloud/clips")
@Api("云剪輯接口")
public class CloudClipsController {
	
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	@Autowired
	private CloudClipsService cloudClipsService;
	@Autowired
    private CloulClipsJwtUtils jwtUtils;
	@Autowired
	private PlmVideoNewsService plmVideoNewsService;
	
	@GetMapping("/token")
	@ApiOperation(value = "获取accessToken")
	@SysLog("趣看获取accessToken")
	public R token(@RequestParam Map<String, Object> params) {
		Object appKey = params.get("appKey");
		Object appSecret = params.get("appSecret");
		if(appKey == null || StringUtils.isBlank(appKey.toString()) || appSecret == null || StringUtils.isBlank(appSecret.toString())){
			return R.error(10002,"appKey或appSecret为空");
		}
		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(appKey.toString());

		//账号不存在、密码错误
		if(user == null || user.getUserId()==null || !user.getPassword().equals(new Sha256Hash(appSecret.toString(), user.getSalt()).toHex())) {
			return R.error(10002,"appKey和appSecret不匹配");
		}

		//账号锁定
		if(user.getStatus() == 0){
			return R.error("账号已被锁定,请联系管理员");
		}

		//生成token
        String token = jwtUtils.generateToken(appKey.toString());

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("accessToken", token);
        map.put("expire", jwtUtils.getExpire());
        
        return R.ok(map);
	}
	
	/**
	 * 多媒体素材
	 * @param params
	 * @return
	 */
	@Login
	@GetMapping("/material/list")
	@SysLog("趣看获取素材列表")
	@ApiOperation(value = "列表")
	public R list(@RequestParam Map<String, Object> params) {
		verifyMaterialList(params);
		params.put("isDelete", 0);
		Map<String, Object> map= cloudClipsService.queryPage(params);
		return R.ok(map);
	}
	@Login
	@PostMapping("/material/synthesis/start")
	@SysLog("趣看视频剪辑合成开始")
	@ApiOperation(value = "合成开始")
	public R synthesisStart(@RequestParam Map<String, Object> params) {
		verifySynthesisStart(params);
		cloudClipsService.synthesisStart(params);
		return R.ok();
	}
	@Login
	@PostMapping("/material/synthesis/stop")
	@SysLog("趣看视频剪辑合成结束")
	@ApiOperation(value = "合适结束")
	public R synthesisStop(@RequestParam Map<String, Object> params) {
		verifySynthesisStop(params);
		cloudClipsService.synthesisStop(params);
		return R.ok();
	}
	
	private void verifyMaterialList(Map<String, Object> params){
        String materialType = params.get("materialType")==null ? null : params.get("materialType").toString(); 
		String operatorId = params.get("operatorId")==null ? null : params.get("operatorId").toString();
		String limit = params.get("limit")==null ? null : params.get("limit").toString();
		if((StringUtils.isNotBlank(materialType) && !isInteger(materialType)) || (StringUtils.isNotBlank(operatorId) && !isInteger(operatorId)) || (StringUtils.isNotBlank(limit) && !isInteger(limit))) {
        	throw new RRException("参数的数据类型不正确",10004);
        }
	}
	
	private void verifySynthesisStart(Map<String, Object> params){
		if (params == null || params.size() == 0) {
            throw new RRException("未传入参数",10003);
        }
        if (!params.containsKey("taskId") || !params.containsKey("title") || !params.containsKey("operatorId") || !params.containsKey("startTime")) {
            throw new RRException("没有传入必要的参数",10005);
        }
        String taskId = params.get("taskId")==null ? null : params.get("taskId").toString(); 
		String title = params.get("title")==null ? null : params.get("title").toString();
		String operatorId = params.get("operatorId")==null ? null : params.get("operatorId").toString();
		String startTime = params.get("startTime")==null ? null : params.get("startTime").toString();
		if(!isInteger(taskId) || StringUtils.isBlank(title) || !isInteger(operatorId) || !isInteger(startTime) || (isInteger(startTime) && startTime.length()!=13)) {
        	throw new RRException("参数的数据类型不正确",10004);
        }
		PlmVideoNewsEntity videoNewsEntity = plmVideoNewsService.queryByTaskId(Long.valueOf(taskId));
		if(videoNewsEntity!=null){
			throw new RRException("taskId已存在",10006);
		}
	}
	
	private void verifySynthesisStop(Map<String, Object> params){
		if (params == null || params.size() == 0) {
            throw new RRException("未传入参数",10003);
        }
        if (!params.containsKey("taskId") || !params.containsKey("status") || !params.containsKey("message") ) {
        	throw new RRException("没有传入必要的参数",10005);
        }
        String status = params.get("status")==null ? null : params.get("status").toString(); 
        String message = params.get("message")==null ? null : params.get("message").toString(); 
        String taskId = params.get("taskId")==null ? null : params.get("taskId").toString(); 
        String materialId = params.get("materialId")==null ? null : params.get("materialId").toString(); 
		String materialCoverUrl = params.get("materialCoverUrl")==null ? null : params.get("materialCoverUrl").toString();
		String materialUrl = params.get("materialUrl")==null ? null : params.get("materialUrl").toString();
		String materialDuration = params.get("materialDuration")==null ? null : params.get("materialDuration").toString();
		String materialSize = params.get("materialSize")==null ? null : params.get("materialSize").toString();
		String endTime = params.get("endTime")==null ? null : params.get("endTime").toString();
		PlmVideoNewsEntity videoNewsEntity = plmVideoNewsService.queryByTaskId(Long.valueOf(taskId));
		if(videoNewsEntity==null){
			throw new RRException("taskId不存在",10008);
		}
        if(StringUtils.isNotBlank(status) && (status=="success" || status.equals("success"))){
    		if(!isInteger(taskId) || !isInteger(materialId) || StringUtils.isBlank(materialCoverUrl)  || StringUtils.isBlank(materialUrl) || StringUtils.isBlank(message)
    				|| !isDouble(materialDuration) ||  !isDouble(materialSize) || !isInteger(endTime) || (isInteger(endTime) && endTime.length()!=13)) {
            	throw new RRException("参数的数据类型不正确",10004);
            }
    		if(!isURL(materialCoverUrl) || !isURL(materialUrl)){
    			throw new RRException("无效的资源地址",10007);
    		}
        }
	}
	
	//判断整数（int）
	private boolean isInteger(String str) {
		if (null == str || "".equals(str)) {
			return false;
		}
		Pattern pattern = Pattern.compile("^[+]?[\\d]*$");
		return pattern.matcher(str).matches();
	}
	 
	//判断浮点数（double和float）
	private boolean isDouble(String str) {
		if (null == str || "".equals(str)) {
			return false;
		}
		Pattern pattern = Pattern.compile("^[+]?[\\d]*[.\\d]*$");
		return pattern.matcher(str).matches();
	}
	
	private boolean isURL(String strUrl) {
		if(!strUrl.startsWith("http://") && !strUrl.startsWith("https://")){
			return false; 
		}
		int counts = 0;
		boolean flag =  false;
		while (counts < 5) {
		   try {
			   	URL url  = new URL(strUrl);
			   	HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			   	if (connection.getResponseCode() == 200) {
				   flag = true;
			    }
		    	break;
		   	} catch (Exception ex) {
			   continue;
		   	}
		}
		return flag;
	}  
}
