package com.chinacreator.process.service;

import com.alibaba.fastjson.JSON;
import com.chinacreator.common.exception.BusinessException;
import com.chinacreator.common.util.URLUtil;
import com.chinacreator.process.bean.*;
import com.chinacreator.process.dao.*;
import com.chinacreator.process.exception.VideoException;
import com.chinacreator.video.queue.MessageService;
import com.chinacreator.video.queue.bean.MessagePipe;
import net.sf.json.JSONSerializer;
import oracle.sql.DATE;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class JiYueService {

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

    @Autowired
    private SdkOrderDao sdkOrderDao;

    @Autowired
    private NetOrderDao netOrderDao;

    @Autowired
    private CallerAreacodeDao callerAreacodeDao;

    @Autowired
    private SysDao sysDao;

    @Autowired
    private JiYueOrderDao jiYueOrderDao;

    @Autowired
    private MessageService messageService;

    @Autowired
    private ChangshiDao changshiDao;

    @Autowired
    private CsOrderControlDao csOrderControlDao;

    @Autowired
    private EcbProductDao ecbProductDao;

    @Autowired
    private WxcsDao wxcsDao;

    @Autowired
    private EcbDiscntDao ecbDiscntDao;

    @Autowired
    private ChangshiBlackDao changshiBlackDao;

    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private BusiOperlimitConfDao busiOperlimitConfDao;

    @Autowired
    private NextMonthEffectService nextMonthEffectService;

    public int doLocalData(HashMap<String, String> data) {
        int result = 0;
        try {
            //北京号码段订购限制
            String numberlimit = dictionaryDao.getValue("Numberlimit");
            if(numberlimit != null && numberlimit.indexOf(data.get("ID").substring(0, 7)) != -1){
                jiYueOrderDao.updataQueryList(data.get("ID"), "9010","用户为黑名单用户");
                throw new BusinessException("9010", "用户为黑名单用户", new String[0]);
            }

            HashMap cpSp = jiYueOrderDao.getCpSp(data.get("PRODUCTID"));
            OrderConfigBean orderConfigBean = new OrderConfigBean();
            if (cpSp!=null&&cpSp.size()>0){
                data.put("CPID",cpSp.get("CPID").toString());
                data.put("SPID",cpSp.get("SPID").toString());
                orderConfigBean.setCpid(cpSp.get("CPID").toString());
                orderConfigBean.setSpid(cpSp.get("SPID").toString());
                orderConfigBean.setType(cpSp.get("AUTHSTATUS").toString());
            }else {
                jiYueOrderDao.updataQueryList(data.get("ID"), "9012","PRODUCTID未匹配到spid");
                throw new BusinessException("9012", "PRODUCTID未匹配到spid", new String[0]);
            }

            //验证业务操作限制（是否能订购，是否能退订）
            if(this.valiOperLimit(data.get("ID"), data.get("SPID"), data.get("TYPE"))){
                jiYueOrderDao.updataQueryList(data.get("ID"), "9016", "业务办理限制，不处理");
                throw new BusinessException("9016", data.get("ID")+"业务办理限制，不处理", new String[0]);
            }

            if ("1006".equals(orderConfigBean.getSpid()) && 0 == jiYueOrderDao.isOrder(orderConfigBean.getCpid(), "1009", data.get("USERMOB"))) {
                jiYueOrderDao.updataQueryList(data.get("ID"), "9001","订购失败，芒果TV16元产品互斥,订购了合约产品");
                throw new BusinessException("9001", "订购失败，芒果TV16元产品互斥,订购了合约产品", new String[0]);
            }

            getProvinceInfo(data);

            if ("0".equals(data.get("TYPE"))) {
                String provinceOrder = sdkOrderDao.getProvinceOrder(orderConfigBean.getSpid());
                if (StringUtils.isNotEmpty(provinceOrder)){
                    String mobileInfo = getMobileInfo(data.get("USERMOB"));
                    if (!provinceOrder.contains(mobileInfo)){
                        throw new VideoException("1", "订购失败，该"+mobileInfo+"地区不能订购此产品");
                    }
                }
                System.out.println(orderConfigBean.getType().equals("0")||orderConfigBean.getType().equals("1"));
                if (orderConfigBean.getType().equals("0")||orderConfigBean.getType().equals("1")) {
                    if (orderConfigBean.getCpid().equals("tencent")
                            && (orderConfigBean.getSpid().equals("101") || orderConfigBean.getSpid().equals("84"))) {
                        result = inserttencentMq(data, orderConfigBean, "0");
                    } else {
                        result = compareOrderForNet(data);
                        if(result == 0){//成功发短信
                            logger.info("开始推短信mq");
                            insertSmsMq1(data.get("USERMOB"), "jypt", orderConfigBean, "0",data);
                            logger.info("推短信mq");
                        }
                    }
                } else {
//                    result = compareOrderForSdk(data);
                }
            } else {
                if (orderConfigBean.getType().equals("0")||orderConfigBean.getType().equals("2")) {
                    if (orderConfigBean.getCpid().equals("tencent")
                            && (orderConfigBean.getSpid().equals("101") || orderConfigBean.getSpid().equals("84"))) {
                        result =inserttencentMq(data, orderConfigBean, "1");
                    } else{
                        result = compareCancelForNet(data);
                        if(result == 0){//成功发短信
                            insertSmsMq1(data.get("USERMOB"), "bss", orderConfigBean, "1",data);
                        }
                    }
                } else {
//                    result = compareCancelForSdk(data);
                }
            }

            if (result == 0) {
                logger.info("开始生成活动关系");
                insertMqOffline(data, orderConfigBean);
                logger.info("推送到mq生成活动关系");
                if (orderConfigBean.getCpid().equals("changshi") && orderConfigBean.getSpid().equals("1150")
                        && data.get("TYPE").equals("0")) {
                    WxcsBean wxcsBean = wxcsDao.getConfig(orderConfigBean.getCpid(), orderConfigBean.getSpid());
                    if (wxcsBean.getVipstatus().equals("0")
                            && NumberUtils.toLong(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss")) < NumberUtils
                            .toLong(wxcsBean.getVipendtime())
                            && NumberUtils.toLong(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss")) > NumberUtils
                            .toLong(wxcsBean.getVipstarttime())) {
                        insertSmsMq(data.get("USERMOB"), "ecb", orderConfigBean);
                    }
                }
            }
            logger.info("结束");

        }catch (Exception e){
            result = 8000;
            e.printStackTrace();
            logger.error("同步订购关系出现异常，"+e.getMessage());
        }finally {
            logger.info("结束订购退订流程，返回");
        }
        return result;
    }

    public OrderConfigBean getOrderConfigBean(String spid) throws SQLException {
        return this.jiYueOrderDao.findBySpid(spid);
    }

    /**
     * 验证业务操作限制（是否能订购，是否能退订）
     * @param id
     * @param spid
     * @param type 操作标识：0订购、 1退订
     * @return
     * @throws Exception
     */
    private boolean valiOperLimit(String id, String spid,String type) throws Exception {
        //数据来源
        String datasrc = "JYPT";
        List<HashMap> dataList = busiOperlimitConfDao.getValue(spid);
        boolean haslimit = false;
        if(dataList != null && dataList.size()>0){
            for(HashMap tm : dataList){
                if(type.equals(tm.get("OPERTYPE")) && datasrc.equals(tm.get("DATASRC"))){
                    haslimit = true;
                    break;
                }
            }
        }
        return haslimit;
    }

    public void getProvinceInfo(HashMap<String, String> data) {
        AreaInfo areaInfo = this.callerAreacodeDao.findByCallerhead(data.get("USERMOB").substring(0, 7));
        if (areaInfo == null) {
            data.put("PROVINCE","");
            data.put("AREA","");
        } else {
            data.put("PROVINCE",areaInfo.getProvince());
            data.put("AREA",areaInfo.getArea());
        }
    }

    /**
     * 查询号码信息
     * @param userid
     * @return
     * @throws Exception
     */
    public String  getMobileInfo(String userid){
        String provice= null;
        try {
            provice= sdkOrderDao.getHmdInfo(userid.substring(0,7));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return provice;
    }

    public int inserttencentMq(HashMap<String, String> data, OrderConfigBean orderConfigBean,String type) throws SQLException {
        try {
            Map<String, String> map = new HashMap<String, String>();
            String url = dictionaryDao.getValue("mqReciveUrl");
            map.put("userid", data.get("USERMOB"));
            map.put("cpid", orderConfigBean.getCpid());
            map.put("spid", orderConfigBean.getSpid());
            map.put("province", data.get("PROVINCE"));
            map.put("area", data.get("AREA"));
            map.put("channel", "jypt");
            if (type.equals("0")) {
                map.put("ordertime", data.get("ORDERTIME"));
            } else {
                map.put("canceltime", data.get("CANCELTIME"));
            }
            map.put("endtime", data.get("ENDTIME"));
            if(orderConfigBean.getSpid().equals("101")){
                map.put("ordertype", "2");
            }else{
                map.put("ordertype", "0");
            }
            map.put("orderstatus", type);
            map.put("type", "vacmq");
            URLUtil.post(url, JSONSerializer.toJSON(map).toString(),1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        jiYueOrderDao.updataQueryList(data.get("ID"), "0","腾讯20元按次或包月产品");

        /****
         * 腾讯20元,集约平台渠道覆盖
         */
        try {
            NetOrderBean newOrderBean = getNetOrderInfo(data);
            NetOrderBean oldOrderBean = this.netOrderDao.findOrder(newOrderBean.getCpid(), newOrderBean.getSpid(), newOrderBean.getUserid());
            if(oldOrderBean != null){
                if("0".equals(type)){
                    /*****************************************************集约平台订购，进行订购渠道更新*************************************************************/
                    if ("0".equals(oldOrderBean.getStatus())) {
                        if("jypt".equals(newOrderBean.getOrderchannel())){
                            try {
                                //订购渠道优先级更新
                                this.netOrderDao.orderUpdate(newOrderBean);
                                saveNetLog(newOrderBean, "9098", "[集约平台订购渠道覆盖]已订购，订购渠道更新为jypt", data.get("TYPE"));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }else{
                        if("jypt".equals(newOrderBean.getOrderchannel())){
                            try {
                                if(newOrderBean.getOrdertime().getTime() < oldOrderBean.getCanceltime().getTime()){
                                    //订购渠道优先级更新
                                    this.netOrderDao.orderUpdate(newOrderBean);
                                    saveNetLog(newOrderBean, "9096", "[集约平台订购渠道覆盖]已退订，且集约平台订购时间小于退订时间，订购渠道更新为jypt",  data.get("TYPE"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    /*****************************************************集约平台订购，进行订购渠道更新*************************************************************/
                }else{
                    /*****************************************************集约平台退订，进行退订渠道更新*************************************************************/
                    if (!"0".equals(oldOrderBean.getStatus())) {
                        if("jypt".equals(newOrderBean.getCancelchannel()) ){
                            try {
                                //退订渠道优先级更新
                                this.netOrderDao.cancelUpdate(newOrderBean);
                                saveNetLog(newOrderBean, "9099", "[集约平台订购渠道覆盖]已退订，退订渠道更新为jypt", data.get("TYPE"));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }else{
                        if("jypt".equals(newOrderBean.getCancelchannel()) ){
                            try {
                                if(newOrderBean.getCanceltime().getTime() < oldOrderBean.getOrdertime().getTime()
                                        && oldOrderBean.getCancelchannel()!=null && !"".equals(oldOrderBean.getCancelchannel().trim())){
                                    //退订渠道优先级更新
                                    this.netOrderDao.cancelUpdate(newOrderBean);
                                    saveNetLog(newOrderBean, "9097", "[集约平台退订渠道覆盖]已订购，且集约平台退订时间小于订购时间，退订渠道更新为jypt", data.get("TYPE"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    /*****************************************************集约平台退订，进行退订渠道更新*************************************************************/
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return 3;
    }

    public NetOrderBean getNetOrderInfo(HashMap<String,String> data) throws Exception {
        OrderConfigBean orderConfigBean = getOrderConfigBean(data.get("SPID"));
        NetOrderBean netOrderBean = new NetOrderBean();
        netOrderBean.setUserid(data.get("USERMOB"));
        netOrderBean.setCpid(orderConfigBean.getCpid());
        netOrderBean.setBatchid(DateFormatUtils.format(new Date(), "yyyyMMdd"));
        netOrderBean.setSpid(orderConfigBean.getSpid());
        netOrderBean.setProvince(data.get("PROVINCE"));
        netOrderBean.setArea(data.get("AREA"));
        if (data.get("TYPE").equals("0")) {
            if (StringUtils.isEmpty(data.get("ORDERTIME"))){
                throw new BusinessException("9012", "参数错误", new String[0]);
            }
            netOrderBean.setOrdertime(DateUtils.parseDate(data.get("ORDERTIME"), new String[] { "yyyyMMddHHmmss" }));
            netOrderBean.setOrderchannel("jypt");
            netOrderBean.setStatus("0");
            netOrderBean.setOrderstatus(3);
        } else {
            if (StringUtils.isEmpty(data.get("CANCELTIME"))) {
                throw new BusinessException("9012", "参数错误", new String[0]);
            }
            netOrderBean.setCanceltime(DateUtils.parseDate(data.get("CANCELTIME"), new String[] { "yyyyMMddHHmmss" }));
            netOrderBean.setCancelchannel("jypt");
            netOrderBean.setStatus("1");
            netOrderBean.setOrderstatus(5);
        }

        /**
         * 计费点相同的产品SPID替换
         */
        nextMonthEffectService.replaceSameVacSpid(netOrderBean);

        /**
         * 次月生效产品SPID替换
         */
        nextMonthEffectService.replaceSpid(netOrderBean);

        //验证业务操作限制（是否能订购，是否能退订）
        if(this.valiOperLimit(data.get("ID"), netOrderBean.getSpid(), data.get("TYPE"))){
            throw new BusinessException("9016", "业务办理限制，不处理", new String[0]);
        }

        return netOrderBean;
    }

    public void saveNetLog(NetOrderBean orderInfo, String errorcode, String errorinfo, String ordertype)
            throws SQLException {
        OrderLog orderLog = new OrderLog();
        orderLog.setApptype(orderInfo.getApptype());
        orderLog.setChannel(ordertype.equals("0") ? orderInfo.getOrderchannel() : orderInfo.getCancelchannel());
        orderLog.setOrderstatus(orderInfo.getOrderstatus());
        orderLog.setStatus(Integer.valueOf(orderInfo.getStatus()).intValue());
        orderLog.setCpid(orderInfo.getCpid());
        orderLog.setIsexperience(orderInfo.getIsexperience());
        orderLog.setOrdertype(orderInfo.getOrdertype());
        orderLog.setProvince(orderInfo.getProvince());
        orderLog.setArea(orderInfo.getArea());
        orderLog.setSpid(orderInfo.getSpid());
        orderLog.setUserid(orderInfo.getUserid());
        orderLog.setErrorcode(errorcode);
        orderLog.setErrorinfo(errorinfo);
        this.netOrderDao.addOrderLog(orderLog);
    }

    public int compareOrderForNet(HashMap<String, String> data) throws Exception {
        int result = 0;
        NetOrderBean orderBean = null;
        NetOrderBean oldOrderBean = null;
        try {
            orderBean = getNetOrderInfo(data);
            if( changshiBlackDao.isBlackUser(orderBean.getUserid(),orderBean.getCpid())){
                throw new BusinessException("9080", "黑名单用户不处理订购", new String[0]);
            }

            boolean hasnme = false; //是否次月生效
            if(nextMonthEffectService.hasNextMonthBusi(orderBean.getSpid())){
                data.put("CPID",orderBean.getCpid());
                data.put("SPID",orderBean.getSpid());
                hasnme = true;
                nextMonthEffectService.process(orderBean);
                //设置同步状态值，用于判断是否生成活动关系
                data.put("SYNCSTATUS",orderBean.getSyncstatus());
            }else{
                oldOrderBean = this.netOrderDao.findOrder(orderBean.getCpid(), orderBean.getSpid(), orderBean.getUserid());
                System.out.println("oldOrderBean"+oldOrderBean != null);
                if (oldOrderBean != null) {
                    //沃视频爱奇艺定向流量年包产品限制为当月不能重复订购
                    if("99134246".equals(orderBean.getSpid()) && valiMonth(orderBean.getOrdertime(),oldOrderBean.getOrdertime())){
                        throw new BusinessException("9088", "订购失败，反向通知的订购时间小于或等于订购关系表的订购时间", new String[0]);
                    }

                    /*****************************************************集约平台订购，进行订购渠道更新*************************************************************/
                    if ("0".equals(oldOrderBean.getStatus())) {
                        if("jypt".equals(orderBean.getOrderchannel())){
                            try {
                                //订购渠道优先级更新
                                this.netOrderDao.orderUpdate(orderBean);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            throw new BusinessException("9098", "[集约平台订购渠道覆盖]已订购，订购渠道更新为jypt", new String[0]);
                        }

                        throw new BusinessException("9010", "已订购，请不要重复订购", new String[0]);
                    }else if("1".equals(oldOrderBean.getStatus()) && oldOrderBean.getSpid().equals("99134246")){
                        orderBean.setEndtime(jiYueOrderDao.getLastYearDay(oldOrderBean.getEndtime()));
                    }else if("2".equals(oldOrderBean.getStatus()) && oldOrderBean.getSpid().equals("99134246")){
                        orderBean.setEndtime(jiYueOrderDao.getLastYearDayFirst(orderBean.getOrdertime()));
                    }else{
                        if("jypt".equals(orderBean.getOrderchannel())){
                            try {
                                if(orderBean.getOrdertime().getTime() < oldOrderBean.getCanceltime().getTime()){
                                    //订购渠道优先级更新
                                    this.netOrderDao.orderUpdate(orderBean);

                                    saveNetLog(orderBean, "9096", "[集约平台订购渠道覆盖]已退订，且集约平台订购时间小于退订时间，订购渠道更新为jypt", data.get("TYPE"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    /*****************************************************集约平台订购，进行订购渠道更新*************************************************************/

                    if (orderBean.getCpid().equals("changshi") && ("1150".equals(orderBean.getSpid()) || "1040".equals(orderBean.getSpid()))){
                        if (orderBean.getSpid().equals("1040")) {
                            throw new BusinessException("9017", "标清订购不处理", new String[0]);
                        }
                        String discntValue = orderBean.getSpid().equals("1150") ? "1" : "0";
                        EcbProductInfo ecbProductInfo = ecbProductDao.queryEcb(data.get("ID"));
                        List<DiscntInfo> list = changshiDao.queryDiscntInfo(orderBean.getUserid(), discntValue);
                        for (DiscntInfo discntInfo : list) {
                            if (discntInfo.getType().equals("0")
                                    && !discntInfo.getDiscntid().equals(ecbProductInfo.getDiscntCode())) {
                                throw new BusinessException("9011", "不同资费有未退的订购请求，不处理", new String[0]);
                            }
                        }
                        if (orderBean.getSpid().equals("1150")) {
                            if (!csOrderControlDao.discntCodeControl(ecbProductInfo.getDiscntCode(), orderBean.getCpid(),
                                    orderBean.getSpid())) {
                                throw new BusinessException("9903", "不在资费白名单内", new String[0]);
                            }
                            if (csOrderControlDao.discntFeeControl(ecbProductInfo.getDiscntCode(), orderBean.getCpid(),
                                    orderBean.getSpid())) {
                                result = 1;
                            }
                            //20220104xu.zhou，只有1150的才走ecbDiscntDao.order，防止其他cpid为changshi的数据落不了订购关系
                            ecbDiscntDao.order(ecbProductInfo, orderBean);
                        }
                        //ecbDiscntDao.order(ecbProductInfo, orderBean);
                    } else if (NumberUtils.toLong(data.get("ORDERTIME")) < NumberUtils
                            .toLong(oldOrderBean.getCanceltimestr())) {
                        throw new BusinessException("9023", "订购时间晚于本地退订时间不处理", new String[0]);
                    }
                    this.netOrderDao.order(orderBean);
                } else {

                    if("99134246".equals(orderBean.getSpid())){
                        orderBean.setEndtime(jiYueOrderDao.getLastYearDayFirst(orderBean.getOrdertime()));
                    }
                    if (orderBean.getCpid().equals("changshi") && orderBean.getSpid().equals("1150")) {
                        EcbProductInfo ecbProductInfo = ecbProductDao.queryEcb(data.get("ID"));
                        if (!csOrderControlDao.discntCodeControl(ecbProductInfo.getDiscntCode(), orderBean.getCpid(),
                                orderBean.getSpid())) {
                            throw new BusinessException("9903", "不在资费白名单内", new String[0]);
                        }
                        if (csOrderControlDao.discntFeeControl(ecbProductInfo.getDiscntCode(), orderBean.getCpid(),
                                orderBean.getSpid())) {
                            result = 1;
                        }
                        ecbDiscntDao.order(ecbProductInfo, orderBean);
                    } else if (orderBean.getCpid().equals("changshi") && orderBean.getSpid().equals("1040")) {
                        throw new BusinessException("9017", "标清订购不处理", new String[0]);
                        // EcbProductInfo ecbProductInfo =
                        // ecbProductDao.queryEcb(bean.getId());
                        // ecbDiscntDao.order(ecbProductInfo, orderBean);
                    }
                    System.out.println("集约平台订购"+JSON.toJSONString(orderBean));
                    this.netOrderDao.order(orderBean);
                }
            }
            //不是能力平台次月生效产品，或者是能力平台产品且是正式订购关系表退订操作
            if(!hasnme || (hasnme && "5".equals(orderBean.getSyncstatus()))){
                saveNetLog(orderBean, "0", "", data.get("TYPE"));
            }
            if(hasnme){
                System.out.println("次月生效数据订购完成");
                jiYueOrderDao.updataQueryList(data.get("ID"),"0","次月生效数据订购完成");
            }else{
                System.out.println("0");
                jiYueOrderDao.updataQueryList(data.get("ID"),"0","ok");
            }
        } catch (Exception e) {
            result = 1;
            result = this.catchOper(e, data, oldOrderBean);
        }
        return result;
    }

    /**
     * 验证订购月份是否与已订购月份相同
     * @param newOrdertime
     * @param oldOrdertime
     * @return 相同返回true，反之返回false
     */
    private boolean valiMonth(Date newOrdertime, Date oldOrdertime){
        boolean res = false;
        String newmonth = DateFormatUtils.format(newOrdertime, "yyyyMM");
        String oldmonth = DateFormatUtils.format(oldOrdertime, "yyyyMM");
        if(newmonth.equals(oldmonth)){
            res = true;
        }
        if(!res && Integer.parseInt(newmonth) < Integer.parseInt(oldmonth)){
            res = true;
        }
        return res;
    }

    /**
     * 异常处理
     * @param e
     * @param orderBean
     * @return
     */
    private int catchOper(Exception e, HashMap<String, String> data, NetOrderBean orderBean){
        int result = 1;
        if ((e instanceof BusinessException)) {
            try {
                //this.channelOrderDao.updatestatus(bean.getId(), ((BusinessException) e).getCode());
                String resultInfo = ((BusinessException) e).getMessage();
                String resultcode = ((BusinessException) e).getCode();
                if(!StringUtils.isEmpty(resultInfo) && resultInfo.length()>500){
                    resultInfo = resultInfo.substring(0, 500);
                }
                logger.info("resultInfo="+resultInfo+", resultcode="+resultcode);
                jiYueOrderDao.updataQueryList(data.get("ID"),resultcode,resultInfo);
            } catch (Exception e2) {
                e.printStackTrace();
                logger.error(data.get("ID")+"JiYueService更新数据出现异常"+e.getMessage());
            }
            try {
                saveNetLog(orderBean, ((BusinessException) e).getCode(), e.getMessage(), data.get("TYPE"));
            } catch (Exception e2) {
                e.printStackTrace();
                logger.error(data.get("ID")+"JiYueService写日志出现异常"+e.getMessage());
            }

            result = Integer.valueOf(((BusinessException) e).getCode()).intValue();
        } else {
            e.printStackTrace();
            try {
                //this.channelOrderDao.updatestatus(bean.getId(), "8000");
                String resultInfo = e.getMessage();
                String resultcode = "8000";
                if(!StringUtils.isEmpty(resultInfo) && resultInfo.length()>500){
                    resultInfo = resultInfo.substring(0, 500);
                }
                jiYueOrderDao.updataQueryList(data.get("ID"),resultcode,resultInfo);
            } catch (Exception e2) {
                e.printStackTrace();
                logger.error(data.get("ID")+"JiYueService更新数据出现异常"+e.getMessage());
            }
            try {
                saveNetLog(orderBean, "8000", "系统忙！", data.get("TYPE"));
            } catch (Exception e2) {
                e.printStackTrace();
                logger.error(data.get("ID")+"JiYueService写日志出现异常"+e.getMessage());
            }
        }
        return result;
    }

    public void insertSmsMq1(String userid, String channel, OrderConfigBean orderConfigBean, String type,HashMap<String, String> data) {
        try {
            //1150的另外处理，保持不动
            if ((!orderConfigBean.getCpid().equals("changshi") && !orderConfigBean.getSpid().equals("1150")) || "1218".equals(orderConfigBean.getSpid()) ){
                Map<String, String> map = new HashMap<String, String>();
                String url = dictionaryDao.getValue("mqReciveUrl");
                String spid = orderConfigBean.getSpid();
                map.put("userid", userid);
                map.put("cpid", orderConfigBean.getCpid());
                map.put("spid", orderConfigBean.getSpid());
                map.put("result", "0");
                map.put("channel", "");
                map.put("times", "");
                map.put("orderType", "");
                map.put("type", "cssms");
                if("fhcp".equals(orderConfigBean.getCpid())&&"99134246".equals(orderConfigBean.getSpid())){
                    map.put("param1", timehandel(jiYueOrderDao.getFhcpEndtime(userid,orderConfigBean.getCpid(),orderConfigBean.getSpid())));
                }
                //20220507修改，针对云南省订购成功短信保持原来的订购成功短信。其他省份订购成功短信短信下发全部是改为：
                //快手12G流量月包省分           spid=  297
                //畅视多视频共享15G流量月包省分  spid= 1218 活动，192908845733和192908129979 渠道 订购成功短信调整为新模板
                String busiType = "";
                boolean flag = false;
                //1.先判断省份
                String province = getMobileInfo(userid);
                //2.获取活动配置
                HashMap activitymap = jiYueOrderDao.getCouponConfig(spid);
                if(activitymap!=null && !"云南".equals(province) && ("297".equals(spid) || "1218".equals(spid) || "299".equals(spid))){
                    String activitystarttime = activitymap.get("STARTTIME").toString();
                    String activityendtime = activitymap.get("ENDTIME").toString();
                    //订购时间小于活动开始时间，或者订购时间大于活动结束时间
                    String ordertime = data.get("ORDERTIME");
                    if(Long.parseLong(ordertime) < Long.parseLong(activitystarttime)
                            || Long.parseLong(ordertime) > Long.parseLong(activityendtime)){
                        System.out.println("订购时间未在【517电信】活动期内，不下发活动短信");
                    }else{
                        //发送短信
                        busiType = "ftp_tran_succ4";
                        System.out.println("下发【517】活动券码短信");
                        flag = true;
                    }
                }
                if(!flag) {
                    //业务类型，默认是办理成功
                    busiType = "ftp_tran_succ";
                }
                if("1".equals(type)){//退订
                    busiType = "ftp_cancel_succ"; //退订成功
                }
                map.put("busiType", busiType);
                map.put("style","0000");
                URLUtil.post(url, JSONSerializer.toJSON(map).toString(),

//				URLUtil.post("http://10.199.99.144:8090/mq-service/recive.do", JSONSerializer.toJSON(map).toString(),
                        1000);
                //20211214 修改 新春活动 1214~0228 活动期间内的1017,979,1005产品发送短信
                //20220412 下线，更改配置化，指定产品可发送短信
                if(!"1".equals(type)) {//订购下发
//                    Boolean hasSendCouponSms = channelOrderDao.hasSendCouponSms(userid,orderConfigBean.getSpid());
                    List<String> sendsmsProduct = jiYueOrderDao.querySendSmsProduct();
                    if(sendsmsProduct!=null && sendsmsProduct.contains(orderConfigBean.getSpid())){
                        System.out.println("下发订购后的定制短信");
//                    if(hasSendCouponSms) {
                        map.put("busiType", "ftp_tran_succ3");
                        URLUtil.post(url, JSONSerializer.toJSON(map).toString(), 1000);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String timehandel(Date time){

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日");
        return sdf.format(time);
    }

    public int compareOrderForSdk(HashMap<String, String> data) throws Exception {
        int result = 0;
        SDKOrderInfo orderInfo = null;
        SdkOrderBean oldOrderBean = null;
        try {
            orderInfo = getSdkOrderInfo(data);
            oldOrderBean = this.sdkOrderDao.queryOrderList(orderInfo.getUserid(), orderInfo.getCpid(),
                    orderInfo.getProductId());
            if (oldOrderBean != null) {
                String status = oldOrderBean.getStatus();
                if (status.equals("0")) {
                    throw new BusinessException("9010", "已订购，请不要重复订购", new String[0]);
                }

                if (NumberUtils.toLong(data.get("ORDERTIME")) < NumberUtils.toLong(oldOrderBean.getCanceltime())) {
                    throw new BusinessException("9023", "订购时间晚于本地退订时间不处理", new String[0]);
                }
                orderInfo.setId(oldOrderBean.getId());
                this.sdkOrderDao.order(orderInfo, true);
            } else {
                orderInfo.setId(this.sysDao.getID());
                this.sdkOrderDao.order(orderInfo, false);
            }
            saveSdkLog(orderInfo, "0", "");
            jiYueOrderDao.updataQueryList(data.get("ID"),"0");
        } catch (Exception e) {
            result = 1;
            e.printStackTrace();
            if ((e instanceof BusinessException)) {
                jiYueOrderDao.updataQueryList(data.get("ID"),((BusinessException) e).getCode());
                saveSdkLog(orderInfo, ((BusinessException) e).getCode(), e.getMessage());
            } else {
                jiYueOrderDao.updataQueryList(data.get("ID"),"8000","系统忙！");
                saveSdkLog(orderInfo, "8000", "系统忙！");
            }
        }
        return result;
    }

    public SDKOrderInfo getSdkOrderInfo(HashMap<String, String> data) throws Exception {
        OrderConfigBean orderConfigBean = getOrderConfigBean(data.get("SPID"));
        SDKOrderInfo orderInfo = new SDKOrderInfo();
        orderInfo.setUserid(data.get("USERMOB"));
        orderInfo.setCpid(orderConfigBean.getCpid());
        orderInfo.setProductId(orderConfigBean.getSpid());
        orderInfo.setAppid("40000001");
        orderInfo.setSectionId(orderConfigBean.getSpid());
        orderInfo.setProvince(data.get("PROVINCE"));
        orderInfo.setArea(data.get("AREA"));
        orderInfo.setIsExperience(0);
        orderInfo.setType(1);
        orderInfo.setAppType("");
        if (data.get("TYPE").equals("0")) {
            if (StringUtils.isEmpty(data.get("ORDERTIME"))) {
                throw new BusinessException("9012", "参数错误", new String[0]);
            }
            orderInfo.setOrderTime(DateUtils.parseDate(data.get("ORDERTIME"), new String[] { "yyyyMMddHHmmss" }));
            orderInfo.setOrdertimestr(data.get("ORDERTIME"));
            orderInfo.setOrderChannel("jypt");
            orderInfo.setStatus("0");
            orderInfo.setOrderStatus(3);
        } else {
            if (StringUtils.isEmpty(data.get("CANCELTIME"))) {
                throw new BusinessException("9012", "参数错误", new String[0]);
            }
            orderInfo.setCancelTime(DateUtils.parseDate(data.get("CANCELTIME"), new String[] { "yyyyMMddHHmmss" }));
            orderInfo.setCanceltimestr(data.get("CANCELTIME"));
            orderInfo.setCancelChannel("jypt");
            orderInfo.setStatus("1");
            orderInfo.setOrderStatus(5);
        }
        return orderInfo;
    }

    public void saveSdkLog(SDKOrderInfo orderInfo, String errorcode, String errorinfo) {
        this.sdkOrderDao.insertOrderLog(orderInfo, errorcode, errorinfo, "");
    }

    /**
     * 退订
     * @return
     * @throws Exception
     */
    public int compareCancelForNet(HashMap<String, String> data) throws Exception {
        int result = 0;
        NetOrderBean orderBean = null;
        NetOrderBean oldOrderBean = null;
        try {
            orderBean = getNetOrderInfo(data);
            if("99134246".equals(orderBean.getSpid())){
                throw new BusinessException("9098", "此产品不支持退订！", new String[0]);
            }
            if(changshiBlackDao.isBlackUser(orderBean.getUserid(),orderBean.getCpid())){
                throw new BusinessException("9081", "黑名单用户不处理退订", new String[0]);
            }

            boolean hasnme = false; //是否次月生效
            //能力平台次月生效产品处理流程
            if(nextMonthEffectService.hasNextMonthBusi(orderBean.getSpid())){
                data.put("CPID",orderBean.getCpid());
                data.put("SPID",orderBean.getSpid());
                hasnme = true;
                nextMonthEffectService.process(orderBean);
                //设置同步状态值，用于判断是否生成活动关系
                data.put("SYNCSTATUS",orderBean.getSyncstatus());
            }else{
                oldOrderBean = this.netOrderDao.findOrder(orderBean.getCpid(), orderBean.getSpid(), orderBean.getUserid());
                if (oldOrderBean != null) {
                    /*****************************************************集约平台退订，进行退订渠道更新*************************************************************/
                    if (!"0".equals(oldOrderBean.getStatus())) {
                        if("jypt".equals(orderBean.getCancelchannel()) ){
                            try {
                                //退订渠道优先级更新
                                this.netOrderDao.cancelUpdate(orderBean);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            throw new BusinessException("9099", "[集约平台退订渠道覆盖]已退订，退订渠道更新为jypt", new String[0]);
                        }
                        throw new BusinessException("9006", "已退订，请不要重复退订", new String[0]);
                    }else{
                        if("jypt".equals(orderBean.getCancelchannel()) ){
                            try {
                                if(orderBean.getCanceltime().getTime() < oldOrderBean.getOrdertime().getTime()
                                        && oldOrderBean.getCancelchannel()!=null && !"".equals(oldOrderBean.getCancelchannel().trim())){
                                    //退订渠道优先级更新
                                    this.netOrderDao.cancelUpdate(orderBean);

                                    saveNetLog(orderBean, "9097", "[集约平台退订渠道覆盖]已订购，且集约平台退订时间小于订购时间，退订渠道更新为jypt", data.get("TYPE"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    /*****************************************************集约平台退订，进行退订渠道更新*************************************************************/
                    //只有1150和1040走ECB订购
                    if (orderBean.getCpid().equals("changshi") && ("1150".equals(orderBean.getSpid()) || "1040".equals(orderBean.getSpid()))){
                        // && !"99144185".equals(orderBean.getSpid())
                        // && !"99144186".equals(orderBean.getSpid())
                        // && !"99144187".equals(orderBean.getSpid())) {
                        String discntValue = orderBean.getSpid().equals("1150") ? "1" : "0";
                        EcbProductInfo ecbProductInfo = ecbProductDao.queryEcb(data.get("ID"));
                        List<DiscntInfo> list = changshiDao.queryDiscntInfo(orderBean.getUserid(), discntValue);
                        for (DiscntInfo discntInfo : list) {
                            if (discntInfo.getType().equals("0")
                                    && !discntInfo.getDiscntid().equals(ecbProductInfo.getDiscntCode())) {
                                throw new BusinessException("9011", "不同资费有未退得订购请求，不处理", new String[0]);
                            }
                        }
                        ecbDiscntDao.cancel(ecbProductInfo, orderBean);
                    } else if (NumberUtils.toLong(data.get("CANCELTIME")) < NumberUtils
                            .toLong(oldOrderBean.getOrdertimestr())) {
                        throw new BusinessException("9025", "退订时间晚于本地订购时间不处理", new String[0]);
                    }
                    this.netOrderDao.cancelOrder(orderBean);
                } else {
                    throw new BusinessException("9026", "本地无订购", new String[0]);
                }
            }
            //不是能力平台次月生效产品，或者是能力平台产品且是正式订购关系表退订操作
            if(!hasnme || (hasnme && "5".equals(orderBean.getSyncstatus()))){
                saveNetLog(orderBean, "0", "", data.get("TYPE"));
            }
            if(hasnme){
                jiYueOrderDao.updataQueryList(data.get("ID"),"0","次月生效数据退订完成");
            }else{
                jiYueOrderDao.updataQueryList(data.get("ID"),"0","ok");
            }
        } catch (Exception e) {
            result = 1;
            catchOper(e,data,orderBean);
        }
        return result;
    }

    public int compareCancelForSdk(HashMap<String, String> data) throws SQLException {
        int result = 0;
        SDKOrderInfo orderInfo = null;
        SdkOrderBean oldOrderBean = null;
        try {
            orderInfo = getSdkOrderInfo(data);
            oldOrderBean = this.sdkOrderDao.queryOrderList(orderInfo.getUserid(), orderInfo.getCpid(),
                    orderInfo.getProductId());

            if (oldOrderBean != null) {
                orderInfo.setId(oldOrderBean.getId());
                String status = oldOrderBean.getStatus();
                if (!status.equals("0")) {
                    throw new BusinessException("9006", "已退订，请不要重复退订", new String[0]);
                }

                if (NumberUtils.toLong(data.get("CANCELTIME")) < NumberUtils.toLong(oldOrderBean.getOrdertime())) {
                    throw new BusinessException("9025", "退订时间晚于本地订购时间不处理", new String[0]);
                }
                this.sdkOrderDao.cancelOrder(orderInfo);
            } else {
                throw new BusinessException("9026", "退订失败，本地无订购", new String[0]);
            }
            saveSdkLog(orderInfo, "0", "");
            jiYueOrderDao.updataQueryList(data.get("ID"),"0");
        } catch (Exception e) {
            result = 1;
            e.printStackTrace();
            if ((e instanceof BusinessException)) {
                jiYueOrderDao.updataQueryList(data.get("ID"),((BusinessException) e).getCode());
                saveSdkLog(orderInfo, ((BusinessException) e).getCode(), e.getMessage());
            } else {
                jiYueOrderDao.updataQueryList(data.get("ID"),"8000","系统忙！");
                saveSdkLog(orderInfo, "8000", "系统忙！");
            }
        }
        return result;
    }

    /**
     * 生成领取会员的活动关系
     * @param configBean
     */
    public void insertMqOffline(HashMap<String, String> data, OrderConfigBean configBean) {
        try{
            //20220507增加能力平次月生效处理逻辑
            //不是能力平台次月生效产品，或者是能力平台产品且是正式订购关系表退订操作
            if(nextMonthEffectService.hasNextMonthBusi(data.get("SPID"))){
                if("5".equals(data.get("SYNCSTATUS"))){
                    logger.info("能力平台正式表退订操作，推送到mq生成活动关系");
                }else{
                    logger.info("能力平台非正式表退订操作，不推送到mq");
                    return;
                }
            }
            MessagePipe mpipe = new MessagePipe();
            mpipe.setHeader("orderoffline");
            mpipe.addBody("userid", data.get("USERMOB"));
            mpipe.addBody("province", data.get("PROVINCE"));
            mpipe.addBody("area", data.get("AREA"));
            if (data.get("TYPE").equals("0")) {
                mpipe.addBody("orderType", "0");
                mpipe.addBody("updateTime", data.get("ORDERTIME"));
            } else {
                mpipe.addBody("orderType", "1");
                mpipe.addBody("updateTime", data.get("CANCELTIME"));
            }
            mpipe.addBody("cpid", configBean.getCpid());
            mpipe.addBody("spid", configBean.getSpid());
            mpipe.addBody("channel", "jypt");
            mpipe.addBody("activated", "2");
            this.messageService.sendMessage(mpipe);
        }catch(Exception e){
            e.printStackTrace();
            logger.error("推送队列出现异常，"+e.getMessage());
        }
    }

    public void insertSmsMq(String userid, String channel, OrderConfigBean orderConfigBean) {
        MessagePipe mpipe = new MessagePipe();
        mpipe.setHeader("cssms");
        mpipe.addBody("userid", userid);
        mpipe.addBody("channel", channel);
        mpipe.addBody("cpid", orderConfigBean.getCpid());
        mpipe.addBody("spid", orderConfigBean.getSpid());
        mpipe.addBody("style", "5");
        mpipe.addBody("result", "");
        mpipe.addBody("times", "");
        mpipe.addBody("orderType", "0");
        this.messageService.sendMessage(mpipe);
    }
}
