package com.chinacreator.process.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinacreator.common.exception.BusinessException;
import com.chinacreator.common.util.DESUtil;
import com.chinacreator.common.util.MD5;
import com.chinacreator.process.bean.ChannelOrderBean;
import com.chinacreator.process.bean.OrderConfigBean;
import com.chinacreator.process.dao.CsmakeupDao;
import com.chinacreator.process.dao.DictionaryDao;
import com.chinacreator.process.util.DesUtil;
import com.chinacreator.process.util.HttpInvoke;
import com.chinacreator.process.util.JsonUtil;
import com.chinacreator.video.queue.MessageService;
import com.chinacreator.video.queue.bean.MessagePipe;
import net.sf.json.JSONArray;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 指定四个畅视产品订购和退订成功后调拓维的C+会员接口同步订购关系
 *
 * @author zhengrong.yan
 * @date 20200911
 */
///update 新增产品加新增字段（传递退订时间等）
			/*
			畅视随心选会员包               99144185
			畅视随心选定向流量会员包（前向） 99144186
			畅视随心选定向流量尊享包（前向） 99144187
			99134262  畅视随心选定向流量会员+PP视频会员包  20210114 新添加
		 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class ChangshiPushMQJob {

    private Logger logger = Logger.getLogger("changshicj");

    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private MessageService messageService;

    @Autowired
    private CsmakeupDao csmakeupDao;

    public void doProcess() throws Exception {
        logger.info("指定四个畅视产品订购和退订成功后调拓维的C+会员接口同步订购关系推送消息队列JOB启动");
        if (dictionaryDao.getValue("recivemq").equals("0")) {
            long beginTime = System.currentTimeMillis();
            List<MessagePipe> list = messageService.reciveBatchMessage("changshicj", 500);
            logger.info("接收消息队列花费时间：" + (System.currentTimeMillis() - beginTime));
            List<Map> dataList = new ArrayList<Map>();
            for (MessagePipe messagePipe : list) {
                Map reqBean = transBean(messagePipe.getBody());
                dataList.add(reqBean);
            }
            if (dataList != null && dataList.size() > 0) {
                logger.info("待处理数据条数：" + dataList.size());
                for (Map reqBean : dataList) {
                    this.handleOrder(reqBean);
                }
            }
        } else {
            logger.info("停止接收队列消息");
        }
    }

    /**
     * 业务处理
     *
     * @param mqBean
     */
    public void handleOrder(Map reqBean) {
        Map logMap = new HashMap();
        logMap.put("data", reqBean);
        long starttime = System.currentTimeMillis();
        String resultCode = "-1";
        String resultInfo = "";
        try {
            //调拓维C+接口
            tuoweiInvoke(reqBean);
            resultCode = "0";
            resultInfo = "执行成功";
        } catch (Exception e) {
            e.printStackTrace();
            resultCode = "8000";
            resultInfo = "系统错误，" + e.getMessage();
            logger.error("同步订购关系出现异常，" + e.getMessage());
        } finally {
            //写日志
            logMap.put("time", System.currentTimeMillis() - starttime);
            logMap.put("reusltCode", resultCode);
            logMap.put("resultInfo", resultInfo);
            logger.info(JsonUtil.objectToJson(logMap));
        }
    }

    /**
     * 解析数据
     *
     * @param body orderId TD_POINTS_ORDER_REC表ID字段，我方生成的订单流水号
     *             orderNo 积分商城订单号
     *             requestId 返回给客户的请求ID
     * @return
     */
    public Map transBean(Map<String, Object> body) {
        String jsonStr = JsonUtil.objectToJson(body);
        return (Map) JsonUtil.jsonToBean(jsonStr, Map.class);
    }

    /**
     * 获取请求属性性
     *
     * @return
     */
    private static Map getProperty(String updatetype) {
        Map reqProperty = new HashMap();
        if ("0".equals(updatetype)) {//订购
            reqProperty.put("Content-type", "application/json;charset=utf-8");
        } else {//退订
            reqProperty.put("Content-type", "application/x-www-form-urlencoded");
        }

        return reqProperty;
    }

    /**
     * 增加拓维C+接口
     *
     * @param orderBean
     */
    private void tuoweiInvoke(Map reqBean) throws Exception {
        boolean hasrec = false;
        long starttime = System.currentTimeMillis();
        HashMap params = new HashMap();
        try {

            List<HashMap> confList = csmakeupDao.getBusiConf(reqBean.get("spid").toString());//spid过滤数据
            if (confList != null && confList.size() > 0) {
                hasrec = true;
                HashMap conf = confList.get(0);
                conf.put("SENO", csmakeupDao.getNo()); //获取业务流水号
                params.put("SENO", conf.get("SENO")); //获取业务流水号
                params.put("CHANNEL", "JOB-changshicj");
                params.put("USERID", reqBean.get("userid"));
                params.put("PROVINCE", reqBean.get("province"));
                params.put("AREA", reqBean.get("area"));
                params.put("VIPRECODE", "-1");
                params.put("VIPREINFO", "");
                params.put("RESULTCODE", "0");
                params.put("RESULTINFO", "ok");
                params.put("STATUS", "0");
                params.put("MUSPID", conf.get("MUSPID"));
                if ("1".equals(reqBean.get("type"))) {//0 订购 1 退订
                    params.put("STATUS", "1");
                }
                params.put("CPID", conf.get("CPID"));
                String result = invokeTwvip(reqBean, conf); //调拓维会员接口返回结果
                if (!"".equals(result)) {
                    params.put("VIPRECODE", JSON.parseObject(result).get("code").toString());
                    //params.put("VIPREINFO", JSON.parseObject(result).get("message").toString());
                    params.put("VIPREINFO", result);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("调拓维C+接口出现异常，" + e.getMessage());
            params.put("VIPRECODE", "8000");
            params.put("VIPREINFO", e.getMessage());
            params.put("RESULTCODE", "8000");
            params.put("RESULTINFO", "调拓维C+会员接口异常，" + e.getMessage());
            throw e;
        } finally {
            if (hasrec) {
                try {
                    String vipreinfo = (String) params.get("VIPREINFO");
                    if (vipreinfo != null && vipreinfo.length() > 500) {
                        params.put("VIPREINFO", vipreinfo.subSequence(0, 450));
                    }
                    params.put("TIMES", System.currentTimeMillis() - starttime);
                    csmakeupDao.addOrderRec(params);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("拓维C+接口添加订购记录出现异常，" + e.getMessage());
                }
            }
        }
    }


    /**
     * 调拓维会员接口
     *
     * @param orderBean
     * @param conf
     * @return
     * @throws Exception
     */
    private String invokeTwvip(Map orderBean, HashMap conf) throws Exception {
        String result = ""; //调拓维会员接口返回结果
        String vipurl = "";
        String jsonParams = "";
        if ("1".equals(orderBean.get("type"))) {//退订
            vipurl = dictionaryDao.getValue("csmakeupvipcancelurl");
            jsonParams = this.fullCancelParams(orderBean.get("userid").toString(), conf,
					orderBean.get("canceltime")==null?"":orderBean.get("canceltime").toString());
        } else {//订购
            vipurl = dictionaryDao.getValue("csmakeupviporderurl");
            jsonParams = this.fullOrderParams(orderBean.get("userid").toString(), conf);
        }
        logger.info("vipurl=>" + vipurl + ", jsonParams=>" + jsonParams);
		/*
		if("1".equals(orderBean.getUpdatetype())){//订购
			result = com.chinacreator.process.util.URLUtil.postJson(vipurl, jsonParams);
			result = HttpInvoke.sendHttpByPost("POST", vipurl, jsonParams, getProperty(orderBean.getUpdatetype()));
		}else{//退订
			result = com.chinacreator.process.util.URLUtil.postForm(vipurl, jsonParams);
			result = HttpInvoke.sendHttpByPost("POST", vipurl, jsonParams, getProperty(orderBean.getUpdatetype()));
		}*/
        result = HttpInvoke.sendhttpsReq("POST", vipurl, jsonParams, getProperty(orderBean.get("type").toString()));
        logger.info("调拓维会员接口返回结果：" + result);
        //去空格、换行符号
        if (result != null) result = result.replaceAll("\r|\n", "").replaceAll("	", "").replaceAll(" ", "");

        //result = "{\"code\":0,\"message\":\"成功\",\"success\":true}";
        //result = "{\"code\":7007,\"message\":\"签名无效\",\"success\":false}";
        return result;

    }

    /**
     * 填充退订会员参数
     *
     * @param mobile
     * @param conf
     * @return
     * @throws Exception
     */
    private String fullCancelParams(String mobile, HashMap conf, String canceltime) throws Exception {
        String jsonParams = "";
        HashMap<String, String> params = new HashMap<String, String>();
        String timestamp = System.currentTimeMillis() + "";
        String spid = conf.get("VSPID").toString();
        String cpid = conf.get("VCPID").toString();
        String userType = "1";
        String password = conf.get("VPWD").toString();
        mobile = DesUtil.encode(mobile, password); //手机号码加密
        String refundTime = canceltime;
        String signature = MD5.MD5Encode(spid + cpid + mobile + refundTime + userType + timestamp + password);

        JSONObject json = new JSONObject();
        json.put("timestamp", timestamp);
        json.put("signature", signature);
        json.put("spid", spid);
        json.put("cpid", cpid);
        json.put("mobile", mobile);
        json.put("userType", userType);
		json.put("refundTime", refundTime);
        jsonParams = json.toJSONString();
        //去除json格式
        jsonParams = jsonParams.replaceAll(":", "=").replaceAll(",", "&")
                .replaceAll("\"", "").replaceAll("\\{", "").replaceAll("\\}", "");
        return jsonParams;
    }

    /**
     * 填充订购会员参数
     *
     * @param mobile
     * @param conf
     * @return
     * @throws Exception
     */
    private String fullOrderParams(String mobile, HashMap conf) throws Exception {
        String jsonParams = "";
        String timestamp = System.currentTimeMillis() + "";
        String spid = conf.get("VSPID").toString();
        String cpid = conf.get("VCPID").toString();
        String memberUrl = "";
        String orderNumber = conf.get("SENO").toString();
        String password = conf.get("VPWD").toString();
        mobile = DesUtil.encode(mobile, password); //手机号码加密
        String signature = MD5.MD5Encode(spid + cpid + orderNumber + timestamp + password);

        JSONObject json = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(mobile);
        json.put("timestamp", timestamp);
        json.put("signature", signature);
        json.put("spid", spid);
        json.put("cpid", cpid);
        json.put("mobiles", jsonArray);
        json.put("memberUrl", memberUrl);
        json.put("orderNumber", orderNumber);
        jsonParams = json.toJSONString();

        return jsonParams;
    }

}
