package com.chinacreator.process.job;


import com.chinacreator.common.support.util.SpringContextUtil;
import com.chinacreator.process.dao.ChannelOrderDao;
import com.chinacreator.process.dao.HuaweiWalletOrderDao;
import com.chinacreator.process.dao.JiYueOrderDao;
import com.chinacreator.process.service.ChannelOrderService;
import com.chinacreator.process.service.JiYueService;
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 JiYueOrderJob {

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

    @Autowired
    private JiYueOrderDao jiYueOrderDao;

    @Autowired
    private JiYueService jiYueService;

    public void doProcess() throws Exception{
        logger.info("开始处理集约平台反向通知job");
        try {
            //获取表中需要订购的数据
            List<HashMap> dataList = jiYueOrderDao.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) {
                    jiYueOrderDao.updataQueryList(data.get("ID"), "2");
                }
                for (HashMap<String, String> data : dataList) {
                    JiYueOrderService continueService = new JiYueOrderService(dataList.size(), threadSignal,jiYueService,data);
                    executorService.execute(continueService);
                }
                executorService.shutdown();
                try {
                    executorService.awaitTermination(5L, TimeUnit.MINUTES);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

            Thread.sleep(100);

            //获取执行状态为2且执行时间超过2分钟的数据为待处理
            int updatalongdata = jiYueOrderDao.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 JiYueOrderService implements Runnable{

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

    public JiYueOrderService(int totalSize, CountDownLatch threadSignal, JiYueService jiYueService, HashMap<String, String> data) {
        this.totalSize = totalSize;
        this.threadSignal = threadSignal;
        this.jiYueService = jiYueService;
        this.data = data;
    }

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