package com.chinacreator.process.job;

import com.chinacreator.process.bean.NetOrderBean;
import com.chinacreator.process.bean.OrderLog;
import com.chinacreator.process.bean.TencentVacOrderBean;
import com.chinacreator.process.dao.CycleDao;
import com.chinacreator.process.dao.NetOrderDao;
import com.chinacreator.process.dao.VacOrderDao;
import com.chinacreator.process.util.CapUtil;
import com.chinacreator.process.util.CycleUtil;
import com.chinacreator.process.util.JsonUtil;
import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class TencentVacActivityJob {

    private static Logger log = Logger.getLogger(TencentVacActivityJob.class);
    private static Logger logger = Logger.getLogger("tencentVacActivityJob");


    @Autowired
    private VacOrderDao vacOrderDao;

    @Autowired
    private NetOrderDao netOrderDao;

    @Autowired
    private CycleDao cycleDao;

    public void doProcess() throws Exception {
        log.info("========》腾讯20元0元扣费job启动");
        List<TencentVacOrderBean> list = vacOrderDao.query();
        if(list != null && list.size()>0){
            for (TencentVacOrderBean tencentVacOrderBean : list) {
                Map<String,String> logMap = new HashMap<String, String>();
                logMap.put("userid", tencentVacOrderBean.getUserid());
                String result ="8000";
                try{
                    if(tencentVacOrderBean.getCpid().equals("tencent") && tencentVacOrderBean.getSpid().equals("84")){
                        logMap.put("spcode", "88226");
                        logMap.put("vacproductid", "8000652500");
                        logMap.put("type", tencentVacOrderBean.getStatus().equals("0") ? "1" : "2");
                        //result = VacUtil.vac(tencentVacOrderBean.getUserid(), "88226", "8000652500", tencentVacOrderBean.getStatus().equals("0") ? "1" : "2");
                        result =cap(tencentVacOrderBean, "88226", "8000652500", tencentVacOrderBean.getStatus());
                        //  判断号码是否在迁移表里面
                        //  是：调包周期退订接口
                        //	否：结束
                        boolean flag = cycleDao.qryIsExist(tencentVacOrderBean.getUserid(),tencentVacOrderBean.getCpid(),tencentVacOrderBean.getSpid());

                        if(flag){
                            //去cap退包周期腾讯20元按次产品
                            String cyclelog = CycleUtil.cycleCancel(tencentVacOrderBean.getUserid(),"8000990000",tencentVacOrderBean.getCpid(),tencentVacOrderBean.getSpid());
                            logger.info("包周期退订结果返回==》"+cyclelog);
                        }


                    }else if(tencentVacOrderBean.getCpid().equals("cctv") && tencentVacOrderBean.getSpid().equals("10081")){
                        logMap.put("spcode", "88226");
                        logMap.put("vacproductid", "8000652800");
                        logMap.put("type", tencentVacOrderBean.getStatus().equals("0") ? "1" : "2");
                        //result =VacUtil.vac(tencentVacOrderBean.getUserid(), "88226", "8000652800", tencentVacOrderBean.getStatus().equals("0") ? "1" : "2");
                        result =cap(tencentVacOrderBean, "88226", "8000652800", tencentVacOrderBean.getStatus());
                    }
                    if(tencentVacOrderBean.getStatus().equals("0")){
                        if ("1200".equals(result)) {
                            result = "0";
                        }
                    }else{
                        if ("1201".equals(result)) {
                            result = "0";
                        }
                    }
                    logMap.put("result", result);
                    if(result.equals("0")){
                        vacOrderDao.update(tencentVacOrderBean.getId(), (Integer.valueOf(tencentVacOrderBean.getVaccount())+1)+"", "0");
                    }else{
                        vacOrderDao.update(tencentVacOrderBean.getId(), (Integer.valueOf(tencentVacOrderBean.getVaccount())+1)+"", "1");
                    }
                }catch(Exception e){
                    log.error("",e);
                    logMap.put("result", "8000");
                }finally {
                    NetOrderBean orderInfo = new NetOrderBean();
                    orderInfo.setUserid(tencentVacOrderBean.getUserid());
                    orderInfo.setCpid(tencentVacOrderBean.getCpid());
                    orderInfo.setSpid(tencentVacOrderBean.getSpid());
                    if(tencentVacOrderBean.getStatus().equals("0")){
                        orderInfo.setOrderchannel(tencentVacOrderBean.getChannel());
                    }else{
                        orderInfo.setCancelchannel(tencentVacOrderBean.getChannel());
                    }
                    saveNetLog(orderInfo,result,"",tencentVacOrderBean.getStatus());
                    logger.info(JsonUtil.objectToJson(logMap));
                }
            }
        }
    }

    public void saveNetLog(NetOrderBean orderInfo, String errorcode, String errorinfo, String ordertype)
            throws SQLException {
        OrderLog orderLog = new OrderLog();
        orderLog.setApptype("");
        orderLog.setOrderstatus(ordertype.equals("0") ? 3:5);
        orderLog.setStatus(Integer.valueOf(ordertype).intValue());
        orderLog.setCpid(orderInfo.getCpid());
        orderLog.setIsexperience(orderInfo.getIsexperience());
        orderLog.setOrdertype("vac");
        orderLog.setProvince("");
        orderLog.setArea("");
        orderLog.setSpid(orderInfo.getSpid());
        orderLog.setUserid(orderInfo.getUserid());
        orderLog.setErrorcode(errorcode);
        orderLog.setErrorinfo(errorcode.equals("0") ? "受理成功(预受理0元)":"受理失败(预受理0元)");
        if(ordertype.equals("0")){
            orderLog.setChannel(orderInfo.getOrderchannel());
        }else{
            orderLog.setChannel(orderInfo.getCancelchannel());
        }
        this.netOrderDao.addOrderLog(orderLog);
    }

    public TencentVacOrderBean transBean(Map<String, Object> body) {
        String jsonStr = JsonUtil.objectToJson(body);
        return (TencentVacOrderBean) JsonUtil.jsonToBean(jsonStr, TencentVacOrderBean.class);
    }


    /**
     * cap
     * @param netOrderBean
     * @return
     * @throws Exception
     */
    public String cap(TencentVacOrderBean netOrderBean,String spCode,String productid,String type) throws Exception{
        String result = "-1";
        String errorinfo = "cap退订失败";

            String resJson = CapUtil.cap(netOrderBean.getCpid(),netOrderBean.getSpid(),netOrderBean.getUserid(), spCode, productid, type,
                    "", "", "", "");
            logger.info("调AP返回结果："+resJson);
            if (resJson != null) {
                Map<?,?> map = JsonUtil.jsonToMap(resJson);
                result = map.get("resultcode") != null ? map.get("resultcode").toString() : "-1";
                errorinfo = map.get("errorinfo") != null ? map.get("errorinfo").toString() : "cap退订失败";
            }
        /**
         业务返回编码
         0000 处理成功
         0007 订单同步失败
         0009 参数异常
         0008 非4G用户,鉴权失败
         0001 订购鉴权失败/退订鉴权失败
         0004 话单缓存失败
         0003 查询用户归属省编码失败
         0002 cbss产品订购异常
         0006 cbss产品退订异常
         */
/*        if (!result.equals("0")) {
            if(result.equals("-1")){
                throw new BusinessException(result, "cap"+("0".equals(type)?"订购":"退订")+"失败:接口调用失败，服务暂不可用", new String[0]);
            }else{
                //errorinfo = handelErrorinfo(result,errorinfo);
                throw new BusinessException(result, "cap"+("0".equals(type)?"订购":"退订")+"失败:"+errorinfo, new String[0]);

            }
        }*/
        return result;
    }

}

