package com.chinacreator.process.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinacreator.common.util.MD5;
import com.chinacreator.process.dao.ColorSealDao;
import com.chinacreator.process.dao.DictionaryDao;
import com.chinacreator.process.util.DesUtil;
import com.chinacreator.process.util.JsonUtil;
import com.chinacreator.process.util.URLUtil;
import com.chinacreator.video.queue.MessageService;
import com.chinacreator.video.queue.bean.MessagePipe;
import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 彩铃侧给用户开通彩铃功能和彩铃权益
 *
 * @author zhengrong.yan
 * @date 20201102
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class ColorSealPushMQJob {

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

    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private MessageService messageService;

    @Autowired
    private ColorSealDao colorSealDao;

    public void doProcess() throws Exception {
        logger.info("彩铃侧给用户开通彩铃功能和彩铃权益队列JOB启动");
        if (dictionaryDao.getValue("recivemq").equals("0")) {
            long beginTime = System.currentTimeMillis();
            List<MessagePipe> list = messageService.reciveBatchMessage("colorSeal", 500);
//            List<MessagePipe> list = new ArrayList<>();
//            MessagePipe mpipe = new MessagePipe();
//            mpipe.setHeader("colorSeal");
//            mpipe.addBody("userid", "18673197465");
//            mpipe.addBody("type", "colorSeal");//直接推入彩铃的队列
//            mpipe.addBody("ordertime", "20201102140155");
//            mpipe.addBody("canceltime", "");
//            mpipe.addBody("cpid", "mangtv");
//            mpipe.addBody("spid", "1008");
//            mpipe.addBody("status", "0");
//            mpipe.addBody("id", "202011042043579937941");
//            list.add(mpipe);
            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 reqBean
     */
    public void handleOrder(Map reqBean) {
        Map logMap = new HashMap();
        HashMap hashMap = new HashMap();
        logMap.put("data", reqBean);
        long starttime = System.currentTimeMillis();
        String resultcode = "-1"; //默认失败
        String description = "执行中";
        String id = "";
        Date now = new Date();
        String ordertype = "";
        HashMap map = new HashMap();
        try {
            Object channel = reqBean.get("orderchannel");
            //调彩铃侧接口
            if (reqBean.get("status") != null) {
                ordertype = reqBean.get("status").toString();//status 0订购1退订
            } else {
                ordertype = reqBean.get("orderType") == null ? "" : reqBean.get("orderType").toString();
            }
            if("0".equals(ordertype)){
                channel = reqBean.get("orderchannel");
                ordertype = "1";
            }else {
                ordertype = "2";
                channel = reqBean.get("cancelchannel");
            }
            if (channel != null && "zongheorder".equals(channel) ) {
                resultcode = "7000";
                description = "不接受该队列数据";
                return;
            }
            /*添加到表*/

            map.put("id", colorSealDao.getNo());
            map.put("userid", reqBean.get("userid"));
            map.put("cpid", reqBean.get("cpid"));
            map.put("spid", reqBean.get("spid"));
            map.put("orderid", reqBean.get("orderid"));
            map.put("ordertype",ordertype);
            map.put("interface", "colorsealnotify");
            String isreverse = "1";
            if("MGTV_APP".equals(channel)){
                isreverse = "2";
            }
            map.put("isreverse", isreverse);
            map.put("channel",channel);
            reqBean.put("subchannel",channel);
            colorSealDao.addOrderRec(map);

            HashMap<String, String> remap = sendRights(reqBean);
            resultcode = remap.get("resultcode");
            description = remap.get("description");
//            }

        } catch (Exception e) {
            e.printStackTrace();
            resultcode = "8000";
            description = "系统错误，" + e.getMessage();
            logger.error("订购关系出现异常，" + e.toString());
        } finally {
            String time = System.currentTimeMillis() / 1000 - starttime / 1000 + "";//调接口时间
            //写日志
            logMap.put("time", time);
            logMap.put("reusltCode", resultcode);
            logMap.put("resultInfo", description);
            map.put("resultcode", resultcode);
            map.put("resultinfo", description);
            try {
                colorSealDao.update(map);
            }catch (Exception e){
                e.printStackTrace();
                logMap.put("error","更新表异常");
            }
            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);
    }


    /*
     * 赠送会员超时异步重试队列推送，最多重试三次
     * @param orderInfo
     */
    public void inserRetryMq(Map map) {
        try {
            MessagePipe mpipe = new MessagePipe();
            mpipe.setHeader("colorsealretry");
            mpipe.addBody("id", map.get("id"));
            mpipe.addBody("userid", map.get("userid"));
            mpipe.addBody("type", "colorSeal");//直接推入彩铃的队列
            mpipe.addBody("ordertime", map.get("ordertime"));
            mpipe.addBody("canceltime", map.get("canceltime"));
            mpipe.addBody("effecttime", map.get("effecttime"));
            mpipe.addBody("cpid", map.get("cpid"));
            mpipe.addBody("spid", map.get("spid"));
            mpipe.addBody("status", map.get("status"));
            this.messageService.sendMessage(mpipe);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("超时异步重试队列推送出现异常，" + e.getMessage());
        }
    }


    /**
     * 调接口
     *
     * @return
     * @throws Exception
     */
    private HashMap<String, String> sendRights(Map map) throws Exception {
        HashMap<String, String> remap = new HashMap<String, String>();
        HashMap<String, String> pushmap = new HashMap<String, String>();//发送接口map
        String resultcode = "-1"; //默认失败
        String description = "执行中";
        try {
            String url = this.dictionaryDao.getValue("colorsealNotify");
            String userid = map.get("userid").toString();
            String spid = map.get("spid").toString();
            String type = "0";
            if (map.get("status") != null) {
                type = map.get("status").toString();//status 0订购1退订
            } else {
                type = map.get("orderType") == null ? "" : map.get("orderType").toString();
            }

            Object channel = map.get("subchannel");

            /*调接口*/
            map.put("url", url);
            logger.info(JSON.toJSONString(map));
            String result = toInterface(map);//调接口
            logger.info("url: " + url);
            logger.info("result: " + result);
            if (!"".equals(result)) {
                net.sf.json.JSONObject resjson = net.sf.json.JSONObject.fromObject(result);
                logger.info("赠送权益结果=> userid: " + userid + ", result: " + result);
                Map<?, ?> resultmap = JsonUtil.jsonToMap(result);
                resultcode = resultmap.get("resultcode") + "";
                description = resultmap.get("errorinfo") + "";
                if ("0".equals(resultcode)) {//通知成功
                    if (type.equals("0") && !"MGTV_APP".equals(channel)) {//订购成功的且渠道不为MGTV_APP
                        url = this.dictionaryDao.getValue("colorsealSet");
                        map.put("url", url);
                        map.put("ringid", this.dictionaryDao.getValue("colorsealdefaultring"));//默认铃声
                        result = toInterface(map);
                        logger.info("seturl: " + url);
                        logger.info("setresult: " + result);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("userid: " + map.get("userid") + "赠送权益失败，" + e);
            resultcode = "8000";
            description = "赠送权益出现异常，" + e.getMessage();
        } finally {
            remap.put("resultcode", resultcode);
            remap.put("description", description);
        }
        return remap;
    }

    /**
     * 通过时间秒毫秒数判断两个时间的间隔
     *
     * @param date1
     * @param date2
     * @return
     */
    public int differentDaysByMillisecond(Date date1, Date date2) {
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000));
        return days;
    }

    public static void main(String[] args) {
        String pwd = "#EDC2wsx";
        String channel = "clmangtv";
        String cpid = "mangtv16";
        String userid = "RVnTfKtPmqiXLJtmwmtMxA==";
        String timestamp = "1605839654";
        String spid = "1008";
        System.out.println((System.currentTimeMillis()) / 1000 + "");

        //System.out.println(userid + channel + spid + cpid + timestamp + pwd);
        String ringid = "99103000202008285994840";
        String signature_fornotify = MD5.MD5Encode(userid + cpid + spid + channel + ringid + timestamp + pwd);
        System.out.println(signature_fornotify);
        String lcalsign = "RVnTfKtPmqiXLJtmwmtMxA==mangtv161008clmangtv1605839654#EDC2wsx";
        System.out.println(MD5.MD5Encode(lcalsign));

    }

    private String getMonthLastDay() {
        //设置时间格式
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        //获得实体类
        Calendar ca = Calendar.getInstance();
        //设置最后一天
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
        //最后一天格式化
        String lastDay = format.format(ca.getTime());
        return lastDay + "235959";
    }

    private String toInterface(Map map) throws Exception {
        try {
            String url = map.get("url").toString();
            String userid = map.get("userid").toString();
            String spid = map.get("spid").toString();
            String type = "0";
            if (map.get("status") != null) {
                type = map.get("status").toString();//status 0订购1退订
            } else {
                type = map.get("orderType") == null ? "" : map.get("orderType").toString();
            }
            Short consumeType = 1;//1订购2退订
            String subTime = map.get("ordertime").toString();//订购时间 consumeType为1时必传
//            String unsubTime = map.get("canceltime").toString();//退订时间 consumeType为2时必传
//            String startTime = subTime;//生效时间 consumeType为1时必传

            //接口传递参数
            if (type.equals("1")) {//退订
                consumeType = 2;
            }
            String pwd = "#EDC2wsx";
            String channel = "clmangtv";
            String cpid = "mangtv16";
            type = consumeType + "";
            userid = DesUtil.encode(userid, pwd);
            String timestamp = (System.currentTimeMillis()) / 1000 + "";

            System.out.println(userid + channel + spid + cpid + timestamp + pwd);
            String signature_fornotify = MD5.MD5Encode(userid + cpid + spid + channel + timestamp + pwd);
            String jsonParams = "";
            JSONObject json = new JSONObject();

            json.put("userid", userid);
            json.put("cpid", cpid);
            json.put("spid", spid);
            json.put("type", type);
            json.put("channel", channel);
            json.put("timestamp", timestamp);
            json.put("signature", signature_fornotify);
            json.put("subchannel",map.get("subchannel"));
            if (map.get("ringid") != null && !"".equals(map.get("ringid"))) {
                String ringid = map.get("ringid").toString();
                String signature_forset = MD5.MD5Encode(userid + cpid + spid + channel + ringid + timestamp + pwd);
                url = map.get("url").toString();
                json.put("ringid", ringid);
                json.put("signature", signature_forset);
            }
            json.put("isreverse", "1");//反向通知标志
            jsonParams = json.toJSONString();
            System.out.println(url);
            System.out.println(jsonParams);
            String result = invokePostJson(url, jsonParams);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }


    public static String invokePostJson(String url, String params) {
        try {
            String resp = URLUtil.postJson(url, params);
            System.out.println(resp);
            return resp;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

}
