package com.chinacreator.process.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinacreator.process.dao.DictionaryDao;
import com.chinacreator.process.dao.NewYearVideoDao;
import com.chinacreator.process.exception.BusinessException;
import com.chinacreator.process.util.Bash;
import com.chinacreator.process.util.JsonUtil;
import com.chinacreator.process.util.TripleDES;
import com.chinacreator.process.util.URLUtil;
import com.chinacreator.process.util.fakeid.MD5;
import com.frameworkset.util.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author zhengrong.yan
 * @date 2021/2/8 9:45
 */
public class NewYearFailVideoJob {
    private Logger log = Logger.getLogger("newyearfailvideo");

    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private NewYearVideoDao newYearVideoDao;

    public void doProcess() throws Exception {
        log.info(Thread.currentThread().getName() + "定时任务开始");
        long beginTime = System.currentTimeMillis();
        List<HashMap> list = newYearVideoDao.getFailData();
        if (list != null && list.size() > 0) {
            CountDownLatch threadSignal = new CountDownLatch(list.size());
            ExecutorService executorService = new ThreadPoolExecutor(12, 16, 10L, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy());
            //去除重复数据
            //List<HashMap> dataList = paraseData(list);
            log.info("数据库有效需要处理的数：" + list.size());

            for (HashMap vipmap : list) {
                NewYearVideoMakeService continueService = new NewYearVideoMakeService(list.size(), threadSignal, vipmap, dictionaryDao, newYearVideoDao);
                executorService.execute(continueService);
            }
            executorService.shutdown();
            try {
                executorService.awaitTermination(5L, TimeUnit.MINUTES);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        log.info(Thread.currentThread().getName() + "定时任务完成，耗时：" + (System.currentTimeMillis() - beginTime) / 1000 + " 秒");
    }

    /**
     * 去除重复数据，防止赠送会员接口被并发限制
     *
     * @param dataList
     * @return
     */
    private List<HashMap> paraseData(List<HashMap> dataList) {
        //去重复后的数据集
        List<HashMap> reDataList = new ArrayList<HashMap>();
        HashMap<String, List> tmpMap = new HashMap<String, List>();
        for (HashMap dataMap : dataList) {
            if (tmpMap.containsKey(dataMap.get("USERID").toString())) {
                log.info("重复数据，" + dataMap.get("USERID"));
            } else {
                reDataList.add(dataMap);
                List tmpList = new ArrayList();
                tmpList.add(dataMap.get("ID"));
                tmpMap.put(dataMap.get("USERID").toString(), tmpList);
            }
        }
        return reDataList;
    }

    static class NewYearVideoMakeService implements Runnable {

        private static Logger log = Logger.getLogger("newyearfailvideo");
        private int totalSize;
        private CountDownLatch threadSignal;
        private HashMap busimap;
        private DictionaryDao dictionaryDao;
        private NewYearVideoDao newYearVideoDao;

        public NewYearVideoMakeService(int totalSize, CountDownLatch threadSignal, HashMap busimap, DictionaryDao dictionaryDao, NewYearVideoDao newYearVideoDao) {
            this.totalSize = totalSize;
            this.threadSignal = threadSignal;
            this.busimap = busimap;
            this.dictionaryDao = dictionaryDao;
            this.newYearVideoDao = newYearVideoDao;
        }

        /**
         * 业务处理
         *
         * @param
         */
        public void run() {
            long startime = System.currentTimeMillis();
            Map logMap = new HashMap();
            //logMap.put("data", busimap);
            String resultCode = "-1";
            String resultInfo = "";
            String result = "";
            String id = String.valueOf(busimap.get("ID"));
            try {
                //调拓维接口
                result = invoke(busimap);
                JSONObject jsonObject = JSON.parseObject(result);
                resultCode = jsonObject.getString("code");
                resultInfo = jsonObject.getString("msg");
            } catch (Exception e) {
                e.printStackTrace();
                if (e instanceof BusinessException) {
                    resultInfo = ((BusinessException) e).getMessage();
                    resultCode = ((BusinessException) e).getCode();
                } else {
                    resultCode = "8000";
                    resultInfo = "系统错误，" + e.getMessage();
                }
            } finally {
                threadSignal.countDown();
                try {
                    if (resultInfo != null && resultInfo.length() > 250) {
                        resultInfo = resultInfo.substring(0, 250);
                    }
                    newYearVideoDao.updateHasNotify(id, resultCode, resultInfo);

                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("更新数据出现异常，" + id + ", resultCode:" + resultCode + ", resultInfo:" + resultInfo);
                }
                logMap.put("reusltCode", resultCode);
                logMap.put("resultInfo", resultInfo);
                logMap.put("result", result);
                log.info(JsonUtil.objectToJson(logMap));
            }
        }


        /**
         * 调合作方接口
         *
         * @param
         * @return
         * @throws Exception
         */
        private String invoke(Map params) throws Exception {
            String result = "";
            try {
                String url = dictionaryDao.getValue("twWXNotify");//调拓维通知接口
                String openid = String.valueOf(params.get("USERID"));
                System.out.println("openid===>" + openid);
                String finishtime = String.valueOf(params.get("FINISHTIME"));
                System.out.println("finishitime===>"+finishtime);
                String templateId = "onueANxf51HC-K0A-Imyjmyhf75aFP6M429rkcxS3Q8";
                String tourl = "https://live.v.wo.cn/platform/ytpxz/univideo/personal.html?id=" + openid;
                url += "?openId=" + openid + "&templateId=" + templateId + "&url=" + tourl;
                //新年视频换脸
                //url = "https://fifa.wo186.tv/wx/sendTemplateMessage.do?openId=ojCvV0t_sRfF1a5AolUTextKHfvM&templateId=fa5QGaGoY9YDB_vPz4q890JO68tLAv97_BjTkY3hTY4&url=";
                //新年视频换脸
                String jsonParams = "";
                JSONObject jsondata = new JSONObject();
                String[] s = {"remark", "first", "keyword1", "keyword2"};
                String[] s2 = {"您上传的照片不符合要求，视频制作失败，可点击重新制作", "非常抱歉，您的超清版视频制作失败了", "失败", finishtime};
                for (int i = 0; i < 4; i++) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("color", "#000000");
                    jsonObject.put("value", s2[i]);
                    jsondata.put(s[i], jsonObject);
                }
                jsonParams = jsondata.toJSONString();
                log.info(url);
                log.info(jsondata.toJSONString());
                try {
                    //加密
                    String keyStr = "d663bd873d93a76ab2ce11e9";
                    String txt = TripleDES.encrypt(jsonParams, keyStr);
                    ;
                    System.out.println(txt);
                    //MD5
                    String sid = "h5game";
                    String timestamp = System.currentTimeMillis() / 1000 + "";
                    String sign = sid + "&" + timestamp + "&" + txt + "&" + keyStr;
                    sign = MD5.MD5Encode(sign);
                    URL url2 = new URL(url);
                    SSLContext sc = SSLContext.getInstance("TLSv1.2"); //$NON-NLS-1$
                    sc.init(null, null, new java.security.SecureRandom());
                    HttpsURLConnection conn = (HttpsURLConnection) url2.openConnection();
                    conn.setSSLSocketFactory(sc.getSocketFactory());
                    conn.setRequestMethod("POST");
                    conn.addRequestProperty("content-type", "application/json;charset=UTF-8");
                    conn.addRequestProperty("sid", sid);
                    conn.addRequestProperty("timestamp", timestamp);
                    conn.addRequestProperty("sign", sign);
                    conn.setDoOutput(true);
                    conn.setUseCaches(false);
                    OutputStreamWriter out = null;
                    out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
                    out.write(txt);
                    out.flush();
                    result = URLUtil.readInputStream(conn.getInputStream());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                log.info("url: " + url);
                log.info("调合作方接口结果=> wxuserid: " + String.valueOf(busimap.get("USERID")) + ", id: " + String.valueOf(busimap.get("ID")) + " , result: " + result);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("id=>" + String.valueOf(params.get("ID")) + "调拓维接口失败，" + e);
            }

            return result;
        }


        /**
         * 解析数据
         *
         * @param body orderId TD_POINTS_ORDER_REC表ID字段，我方生成的订单流水号
         *             orderNo 积分商城订单号
         *             requestId 返回给客户的请求ID
         * @return
         */
        public Map transBean(Map<String, Object> body) {
            String jsonStr = JsonUtil.objectToJson(body);
            return (Map) JsonUtil.jsonToBean(jsonStr, Map.class);
        }


    }
}
