package com.chinacreator.process.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinacreator.common.util.DESUtil;
import com.chinacreator.common.util.MD5;
import com.chinacreator.process.bean.KuaiShouActivationBean;
import com.chinacreator.process.bean.OrderRealationBean;
import com.chinacreator.process.dao.KuaishouDao;
import com.chinacreator.process.util.IdGenerateUtil;
import com.chinacreator.process.util.JsonUtil;
import com.chinacreator.process.util.URLUtil;
import com.chinacreator.process.util.WriteLogUtil;
import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;


import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;


/**
 * kuaishou查询激活状态，每周更新
 * <p>
 * 每2分钟执行一次
 *
 * @author shuiying.ou
 * @date 20220705
 */

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class KuaishouActivationStateJob {

    private static Logger logger = Logger.getLogger("kuaishouactivationstate");

    @Autowired
    private KuaishouDao kuaishouDao;

    public void doProcess() {
        WriteLogUtil.writeLong("KuaishouActivationStateJob查询快手用户激活状态定时任务开始", logger, "KuaishouActivationStateJob");
        long beginTime = System.currentTimeMillis();
        try {
            int rows = 800; //每次取数据条数
            //按分区标识获取快手订购数据
            List<KuaiShouActivationBean> dataList = kuaishouDao.getOrderKuaiShou(rows);
            if (dataList != null) {
                logger.info("新增快手有效用户量：" + dataList.size());
            }
                List<KuaiShouActivationBean> unActivationList = kuaishouDao.getUnActivationStatus(rows);
                if (dataList != null && unActivationList != null) {
                    dataList.addAll(unActivationList);
                }else if(dataList == null && unActivationList != null){
                    dataList = unActivationList;
            }
                String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            if (dataList != null) {
                logger.info("获取到总数据：" + dataList.size() + "---time" + time);
            }
            if (dataList!= null && dataList.size() > 0) {
                    CountDownLatch threadSignal = new CountDownLatch(dataList.size());
                    ExecutorService executorService = new ThreadPoolExecutor(2, 2, 10L, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy());
                    //把数据更新为正在处理状态
                    for (KuaiShouActivationBean hm : dataList) {
                        String acticationstatus = "2";
                        kuaishouDao.updOrderKuaiShouDataToTwo(hm.getId(), acticationstatus);
                    }

                    for (KuaiShouActivationBean hm : dataList) {
                        KuaishouActivationStateService continueService = new KuaishouActivationStateService(threadSignal, hm, kuaishouDao);
                        executorService.execute(continueService);
                    }
                    executorService.shutdown();
                    try {
                        executorService.awaitTermination(5L, TimeUnit.MINUTES);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                logger.info("无新增数据与未激活数据");
            }
            Thread.sleep(100);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("查询失败" + e.getMessage() + e);
        }
        WriteLogUtil.writeLong("KuaishouActivationStateJob查询快手用户激活状态定时任务完成，耗时：" + (System.currentTimeMillis() - beginTime) / 1000 + " 秒", logger, "KuaishouActivationStateJob");
    }


    public static void main(String[] args) {
        KuaishouPushMonthNewJob job = new KuaishouPushMonthNewJob();
        try {
            job.doProcess();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class KuaishouActivationStateService implements Runnable {

    private static Logger logger = Logger.getLogger("kuaishouactivationstate");
    private CountDownLatch threadSignal;
    private KuaishouDao kuaishouDao;
    private KuaiShouActivationBean hm; //用户数据，ID和USERID

    public KuaishouActivationStateService(CountDownLatch threadSignal, KuaiShouActivationBean hm, KuaishouDao kuaishouDao) {
        this.threadSignal = threadSignal;
        this.hm = hm;
        this.kuaishouDao = kuaishouDao;
    }


    @Override
    public void run() {
        Map<String, Object> logMap = new HashMap<>();
        logMap.put("userinfo", hm);
        String acticationstatus = "1";
        String id = hm.getId();
        String userid = hm.getUserid();
        KuaiShouActivationBean activationBean = new KuaiShouActivationBean();
        //未出现异常，默认设置为成功
        acticationstatus = "0";
        try {
            //处理业务逻辑   调快手激活状态接口
            String resp = queryService(logMap);
            JSONObject json = JSON.parseObject(resp);   //调用接口后获取的结果
            Map map = JSONObject.parseObject(resp, Map.class);
            // 解析接口数据
            if (json != null && "0".equals(json.getString("result"))) {
                activationBean.setResultcode(map.get("result").toString());
                activationBean.setErrorinfo(map.get("errorcode").toString());
                activationBean.setData(map.get("data").toString());
                Map infoMessage = (Map) map.get("data");
                String status = null;
                String actype = null;
                String updatetim = null;
                if (!infoMessage.isEmpty()) {
                    try {
                        status = infoMessage.get("status").toString();
                    } catch (Exception e) {
                        status = null;
                    }
                    try {
                        actype = infoMessage.get("actype").toString();
                    } catch (Exception e) {
                        actype = null;
                    }
                    try {
                        updatetim = infoMessage.get("updatetime").toString();
                    } catch (Exception e) {
                        updatetim = null;
                    }
                }
                activationBean.setStatus(status);
                activationBean.setActype(actype);
                activationBean.setUpdatetime(updatetim);


            } else if (json != null && "1".equals(json.getString("result"))) {
                // result = 1 接口返回失败
                activationBean.setResultcode(map.get("result").toString());
                activationBean.setErrorinfo(map.get("errorcode").toString());
            } else {
                //查询失败，设置为失败
                acticationstatus = "3";
                logger.info(id + "=======>调快手激活状态接口失败");
            }
            if ("0".equals(acticationstatus)) {
                // 根据TD_KUAISHOU_FIRSTMONTH表中id查订购关系表中的数据
                OrderRealationBean orderRealationBean = kuaishouDao.getOrderRealationById(id);
                if (orderRealationBean != null && !StringUtils.isEmpty(orderRealationBean.getId())) {
                    activationBean.setOrderid(id);
                    // 根据orderid查 TD_KUAISHOU_VALID_STATUS 是否存在数据，存在则更新，不存在则新建
                    KuaiShouActivationBean bean = kuaishouDao.getKSActivate(id);
                    if (bean != null) {
                        // 更新
                        if (!StringUtils.isEmpty(orderRealationBean.getOrdertime())) {
                            activationBean.setOrdertime(orderRealationBean.getOrdertime());
                        }
                        if (!StringUtils.isEmpty(orderRealationBean.getOrderchannel())) {
                            activationBean.setOrderchannel(orderRealationBean.getOrderchannel());
                        }
                        if (!StringUtils.isEmpty(orderRealationBean.getCanceltime())) {
                            activationBean.setCanceltime(orderRealationBean.getCanceltime());
                        }
                        kuaishouDao.updKSActivate(activationBean);
                    } else {
                        // 新建
                        activationBean.setId(IdGenerateUtil.uuid6());
                        activationBean.setUserid(orderRealationBean.getUserid());
                        if (!StringUtils.isEmpty(orderRealationBean.getSpid())) {
                            activationBean.setSpid(orderRealationBean.getSpid());
                        }
                        if (!StringUtils.isEmpty(orderRealationBean.getSpname())) {
                            activationBean.setSpname(orderRealationBean.getSpname());
                        }
                        if (!StringUtils.isEmpty(orderRealationBean.getOrdertime())) {
                            activationBean.setOrdertime(orderRealationBean.getOrdertime());
                        }
                        if (!StringUtils.isEmpty(orderRealationBean.getOrderchannel())) {
                            activationBean.setOrderchannel(orderRealationBean.getOrderchannel());
                        }
                        if (!StringUtils.isEmpty(orderRealationBean.getCanceltime())) {
                            activationBean.setCanceltime(orderRealationBean.getCanceltime());
                        }

                        kuaishouDao.inserttimeKSActivate(activationBean);
                    }
                } else {
                    logger.info(id + "=======>订购关系表中无该数据");
                }
            } else {
                logger.info(userid + "=======>调快手激活状态查询接口失败");
            }
        } catch (Exception e) {
            //出现异常，设置为失败
            acticationstatus = "3";
        } finally {
            threadSignal.countDown();
            try {
                //如果为3，下次再处理
               kuaishouDao.updOrderKuaiShouData(id, acticationstatus);
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("更新数据出现异常，" + e.getMessage());
            }
            //写日志
            logMap.put("jobname", "KuaishouActivationStateJob");
            logMap.put("activationBean", activationBean);
            String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            logMap.put("time", time);
            logger.info(JsonUtil.objectToJson(logMap));
        }
    }

    private String queryService(Map<String, Object> logMap) {
        String baseurl = "http://api.gifshow.com/rest/n/partner/cucc/callback/check/active";
        HashMap<String, Object> paramsMap = new HashMap<>();
        String userid = hm.getUserid();
        try {
            userid = DESUtil.encode(userid, "ksks1234");
            paramsMap.put("usermob", userid);
            logMap.put("userid", userid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        StringBuffer stringBuffer = new StringBuffer();
        String str = stringBuffer.append(userid).append("2rFUrLZyKV9S").toString();
        String sign = MD5.MD5Encode(str);
        if (sign != null && sign.length() > 16) {
            sign = sign.substring(0, 16);
        }
        paramsMap.put("sign", sign);
        logMap.put("sign", sign);
        String result = "";
        try {
            result = URLUtil.postJson(baseurl, JsonUtil.objectToJson(paramsMap));
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("调查询快手激活状态接口失败" + e.getMessage() + e);
        }
        return result;
    }


}
