package com.chinacreator.process.job;


import com.chinacreator.common.util.URLUtil;
import com.chinacreator.process.bean.WyjLogBean;
import com.chinacreator.process.dao.WyjAsyncOrderDao;
import com.chinacreator.process.util.DesUtil;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class WyjAsyncOrderJob {

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

    @Autowired
    private  WyjAsyncOrderDao wyjAsyncOrderDao;
    /**
     * 订购违约包
     * @throws Exception
     */
    @Scheduled(cron = "0/10 * * * * *")
    public void doProcess() throws Exception{
        System.out.println("开始订购违约包job");
        //获取表中需要订购的数据
        List<HashMap> dataList = wyjAsyncOrderDao.queryList();
        logger.info("获取数据条数" + dataList.size());
        if (dataList!=null&&dataList.size()>0){

            //对同一个手机号10分钟内有订购违约金的，往后顺延10分钟后处理
            dataList = paraseData(dataList);
            logger.info("去重与顺延后剩余数据条数" + dataList.size());

            //修改为处理中
            for (HashMap<String,String> data : dataList){
                wyjAsyncOrderDao.updataResultCode(data.get("ID"),"2");
            }
            for (HashMap<String,String> data : dataList){
                //添加一个判断 net3g.tl_order_log 客服的操作记录
                boolean flag = false;
                try {
                    flag = wyjAsyncOrderDao.queryOrderLog(data.get("USERID"),data.get("EXTEND1"),data.get("INSERTTIME"));
                }catch (Exception e){
                    logger.error("查询net3g订购日志表客服操作记录失败");
                    flag = true;
                }
                logger.info(data.get("USERID")+data.get("extend1")+data.get("INSERTTIME")+flag);
                if (flag){
                    wyjAsyncOrderDao.updataResultCode(data.get("ID"), "5");
                }else {
                    //组件订购参数
                    logger.info("获取数据" + "USERID: " + data.get("USERID") + data);
                    WyjLogBean wyjLogBean = new WyjLogBean();
                    wyjLogBean.setId(data.get("ID"));
                    wyjLogBean.setUserid(data.get("USERID"));
                    wyjLogBean.setProvince(data.get("PROVINCE"));
                    wyjLogBean.setArea(data.get("AREA"));
                    wyjLogBean.setCpid(data.get("CPID"));
                    wyjLogBean.setSpid(data.get("SPID"));
                    //                wyjLogBean.setInserttime(data.get("INSERTTIME"));
                    wyjLogBean.setResultcode(data.get("RESULTCODE"));
                    wyjLogBean.setResultinfo(data.get("RESULTINFO"));
                    wyjLogBean.setChannel(data.get("CHANNEL"));
                    String netPwd = "wyj44e50";
                    //发起订购
                    String result = null;
                    String url = "";
                    try {
                        //                    url = "http://10.0.17.151:6060/videoif/order.do";//测试环境
                        //                    url = "http://172.16.1.81:809/videoif/order.do";
                        url = wyjAsyncOrderDao.getValue("commonOrderUrl");
                        String urlStr = url + "order.do?userid=" + URLEncoder.encode(DesUtil.encode(wyjLogBean.getUserid(), netPwd), "UTF-8") + "&cpid=" + wyjLogBean.getCpid() + "&spid=" + wyjLogBean.getSpid() + "&channel=" + data.get("CHANNEL") + "&extend1=" + data.get("EXTEND1") + "&apptype=2";
                        logger.info("url: " + urlStr);
                        result = URLUtil.get(urlStr, 60000);
                        logger.info("result: " + result);

                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.info("调videoif订购出错" + "userid" + wyjLogBean.getUserid() + "url:" + url + "?cpid=" + wyjLogBean.getCpid() + "&spid=" + wyjLogBean.getSpid() + "&userid=" + wyjLogBean.getUserid() + e);
                        wyjAsyncOrderDao.updataResultCode(wyjLogBean.getId(), "9017");
                        //                    wyjLogBean.setResultcode("-1");
                        //                    wyjLogBean.setResultinfo("调能力平台订购出错");
                        //                    wyjLogBean.setExtend1("1");
                        //                    wyjAsyncOrderDao.addWYJLog(wyjLogBean);
                    }
                    JSONObject obj = JSONObject.fromObject(result);
                    if (!obj.getString("resultcode").equals("0")) {
                        wyjAsyncOrderDao.updataResultCode(wyjLogBean.getId(), "3");
                        //                    wyjLogBean.setResultcode("-1");
                        //                    wyjLogBean.setResultinfo(obj.getString("resultCode") + obj.getString("resultInfo"));
                        //                    wyjLogBean.setExtend1("1");
                        //                    wyjAsyncOrderDao.addWYJLog(wyjLogBean);
                    } else {
                        wyjAsyncOrderDao.updataResultCode(wyjLogBean.getId(), "0");
                        //                    wyjLogBean.setResultcode("0");
                        //                    wyjLogBean.setResultinfo("成功");
                        //                    wyjLogBean.setExtend1("2");
                        //                    wyjAsyncOrderDao.addWYJLog(wyjLogBean);
                    }
                }
            }
        }
        //更新执行状态为2且执行时间超过10分钟的数据为待处理
        int res = wyjAsyncOrderDao.updataTooLong();
        if(res > 0){
            logger.info("更新状态为2处理中且执行时间超过10分钟的数据为待处理的异常数据条数【"+res+"】");
        }

        System.out.println("结束订购违约包job");
    }

    private List<HashMap> paraseData(List<HashMap> dataList) throws SQLException {
        //去重复后的数据集
        List<HashMap> reDataList = new ArrayList<HashMap>();
        HashMap<Object, Object> tmpMap = new HashMap<Object, Object>();
        for (HashMap dataMap : dataList) {
            if(tmpMap.containsKey(dataMap.get("USERID"))){
                logger.info("重复数据，"+dataMap);
            }else{
                tmpMap.put(dataMap.get("USERID"), dataMap);
                reDataList.add(dataMap);
            }
        }
        dataList = reDataList;
        //获取10分钟内订购数据
        List<HashMap> recdataList = wyjAsyncOrderDao.queryRecList();
        reDataList = new ArrayList<HashMap>();
        if (recdataList!=null&&recdataList.size()>0){
            for (HashMap<String,String> data : dataList){
                boolean flag = true;
                for (HashMap<String,String> recdata : recdataList){
                    if (recdata.get("USERID").equals(data.get("USERID"))){
                        wyjAsyncOrderDao.updataInserttime(data.get("ID"),recdata.get("ORDERTIME"));
                        flag = false;
                    }
                }
                if (flag){
                    reDataList.add(data);
                }
            }
        }else {
            reDataList = dataList;
        }
        return reDataList;
    }


}
