package com.chinacreator.process.job;

import com.chinacreator.process.dao.KcOrderDao;
import com.chinacreator.process.service.KcService;
import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.*;

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class KcOrderJob {

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

    @Autowired
    private KcOrderDao kcOrderDao;

    @Autowired
    private KcService kcService;

    public void doProcess() throws Exception{
        logger.info("开始处理科创反向通知job");
        try {
            //获取表中需要订购的数据
            List<HashMap> dataList = kcOrderDao.queryList();
            logger.info("获取数据条数" + dataList.size());
            if (dataList != null && dataList.size() > 0) {
                dataList = paraseData(dataList); //去重复数据
                logger.info("去重复后用户数：" + dataList.size());
                CountDownLatch threadSignal = new CountDownLatch(dataList.size());
                ExecutorService executorService = new ThreadPoolExecutor(10, 20, 10L, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy());

                for (HashMap<String, String> data : dataList) {
                    kcOrderDao.updataQueryList(data.get("ID"), "2");
                }
                for (HashMap<String, String> data : dataList) {
                    kcOrderService continueService = new kcOrderService(dataList.size(), threadSignal,kcService,data);
                    executorService.execute(continueService);
                }
                executorService.shutdown();
                try {
                    executorService.awaitTermination(5L, TimeUnit.MINUTES);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

            Thread.sleep(100);

            //获取执行状态为2且执行时间超过2分钟的数据为待处理
            int updatalongdata = kcOrderDao.updatalongdata();
            if (updatalongdata > 0) {
                logger.info("更新状态为2处理中且执行时间超过2分钟的数据为待处理的异常数据条数【" + updatalongdata + "】");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.info("科创反向通知job执行出现异常，"+e.getMessage());
        }
        logger.info("结束科创反向通知job");
    }

    /**
     * 按手机号码与productid去除重复数据
     * @param dataList
     * @return
     */
    private List<HashMap> paraseData(List<HashMap> dataList){
        //去重复后的数据集
        List<HashMap> reDataList = new ArrayList<HashMap>();
        HashMap<Object, Object> tmpMap = new HashMap<Object, Object>();
        for (HashMap dataMap : dataList) {
            if(tmpMap.containsKey(dataMap.get("USERMOB").toString()+dataMap.get("PRODUCTID").toString())){
                logger.info("重复数据，"+dataMap);
            }else{
                tmpMap.put(dataMap.get("USERMOB").toString()+dataMap.get("PRODUCTID").toString(), dataMap);
                reDataList.add(dataMap);
            }
        }
        return reDataList;
    }

}

class kcOrderService implements Runnable{

    private static Logger logger = Logger.getLogger("kcOrder");
    private int totalSize;
    private CountDownLatch threadSignal;
    private KcService kcService;
    private HashMap<String,String> data; //订购数据

    public kcOrderService(int totalSize, CountDownLatch threadSignal, KcService kcService, HashMap<String, String> data) {
        this.totalSize = totalSize;
        this.threadSignal = threadSignal;
        this.kcService = kcService;
        this.data = data;
    }

    @Override
    public void run() {
        long startime = System.currentTimeMillis();
        int result = kcService.doLocalData(data);
        threadSignal.countDown();
        logger.info("["+data.get("ID")+"]:结果="+result+"["+ totalSize+"/"+(totalSize - threadSignal.getCount())+"],花费时间："+(System.currentTimeMillis()-startime+"/ms"));
    }
}