package com.chinacreator.process.job;

import com.chinacreator.common.exception.BusinessException;
import com.chinacreator.common.util.DESUtil;
import com.chinacreator.common.util.MD5;
import com.chinacreator.common.util.URLUtil;
import com.chinacreator.process.bean.*;
import com.chinacreator.process.dao.*;
import com.chinacreator.process.service.*;
import com.chinacreator.process.util.JsonUtil;
import com.chinacreator.video.queue.MessageService;
import com.chinacreator.video.queue.bean.MessagePipe;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

//import com.chinacreator.process.service.OrderToVipService;

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class ReciveMQJob {

    private Logger log = Logger.getLogger("recivemq");

    private Logger sendviplog = Logger.getLogger("ordersendvip");

    private Logger logger = Logger.getLogger(ReciveMQJob.class);
    @Autowired
    private MessageService messageService;

    @Autowired
    private ActivityConfigDao activityConfigDao;

    @Autowired
    private BlackWhiteDao blackWhiteDao;

    @Autowired
    private CallerAreacodeDao callerAreacodeDao;

    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private ComOrderService comOrderService;

    @Autowired
    private BestvOrderService bestvOrderService;

    @Autowired
    private CctvOrderService cctvOrderService;

    @Autowired
    private AqiyOrderService aqiyOrderService;

    @Autowired
    private AqiyMonthOrderService aqiyMonthOrderService;

    @Autowired
    private ActivityHandleService activityHandleService;

    @Autowired
    private FhGoodsHandleService fhGoodsHandleService;

    @Autowired
    private YoutuOrderService youtuOrderService;

    //@Autowired
    //private OrderToVipService orderToVipService;

    @Autowired
    private OrderSendVipDao orderSendVipDao;

    @Autowired
    private SPDao spDao;

    @Autowired
    private CPDao cpDao;

    public void doProcess() throws Exception {
        logger.info("接收订购队列JOB启动");
        if (dictionaryDao.getValue("recivemq").equals("0")) {
            long beginTime = System.currentTimeMillis();
            List<MessagePipe> list = messageService
                    .reciveBatchMessage("order", 500);
            logger.info("接收订购队列花费时间：" + (System.currentTimeMillis() - beginTime));
            for (MessagePipe messagePipe : list) {
                LogBean logBean = new LogBean();
                try {
                    OrderBean orderBean = transBean(messagePipe.getBody());
                    logBean.setUserid(orderBean.getUserid());
                    logBean.setInputParm(JsonUtil.objectToJson(orderBean));
                    if (StringUtils.isEmpty(orderBean.getProvince())) {
                        AreaInfo areaInfo = callerAreacodeDao.findByCallerhead(orderBean.getUserid().substring(0, 7));
                        if (areaInfo != null) {
                            orderBean.setProvince(areaInfo.getProvince());
                            orderBean.setArea(areaInfo.getArea());
                        }
                    }
                    ActivityConfigBean activityConfigBean = activityConfigDao
                            .findByCallerhead(orderBean.getCpid(),
                                    orderBean.getSpid(), orderBean.getProvince());
                    if (activityConfigBean == null) {
                        throw new BusinessException("9030", "非活动产品或者活动结束");
                    }
                    //设置ActiveType
                    orderBean.setActiveType(activityConfigBean.getActiveType());
                    if (blackWhiteDao.isWhite(orderBean.getUserid())) {//是白名单
                        orderBean.setIsWhite(0);
                    } else {
                        orderBean.setIsWhite(1);
                    }
                    if (orderBean.getOrderType().equals("0")) {
                        if ((NumberUtils.toLong(orderBean.getUpdateTime()) < NumberUtils
                                .toLong(activityConfigBean.getBegintime()) || NumberUtils
                                .toLong(orderBean.getUpdateTime()) > NumberUtils
                                .toLong(activityConfigBean.getEndtime()))
                                && (orderBean.getIsWhite() == 1)) {
                            throw new BusinessException("9031", "非活动产品或者活动结束");
                        }
                    } else {
                        if ((NumberUtils.toLong(orderBean.getUpdateTime()) < NumberUtils
                                .toLong(activityConfigBean.getBegintime()) || NumberUtils
                                .toLong(orderBean.getUpdateTime()) > NumberUtils
                                .toLong(activityConfigBean.getCancelendtime()))
                                && (orderBean.getIsWhite() == 1)) {
                            throw new BusinessException("9032", "非活动产品或者活动结束");
                        }
                    }

                    //获取子业务数据
                    List<OrderBean> subOrderList = this.getSubPorduct(orderBean);
                    if (subOrderList != null && subOrderList.size() > 0) {
                        for (OrderBean bean : subOrderList) {//逐个处理
                            commUpdateHandle(bean);
                        }
                    } else {
                        commUpdateHandle(orderBean);
                    }

                    //订购送会员
                    //if (orderBean.getOrderType().equals("0")) {//订购
                    //orderToVipService.sendVip(orderBean);
                    //}

                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("执行出错：" + logBean.getUserid() + "=>" + e);
                    logBean.setErrorInfo("系统错误");
                    logBean.setResultCode("8000");
                    if (e instanceof BusinessException) {
                        logBean.setErrorInfo(e.getMessage());
                        logBean.setResultCode(((BusinessException) e).getCode());
                    }
                } finally {
                    log.info(JsonUtil.objectToJson(logBean));
                }
            }
        } else {
            logger.info("停止接收队列消息");
        }
    }

    /**
     * 真正业务处理
     *
     * @param orderBean
     * @throws Exception
     */
    public void commUpdateHandle(OrderBean orderBean) throws Exception {
        //添加订购关系是否有异常
        boolean haserror = false;
        try {
            //是复合产品
            if (!StringUtils.isEmpty(orderBean.getFhcpid()) && !StringUtils.isEmpty(orderBean.getFhspid())) {
                //复合产品不重设activeType，走专用通道
                fhGoodsHandleService.handle(orderBean);
            } else {//非复合产品
                //这部分代码不方便去除，因为TB_ACTIVITY_CONFIG表同样的SPID和CPID但ActiveType值可能不一样，比如leshilt952
                if (orderBean.getCpid().equals("bestv") && orderBean.getSpid().equals("980")) {
                    orderBean.setActiveType(4);
                } else if (orderBean.getCpid().equals("changshi") && orderBean.getSpid().equals("1150")) {
                    orderBean.setActiveType(5);
                } else if (orderBean.getCpid().equals("cctv") && orderBean.getSpid().equals("10081")) {
                    orderBean.setActiveType(8);
                } else if (orderBean.getCpid().equals("aiqy") && orderBean.getSpid().equals("1017")) {
                    //orderBean.setActiveType(9);
                } else if (orderBean.getCpid().equals("leshilt") && orderBean.getSpid().equals("952")) {
                    orderBean.setActiveType(13);
                } else if (orderBean.getCpid().equals("aiqy") && orderBean.getSpid().equals("1018")) {
                    orderBean.setActiveType(20);
                }
                
                //生成活动关系入口配置信息
                String activehandle = orderBean.getActivehandle();
                //20210802生成活动关系入口改为配置化
                if(!StringUtils.isEmpty(activehandle)){
                    if(activehandle.indexOf("bestvOrderService") != -1){
                        if (orderBean.getOrderType().equals("0")) {//订购
                            bestvOrderService.order(orderBean);
                        } else {//退订
                            bestvOrderService.cancel(orderBean);
                        }
                    }else  if(activehandle.indexOf("cctvOrderService") != -1){
                    	 cctvOrderService.handle(orderBean);
                    //一般都走这个处理入口
                    }else  if(activehandle.indexOf("aqiyOrderService") != -1){
                    	aqiyOrderService.handle(orderBean);
                    //生成活动关系后要赠送流量的走这个入口
                    }else  if(activehandle.indexOf("youtuOrderService") != -1){
                    	youtuOrderService.handle(orderBean);
                    }else  if(activehandle.indexOf("aqiyMonthOrderService") != -1){
                    	aqiyMonthOrderService.handle(orderBean);
                    }else  if(activehandle.indexOf("activityHandleService") != -1){
                    	activityHandleService.handle(orderBean);
                    }else {//没配置的或者匹配不上的都走公共通道
                        if (orderBean.getOrderType().equals("0")) {//订购
                            comOrderService.order(orderBean);
                        } else {//退订
                            comOrderService.cancel(orderBean);
                        }
                    }
                }else {
                    if (orderBean.getOrderType().equals("0")) {//订购
                        comOrderService.order(orderBean);
                    } else {//退订
                        comOrderService.cancel(orderBean);
                    }
                }

                /****
                switch (orderBean.getActiveType()) {
                    case 4: //bestv 980
                        if (orderBean.getOrderType().equals("0")) {//订购
                            bestvOrderService.order(orderBean);
                        } else {//退订
                            bestvOrderService.cancel(orderBean);
                        }
                        break;
                    case 8:
                        cctvOrderService.handle(orderBean); //cctv 10081
                        break;
                    case 9:
                        aqiyOrderService.handle(orderBean); //aiqy 1017
                        break;
                    case 13:
                        aqiyOrderService.handle(orderBean); //leshilt 952
                        break;
                    case 20:
                        aqiyOrderService.handle(orderBean); //aiqy 1018
                        break;
                    case 12:
                        aqiyOrderService.handle(orderBean); //leshilt 954
                        break;
                    case 16:
                        youtuOrderService.handle(orderBean);//芒果TV16元（mangtv16 1006）
                        break;
                    case 18:
                        aqiyMonthOrderService.handle(orderBean); //aiqy 1017 已失效
                        break;
                    case 21:
                        activityHandleService.handle(orderBean); //youtu 21156
                        break;
                    case 22:
                        youtuOrderService.handle(orderBean);//优酷20元（youtu 1167）
                        break;
                    case 23:
                        aqiyOrderService.handle(orderBean);//华数 （huashuapp 10206）
                        break;
                    case 24:
                        aqiyOrderService.handle(orderBean);//PPTV16元（pptv 10）
                        break;
                    case 25:
                        aqiyOrderService.handle(orderBean);//风行12元
                        break;
                    case 43:
                        aqiyOrderService.handle(orderBean);//sohutv 搜狐18元
                        break;
                    case 45:
                        aqiyOrderService.handle(orderBean);//xueguoxue 学国学12元
                        break;
                    case 46:
                        aqiyOrderService.handle(orderBean);//zmkb 最美课本
                        break;
                    case 82:
                        aqiyOrderService.handle(orderBean);//哔哩哔哩 20
                        break;
                    case 49:
                        aqiyOrderService.handle(orderBean);//cpid:ppsport  spid:36
                        break;
                     case 50:
                        aqiyOrderService.handle(orderBean);//cpid:aiqy  spid:1035
                        break;
                    case 51:
                        aqiyOrderService.handle(orderBean);//cpid:changshi  spid:99144185
                        break;
                    case 52:
                        aqiyOrderService.handle(orderBean);//cpid:mangtv16  spid:1008
                        break;
                    case 53:
                        aqiyOrderService.handle(orderBean);//cpid:aiqy  spid:1017
                        break;
                    case 83:
                        aqiyOrderService.handle(orderBean);
                        break;
                    case 84:
                        aqiyOrderService.handle(orderBean);
                        break;
                    case 85:
                        aqiyOrderService.handle(orderBean);
                        break;
                    case 86:
                        aqiyOrderService.handle(orderBean);
                        break;
                    case 87:
                        aqiyOrderService.handle(orderBean);
                        break;
                    case 88:
                        aqiyOrderService.handle(orderBean);
                        break;
                    default:
                        if (orderBean.getOrderType().equals("0")) {//订购
                            comOrderService.order(orderBean);
                        } else {//退订
                            comOrderService.cancel(orderBean);
                        }
                        break;
                }
                
                *****/
            }
        } catch (Exception e) {
            haserror = true;
            throw e;
        } finally {
            //添加成功，走实时送会员流程
            if (!haserror) {
            	/***
                if (straightBoolean(orderBean)) {
                    logger.info("芒果活动会员直充开始");
                    invokeVip(orderBean);
                    logger.info("芒果活动会员直充结束");
                } else {***/
                	//根据渠道和SPID送会员，走会员领取接口
                    sendVip(orderBean);
                    //爱奇艺1017送两个会员，走直充接口
                    //sendQiqyVip(orderBean);
                    //走直充送会员
                    sendVipByZc(orderBean);
                //}
            }
        }
    }

    /**
     * 芒果会员直充资格判断
     *
     * @param orderBean
     * @return
     */
    public boolean straightBoolean(OrderBean orderBean) throws Exception {
        logger.info("队列数据:" + orderBean.toString());
        try {
            //渠道判断
            String channel = orderBean.getChannel();
            //渠道为空，或不是以WP_开头，不处理
            if (StringUtils.isEmpty(channel) || !channel.startsWith("WP_")) {
                return false;
            }
            String straightTime = dictionaryDao.getValue("straightTime");
            logger.info("字典表中获取的数据:" + straightTime);
            String[] split = straightTime.split(",");
            //spid判断
            if (!split[0].equals(orderBean.getSpid())) {
                logger.info("芒果会员参数1" + !split[0].equals(orderBean.getSpid()));
                return false;
            }
            //复合产品，验证的是子产品的SPID，不处理
            if (!StringUtils.isEmpty(orderBean.getFhcpid()) && !StringUtils.isEmpty(orderBean.getFhspid())) {
            	return false;
            }
            //时间判断
            String[] time = split[1].split("\\|");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            long startTime = sdf.parse(time[0]).getTime();
            long endTime = sdf.parse(time[1]).getTime();
            long nowTime = sdf.parse(orderBean.getUpdateTime()).getTime();
            if (nowTime < startTime || nowTime > endTime) {

                logger.info("芒果会员参数2" + (nowTime < startTime || nowTime > endTime));
                return false;
            }
            logger.info("芒果会员参数3" + "0".equals(orderBean.getOrderType()));
            //判断是否订购
            return "0".equals(orderBean.getOrderType());
        } catch (Exception e) {
            logger.info("芒果活动会员直充出错");
            e.printStackTrace();
            return false;
        }

    }

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

    /**
     * 判断是否复合产品，获取可赠送会员的子业务列表
     *
     * @param orderBean
     * @return
     * @throws Exception
     */
    private List<OrderBean> getSubPorduct(OrderBean orderBean) throws Exception {
        List<OrderBean> resultData = new ArrayList<OrderBean>();
        try {
            //查询是否复合产品
            List<HashMap> fhGoods = spDao.getFhGoods(orderBean.getSpid());
            if (fhGoods.size() > 0) {//复合产品
                logger.info("是复合产品");
                //获取子业务列表
                List<HashMap> reList = spDao.getSubSpInfo(orderBean.getSpid());
                if (reList != null && reList.size() > 0) {
                    logger.info(orderBean.getCpid() + ">>>" + orderBean.getSpid() + ",子业务数据条数为：" + reList.size());
                    for (HashMap hm : reList) {//遍历子业务列表
                        resultData.add(cloneBean(orderBean, hm.get("CPID") + "", hm.get("SPID") + ""));
                        logger.info("要处理的子业务：" + hm.get("CPID") + ">>>" + hm.get("SPID"));
                    }
                } else {
                    throw new BusinessException("9061", "复合产品无子业务配置");
                }
                logger.info("要处理的子业务条数：" + resultData.size());
            } else {//非复合产品
                logger.info("不是复合产品");
            }
        } catch (SQLException e) {
            throw new BusinessException("9060", "查询子产品出现异常，" + e.getMessage());
        }
        return resultData;
    }

    /**
     * 克隆对象
     *
     * @param orderBean
     * @param subCpid   子产品CPID
     * @param subSpid   子产品SPID
     * @return
     */
    private OrderBean cloneBean(OrderBean orderBean, String subCpid, String subSpid) {
        OrderBean bean = new OrderBean();
        bean.setFhcpid(orderBean.getCpid());
        bean.setFhspid(orderBean.getSpid());
        bean.setCpid(subCpid);
        bean.setSpid(subSpid);
        bean.setUserid(orderBean.getUserid());
        bean.setOrderType(orderBean.getOrderType());
        bean.setOrderstatus(orderBean.getOrderType());
        bean.setProvince(orderBean.getProvince());
        bean.setArea(orderBean.getArea());
        bean.setUpdateTime(orderBean.getUpdateTime());
        bean.setActivated(orderBean.getActivated());

        if ("0".equals(orderBean.getOrderType())) {//y订购
            bean.setOrderchannel(orderBean.getChannel());
            bean.setOrdertime(orderBean.getUpdateTime());
            bean.setOrderstatus("0");
        } else {//退订
            bean.setCanceltime(orderBean.getUpdateTime());
            bean.setCancelchannel(orderBean.getChannel());
            bean.setOrderstatus("1");
        }

        //使用复合产品的activeType
        bean.setActiveType(orderBean.getActiveType());

        return bean;
    }

    /**
     * 实时送会员
     *
     * @param orderBean
     */
    private void sendVip(OrderBean orderBean) {
        //只处理订购
        if (!"0".equals(orderBean.getOrderType())) return;
        //复合产品，生成活动关系时是每个子业务一条活动关系，验证的是子产品的SPID，不处理
        if (!StringUtils.isEmpty(orderBean.getFhcpid()) && !StringUtils.isEmpty(orderBean.getFhspid())) {
        	return;
        }
        boolean flag = false;
        long startime = System.currentTimeMillis();
        Map logMap = new HashMap();
        logMap.put("data", orderBean);
        String resultcode = "-1";
        String errorinfo = "";
        String sendno = ""; //赠送记录表的ID，用于更新数据
        boolean hassend = false; //是否赠送
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String currtime = sdf.format(new Date()); //当前时间
            String userid = orderBean.getUserid();
            String cpid = orderBean.getCpid();
            String spid = orderBean.getSpid();
            String orderchannel = orderBean.getOrderchannel();
            //手厅传的渠道标识与订购疯关系表不相同
            String channel = orderBean.getChannel();
            //String sendmonth = ""; //赠送月份
            String ordertime = ""; //订购时间
            List<HashMap> confList = orderSendVipDao.qryOrderSendvipConf(cpid, spid);
            if (confList != null && confList.size() > 0) {
                if (StringUtils.isEmpty(orderchannel) && StringUtils.isEmpty(channel)){
                	throw new BusinessException("5006", "订购渠道为空，orderchannel=>"+orderchannel);
                }
                List<HashMap> orderList = orderSendVipDao.findOrderRel(userid, spid);
                if (orderList != null && orderList.size() > 0) {
                    HashMap orderMap = orderList.get(0);
                    //sendmonth = orderMap.get("ORDERTIME").toString().substring(0, 6);
                    ordertime = orderMap.get("ORDERTIME").toString();
                    //如果订购渠道为空，从订购关系中获取订购渠道
                    //if (StringUtils.isEmpty(orderchannel)) {
                        //orderchannel = (String) orderMap.get("ORDERCHANNEL");
                    //}
                    if( orderchannel != null && channel != null 
                    		&& !orderchannel.equals(orderMap.get("ORDERCHANNEL"))                   		
                    		&& !channel.equals(orderMap.get("ORDERCHANNEL"))){
                    	throw new BusinessException("5005", "渠道与订购关系表的渠道不一致，orderchannel=>"+orderchannel);
                    }

                    logMap.put("orderchannel", orderchannel);
                    logMap.put("channel", channel);
                    
                    String confChannel = "";
                    String starttime = "";
                    String endtime = "";
                    //判断订购渠道是否有配置
                    for (HashMap confMap : confList) {
                    	flag = false;
                    	starttime = (String)confMap.get("STARTTIME");
                    	endtime = (String)confMap.get("ENDTIME");
                    	confChannel = confMap.get("CHANNEL").toString().trim();
                    	//订购渠道与配置渠道相同，或者配置渠道不限制
                        if (confChannel.equals(orderchannel) 
                        		|| confChannel.equals(channel) 
                        		|| "*".equals(confChannel)
                        		//配置渠道以指定字符开头且订购渠道是以指定渠道开头，芒果16元      
                        		|| (confChannel.indexOf("*") != -1  && orderchannel != null && orderchannel.indexOf(confChannel.split("\\*")[0]) == 0)
                        		|| (confChannel.indexOf("*") != -1  && channel != null && channel.indexOf(confChannel.split("\\*")[0]) == 0)) {
                        	/**************************判断时间是否合法开始************************/
                        	//开始时间和结束时间都不为空且当前时间包含在两者之间
                        	if (!StringUtils.isEmpty(starttime) && !StringUtils.isEmpty(endtime)
                        		&& Long.parseLong(currtime) >= Long.parseLong(starttime.trim()) 
                        		&& Long.parseLong(currtime) <= Long.parseLong(endtime.trim())){
                        		flag = true;
                        		break;
                        	//开始时间不为空，结束时间为空，当前时间大于或等于开始时间
                        	}else if (!StringUtils.isEmpty(starttime) && StringUtils.isEmpty(endtime)
                        			&& Long.parseLong(currtime) >= Long.parseLong(starttime.trim())){
                        		flag = true;
                        		break;
                        	//开始时间为空，结束时间不为空，当前时间小于或等于结束时间
                        	}else if (StringUtils.isEmpty(starttime) && !StringUtils.isEmpty(endtime)
                        			&& Long.parseLong(currtime) <= Long.parseLong(endtime.trim())){
                        		flag = true;
                        		break;
                        	//开始时间为空且结束时间也为空
                        	}else if (StringUtils.isEmpty(starttime) && StringUtils.isEmpty(endtime)){
                        		flag = true;
                        		break;                        		
                        	}else{
                        		 throw new BusinessException("5004", "当前时间未包含在配置时间内");
                        	} 
                        	/**************************判断时间是否合法结束************************/
                        }
                    }    
                    //订购渠道有配置
                    if (flag) {
                        //logMap.put("sendmonth", sendmonth);
                        logMap.put("ordertime", ordertime);
                        logMap.put("status", orderMap.get("STATUS"));
                        if ("0".equals(orderMap.get("STATUS")) || "1".equals(orderMap.get("STATUS"))) {
                            hassend = true;
                            sendno = orderSendVipDao.getNo();
                            logMap.put("sendno", sendno);
                            HashMap<String, String> params = new HashMap<String, String>();
                            params.put("ID", sendno);
                            params.put("USERID", userid);
                            params.put("CPID", cpid);
                            params.put("SPID", spid);
                            //params.put("SENDMONTH", sendmonth);
                            params.put("RESULTCODE", "2");
                            params.put("RESULTINFO", "赠送中");
                            params.put("ORDERTIME", ordertime);
                            params.put("ORDERCHANNEL", orderchannel);
                            orderSendVipDao.addSendvipRec(params);
                            String result = invokeVip(orderBean);
                            logMap.put("result", result);
                            if (result != null && !"".equals(result)) {
                                Map<?, ?> map = JsonUtil.jsonToMap(result);
                                resultcode = (String) map.get("resultcode");
                                errorinfo = (String) map.get("errorinfo");
                            }
                        } else {
                            throw new BusinessException("5002", "订购关系已失效");
                        }
                    } else {
                        throw new BusinessException("5003", "非指定渠道，" + orderchannel);
                    }
                } else {
                    throw new BusinessException("5001", "无订购关系");
                }
            }
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                errorinfo = ((BusinessException) e).getMessage();
                resultcode = ((BusinessException) e).getCode();
            } else {
                e.printStackTrace();
                resultcode = "8000";
                errorinfo = "处理数据出现异常，" + e.getMessage();
                sendviplog.error("处理出现异常，" + e.getMessage() + "，data: " + JsonUtil.objectToJson(orderBean));
            }
        } finally {
            if (hassend) {
                try {
                    if (errorinfo != null && errorinfo.length() > 500) {
                        errorinfo = errorinfo.substring(0, 500);
                    }
                    boolean updRes = orderSendVipDao.updatePush(sendno, resultcode, errorinfo);
                    sendviplog.info("updRes=>" + updRes);
                } catch (Exception e2) {
                    e2.printStackTrace();
                    errorinfo = "更新领取结果出现异常，" + e2.getMessage();
                    sendviplog.error(errorinfo);
                }
            }
            //写日志
            logMap.put("hassend", hassend);
            logMap.put("resultcode", resultcode);
            logMap.put("errorinfo", errorinfo);
            logMap.put("time", (System.currentTimeMillis() - startime) + "");
            sendviplog.info(JsonUtil.objectToJson(logMap));
        }
    }

    /**
     * 调接口送会员
     *
     * @param
     * @return
     * @throws Exception
     */
    private String invokeVip(OrderBean orderBean) throws Exception {
        String result = "";
        try {
            String vipurl = this.dictionaryDao.getValue("joinActivityUrl");
            String timestamp = (System.currentTimeMillis() / 1000) + "";
            String userid = orderBean.getUserid();
            String channel = orderBean.getChannel();
            String usertype = "4"; //会员账号类型	4：手机号
            String userval = userid;
            String pwd = "";
            CPInfo cpinfo = cpDao.findById(orderBean.getCpid());
            if (cpinfo != null) {
                pwd = cpinfo.getNetpwd();
            }
            userid = DESUtil.encode(userid, pwd);
            String signature = MD5.MD5Encode(userid + userval + pwd + timestamp);
            signature = signature.toLowerCase();
            vipurl = vipurl + "?userid=" + URLEncoder.encode(userid, "utf-8") + "&usertype=" + usertype + "&userval=" + userval + "&channel=" + channel + "&timestamp="
                    + timestamp + "&signature=" + signature + "&activetype=" + orderBean.getActiveType();
            sendviplog.info("vipurl: " + vipurl);
            result = URLUtil.get(vipurl, 30 * 1000); //调赠送会员接口，超时时间设置为10秒
            sendviplog.info("赠送会员结果=> userid: " + userval + ", spid: " + orderBean.getSpid() + " , result: " + result);
        } catch (Exception e) {
            e.printStackTrace();
            sendviplog.error("userid: " + orderBean.getUserid() + "赠送会员出现异常，" + e);
            if (e.getMessage() != null && e.getMessage().indexOf("TimeoutException") != -1) {//超时异常
                throw new BusinessException("9070", "赠送会员超时", new String[0]);
            } else {
                throw new BusinessException("9002", "赠送会员未成功，" + e.getMessage(), new String[0]);
            }
        }

        return result;
    }
    
    
    /**
     * 调直充接口送会员
     * @param
     * @return
     * @throws Exception
     */
    private String invokeVipByZc(OrderBean orderBean, HashMap confmp) throws Exception {
        String result = "";
        try {
            String basevipurl = this.dictionaryDao.getValue("giveVipUrl");
            
            String vipurl = basevipurl;
            
            String apptype = "2";
            String orderid = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
            String timestamp = System.currentTimeMillis() + "";
            String userid = orderBean.getUserid();
            String channel = orderBean.getSpid(); //渠道传SPID
            String usertype = "4"; //会员账号类型	4：手机号
            String userval = userid;
            String vipid = confmp.get("VIPID").toString();
            String viptype = confmp.get("VIPTYPE").toString();
            String pwd = confmp.get("VIPPWD").toString();
            String vipval = "1";
            String signature = MD5.MD5Encode(orderid+channel+vipid+userval+pwd+timestamp);
            signature = signature.toLowerCase();
            
            //直充接口新参数
            //产品名称
            String productName = URLEncoder.encode(confmp.get("PRODUCTNAME") == null ? "" : confmp.get("PRODUCTNAME").toString(),"utf-8");
            //产品ID
            String productId = confmp.get("PRODUCTID") == null ? "" : confmp.get("PRODUCTID").toString();
            //订购状态，0订购，1退订
            String orderType = orderBean.getOrderType();
            
            vipurl = vipurl + "?userval=" + URLEncoder.encode(userval,"utf-8") + "&usertype=" + usertype + "&channel=" + channel + "&timestamp="
                    + timestamp + "&signature=" + signature + "&orderid=" + orderid + "&viptype=" + viptype + "&vipid=" + vipid + "&vipval="+vipval + "&apptype=" + apptype
                    + "&productName="+productName + "&productId=" + productId + "&orderType=" + orderType;
            sendviplog.info("vipurl: " + vipurl);
            //第一次直充会员
            result = URLUtil.get(vipurl, 30 * 1000); //调赠送会员接口，超时时间设置为10秒
            sendviplog.info("爱奇异第一次直充会员结果=> userid: " + userval + ", spid: " + orderBean.getSpid() + " , result: " + result);
        } catch (Exception e) {
            e.printStackTrace();
            sendviplog.error("userid: " + orderBean.getUserid() + "赠送会员出现异常，" + e);
            if (e.getMessage() != null && e.getMessage().indexOf("TimeoutException") != -1) {//超时异常
                throw new BusinessException("9070", "赠送会员超时", new String[0]);
            } else {
                throw new BusinessException("9002", "赠送会员未成功，" + e.getMessage(), new String[0]);
            }
        }

        return result;
    }
    
    
    /**
     * 1017 aiqy WO+视频爱奇艺定向流量包月
     * 活动时间上线时间12月17日——12月30日（晚间下线）
     * 活动上线之后用户订购，直接充值两个爱奇艺7日会员。退订再订购也直充
	 * 如果用户在活动上线前已经完成订购，需要通过退订再订购触发直充会员
     * @param orderBean
     * @return
     */
    /***
    private String sendQiqyVip(OrderBean orderBean){
        String result = "";
        try {
            //只处理1017的订购
            if(!"1017".equals(orderBean.getSpid()) || !"0".equals(orderBean.getOrderType())){
            	return "非指定产品或者非订购操作";
            }
        	if (!StringUtils.isEmpty(orderBean.getFhcpid()) && !StringUtils.isEmpty(orderBean.getFhspid())) {
        		return "复合产品，不赠送";
        	}
            String currTime = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
            String offlinetime = this.dictionaryDao.getValue("aiqy15vipendtime");
            if(Long.parseLong(currTime) > Long.parseLong(offlinetime)){
            	return "活动已过期";
            }
            
            String basevipurl = this.dictionaryDao.getValue("giveVipUrl");
            
            String vipurl = basevipurl;
            
            String apptype = "2";
            String orderid = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
            String timestamp = System.currentTimeMillis() + "";
            String userid = orderBean.getUserid();
            String channel = orderBean.getSpid(); //渠道传SPID
            String usertype = "4"; //会员账号类型	4：手机号
            String userval = userid;
            String vipid = "00501";
            String viptype = "aiqyVip";
            String pwd = "ahd7aqy2";
            String vipval = "1";
            String signature = MD5.MD5Encode(orderid+channel+vipid+userval+pwd+timestamp);
            signature = signature.toLowerCase();
            vipurl = vipurl + "?userval=" + URLEncoder.encode(userval,"utf-8") + "&usertype=" + usertype + "&channel=" + channel + "&timestamp="
                    + timestamp + "&signature=" + signature + "&orderid=" + orderid + "&viptype=" + viptype + "&vipid=" + vipid + "&vipval="+vipval + "&apptype=" + apptype;
            sendviplog.info("vipurl: " + vipurl);
            //第一次直充会员
            result = URLUtil.get(vipurl, 30 * 1000); //调赠送会员接口，超时时间设置为10秒
            sendviplog.info("爱奇异第一次直充会员结果=> userid: " + userval + ", spid: " + orderBean.getSpid() + " , result: " + result);
            
            //第二次直充会员
            vipurl = basevipurl;
            orderid = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
            timestamp = System.currentTimeMillis() + "";
            signature = MD5.MD5Encode(orderid+channel+vipid+userval+pwd+timestamp);
            vipurl = vipurl + "?userval=" + URLEncoder.encode(userval,"utf-8") + "&usertype=" + usertype + "&channel=" + channel + "&timestamp="
                    + timestamp + "&signature=" + signature + "&orderid=" + orderid + "&viptype=" + viptype + "&vipid=" + vipid + "&vipval="+vipval + "&apptype=" + apptype;
            sendviplog.info("vipurl: " + vipurl);
            result = URLUtil.get(vipurl, 30 * 1000); //调赠送会员接口，超时时间设置为10秒
            sendviplog.info("爱奇异第二次直充会员结果=> userid: " + userval + ", spid: " + orderBean.getSpid() + " , result: " + result);
        } catch (Exception e) {
            e.printStackTrace();
            result =  "赠送会员异常，"+e.getMessage();   
            sendviplog.info("爱奇异直充会员出现异常："+result+"，userid："+orderBean.getUserid());
        }
        
        return result;
    }    
    ******/
    
    /**
     * 直充方式送会员
     * @param orderBean
     * @return
     */
    /**
     * 实时送会员
     *
     * @param orderBean
     */
    private void sendVipByZc(OrderBean orderBean) {
        //只处理订购
        if (!"0".equals(orderBean.getOrderType())) return;
        //复合产品，生成活动关系时是每个子业务一条活动关系，验证的是子产品的SPID，不处理
        if (!StringUtils.isEmpty(orderBean.getFhcpid()) && !StringUtils.isEmpty(orderBean.getFhspid())) {
        	return;
        }
        boolean flag = false;
        long startime = System.currentTimeMillis();
        Map logMap = new HashMap();
        logMap.put("data", orderBean);
        String resultcode = "-1";
        String errorinfo = "";
        String sendno = ""; //赠送记录表的ID，用于更新数据
        boolean hassend = false; //是否赠送
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String currtime = sdf.format(new Date()); //当前时间
            String userid = orderBean.getUserid();
            String cpid = orderBean.getCpid();
            String spid = orderBean.getSpid();
            String orderchannel = orderBean.getOrderchannel();
            //手厅传的渠道标识与订购疯关系表不相同
            String channel = orderBean.getChannel();
            //String sendmonth = ""; //赠送月份
            String ordertime = ""; //订购时间
            List<HashMap> confList = orderSendVipDao.qryOrderSendvipConfByZc(cpid, spid);
            if (confList != null && confList.size() > 0) {
                if (StringUtils.isEmpty(orderchannel) && StringUtils.isEmpty(channel)){
                	throw new BusinessException("5006", "订购渠道为空，orderchannel=>"+orderchannel);
                }
                //sendviplog.info("confList=>"+confList);
                List<HashMap> orderList = orderSendVipDao.findOrderRel(userid, spid);
                if (orderList != null && orderList.size() > 0) {
                    HashMap orderMap = orderList.get(0);
                    ordertime = orderMap.get("ORDERTIME").toString();
                    if( orderchannel != null && channel != null 
                    		&& !orderchannel.equals(orderMap.get("ORDERCHANNEL"))                   		
                    		&& !channel.equals(orderMap.get("ORDERCHANNEL"))){
                    	throw new BusinessException("5005", "渠道与订购关系表的渠道不一致，orderchannel=>"+orderchannel);
                    }

                    logMap.put("orderchannel", orderchannel);
                    logMap.put("channel", channel);
                    
                    String confChannel = "";
                    String starttime = "";
                    String endtime = "";
                    
                    HashMap cm = null;
                    //判断订购渠道是否有配置
                    for (HashMap confMap : confList) {
                    	flag = false;
                    	starttime = (String)confMap.get("STARTTIME");
                    	endtime = (String)confMap.get("ENDTIME");
                    	confChannel = confMap.get("CHANNEL").toString().trim();
                    	//订购渠道与配置渠道相同，或者配置渠道不限制
                        if (confChannel.equals(orderchannel) 
                        		|| confChannel.equals(channel) 
                        		|| "*".equals(confChannel)
                        		//配置渠道以指定字符开头且订购渠道是以指定渠道开头，芒果16元      
                        		|| (confChannel.indexOf("*") != -1  && orderchannel != null && orderchannel.indexOf(confChannel.split("\\*")[0]) == 0)
                        		|| (confChannel.indexOf("*") != -1  && channel != null && channel.indexOf(confChannel.split("\\*")[0]) == 0)) {
                        	/**************************判断时间是否合法开始************************/
                        	//开始时间和结束时间都不为空且当前时间包含在两者之间
                        	if (!StringUtils.isEmpty(starttime) && !StringUtils.isEmpty(endtime)
                        		&& Long.parseLong(currtime) >= Long.parseLong(starttime.trim()) 
                        		&& Long.parseLong(currtime) <= Long.parseLong(endtime.trim())){
                        		flag = true;
                        		cm = confMap;
                        		break;
                        	//开始时间不为空，结束时间为空，当前时间大于或等于开始时间
                        	}else if (!StringUtils.isEmpty(starttime) && StringUtils.isEmpty(endtime)
                        			&& Long.parseLong(currtime) >= Long.parseLong(starttime.trim())){
                        		flag = true;
                        		cm = confMap;
                        		break;
                        	//开始时间为空，结束时间不为空，当前时间小于或等于结束时间
                        	}else if (StringUtils.isEmpty(starttime) && !StringUtils.isEmpty(endtime)
                        			&& Long.parseLong(currtime) <= Long.parseLong(endtime.trim())){
                        		flag = true;
                        		cm = confMap;
                        		break;
                        	//开始时间为空且结束时间也为空
                        	}else if (StringUtils.isEmpty(starttime) && StringUtils.isEmpty(endtime)){
                        		flag = true;
                        		cm = confMap;
                        		break;                        		
                        	}else{
                        		 //sendviplog.info("starttime=>"+starttime+", endtime=>"+endtime+", currtime=>"+currtime);
                        		 throw new BusinessException("5004", "当前时间未包含在配置时间内");
                        	} 
                        	/**************************判断时间是否合法结束************************/
                        }
                    }    
                    //订购渠道有配置
                    if (flag) {
                        //logMap.put("sendmonth", sendmonth);
                        logMap.put("ordertime", ordertime);
                        logMap.put("status", orderMap.get("STATUS"));
                        if ("0".equals(orderMap.get("STATUS")) || "1".equals(orderMap.get("STATUS"))) {
                            hassend = true;
                            sendno = orderSendVipDao.getNo();
                            logMap.put("sendno", sendno);
                            HashMap<String, String> params = new HashMap<String, String>();
                            params.put("ID", sendno);
                            params.put("USERID", userid);
                            params.put("CPID", cpid);
                            params.put("SPID", spid);
                            //params.put("SENDMONTH", sendmonth);
                            params.put("RESULTCODE", "2");
                            params.put("RESULTINFO", "赠送中");
                            params.put("ORDERTIME", ordertime);
                            params.put("ORDERCHANNEL", orderchannel);
                            orderSendVipDao.addSendvipRec(params);
                            String result = invokeVipByZc(orderBean, cm);
                            logMap.put("result", result);
                            if (result != null && !"".equals(result)) {
                                Map<?, ?> map = JsonUtil.jsonToMap(result);
                                resultcode = (String) map.get("resultcode");
                                errorinfo = (String) map.get("errorinfo");
                            }
                        } else {
                            throw new BusinessException("5002", "订购关系已失效");
                        }
                    } else {
                        throw new BusinessException("5003", "非指定渠道，" + orderchannel);
                    }
                } else {
                    throw new BusinessException("5001", "无订购关系");
                }
            }
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                errorinfo = ((BusinessException) e).getMessage();
                resultcode = ((BusinessException) e).getCode();
            } else {
                e.printStackTrace();
                resultcode = "8000";
                errorinfo = "处理数据出现异常，" + e.getMessage();
                sendviplog.error("处理出现异常，" + e.getMessage() + "，data: " + JsonUtil.objectToJson(orderBean));
            }
        } finally {
            if (hassend) {
                try {
                    if (errorinfo != null && errorinfo.length() > 500) {
                        errorinfo = errorinfo.substring(0, 500);
                    }
                    boolean updRes = orderSendVipDao.updatePush(sendno, resultcode, errorinfo);
                    sendviplog.info("updRes=>" + updRes);
                } catch (Exception e2) {
                    e2.printStackTrace();
                    errorinfo = "更新领取结果出现异常，" + e2.getMessage();
                    sendviplog.error(errorinfo);
                }
            }
            //写日志
            logMap.put("hassend", hassend);
            logMap.put("resultcode", resultcode);
            logMap.put("errorinfo", errorinfo);
            logMap.put("time", (System.currentTimeMillis() - startime) + "");
            sendviplog.info(JsonUtil.objectToJson(logMap));
        }
    } 
}
