package com.chinacreator.process.job;

import com.alibaba.fastjson.JSON;
import com.chinacreator.common.util.DESUtil;
import com.chinacreator.common.util.URLUtil;
import com.chinacreator.process.dao.DictionaryDao;
import com.chinacreator.process.dao.MqSmsConfDao;
import com.chinacreator.process.dao.VirtualDao;
import com.chinacreator.process.util.DesUtil;
import com.chinacreator.process.util.JsonUtil;
import com.chinacreator.process.util.SHAUtil;
import com.chinacreator.process.util.WriteLogUtil;
import com.chinacreator.video.queue.MessageService;
import com.chinacreator.video.queue.bean.MessagePipe;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class CShandleSmsConfJob {

    private Logger logger = Logger.getLogger("cssms");
    //private Logger log = Logger.getLogger(CShandleSmsConfJob.class);
    private final static String KEY = "22fdse33";

    @Autowired
    private MqSmsConfDao mqSmsConfDao;

    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private MessageService messageService;


    @Autowired
    private VirtualDao virtualDao;

    public void doProcess() throws Exception {
    	WriteLogUtil.writeLong("业务短信CShandleSmsConfJob开始执行", logger, "CShandleSmsConfJob");//("业务短信CShandleSmsTempJob开始执行");
        //获取短信配置信息，会不会更新
        List<HashMap> confList = mqSmsConfDao.getConfList();
        //log.info("配置size: " + confList.size());
        if (confList != null && confList.size() > 0 && "0".equals(dictionaryDao.getValue("recivemq"))) {
            List<MessagePipe> list = messageService.reciveBatchMessage("cssms2", 500);
            if (list != null && list.size() > 0) {
            	logger.info("CShandleSmsConfJob短信需要发送的条数：" + list.size());
                HashMap logmap = new HashMap();
                for (MessagePipe messagePipe : list) {
                	logmap = new HashMap();
                	logmap.put("job", "CShandleSmsConfJob");
                	logmap.put("mqbody", messagePipe.getBody());
                    String content = "";
                    String result = "";
                    String spid = (String) messagePipe.getBody().get("spid");
                    String cpid = messagePipe.getBody().get("cpid") + "";
                    String userid = (String) messagePipe.getBody().get("userid");
                    String times = (String) messagePipe.getBody().get("times");
                    String style = (String) messagePipe.getBody().get("style");
                    String busiType = messagePipe.getBody().get("busiType") + "";
                    String channel = messagePipe.getBody().get("channel") == null ? "" : (String) messagePipe.getBody().get("channel");
                    String subchannel = messagePipe.getBody().get("subchannel") == null ? "" : (String) messagePipe.getBody().get("subchannel");
                    String province = messagePipe.getBody().get("province") == null ? "" : (String) messagePipe.getBody().get("province");
                    String param1 = messagePipe.getBody().get("param1") != null ? (String) messagePipe.getBody().get("param1") : "";
                    String param2 = messagePipe.getBody().get("param2") != null ? (String) messagePipe.getBody().get("param2") : "";
                    String param3 = messagePipe.getBody().get("param3") != null ? (String) messagePipe.getBody().get("param3") : "";
                    String staffid = messagePipe.getBody().get("staffid") == null ? "" : (String) messagePipe.getBody().get("staffid");//员工工号
                    try {
                        content = this.getSmsContent(confList, messagePipe);
                        //log.info("sms content:" + content);
                        logmap.put("content", content);
                        if (StringUtils.isNotEmpty(content)) {
                            if (mqSmsConfDao.getChannel(userid, spid) || !("tran_succ".equals(busiType) || "vs_tran_succ".equals(busiType))) {
                                result = URLUtil.get("http://172.16.1.81:809/videoif/channelSmsSend.do?userid=" + URLEncoder.encode(DESUtil.encode(userid, KEY), "utf-8") + "&content=" + URLEncoder.encode(content, "UTF-8") + "&channel=cssms", 2000);
                            }
/*                            //腾讯活动短信发送
                            if (mqSmsConfDao.isSendSms(userid, spid) && "101".equals(spid)) {
                                messagePipe.addBody("busiType","tran_succ_TX20");
                                content = this.getSmsContent(confList, messagePipe);
                                log.info("sms content:" + content);
                                if (StringUtils.isNotEmpty(content)) {
                                        result = URLUtil.get("http://10.199.99.147:8092/videoif/channelSmsSend.do?userid=" + URLEncoder.encode(DESUtil.encode(userid, KEY), "utf-8") + "&content=" + URLEncoder.encode(content, "UTF-8") + "&channel=cssms", 2000);
                                }
                            }*/
                        } else if (StringUtils.isEmpty(content) && "tran_succ".equals(busiType) && StringUtils.isNotEmpty(spid)) {
                            //1.获取短信配置表id
                            List<HashMap> virList = virtualDao.getConfList(spid);
                            //log.info("虚商配置表数据:" + virList);                     
                            if (virList != null && virList.size() > 0) {
                                for (int i = 0; i < virList.size(); i++) {
                                    HashMap hashMap = virList.get(i);
                                    String contentid = hashMap.get("CONTENTID") + "";
                                    if (StringUtils.isNotEmpty(contentid)) {
                                        result = sendSMS(userid, contentid);
                                    }
                                }
                            }
                        }
                        logmap.put("result", result);
                    } catch (Exception e) {
                        logger.error(userid + "短信发送失败", e);
                        logmap.put("result", "出现异常，"+e.getMessage());
                    } finally {
                    	/**
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("userid", userid);
                        map.put("cpid", cpid);
                        map.put("spid", spid);
                        map.put("style", style + "");
                        map.put("result", result);
                        map.put("times", times);
                        map.put("busiType", busiType);
                        map.put("param1", param1);
                        map.put("param2", param2);
                        map.put("param3", param3);
                        map.put("param3", content);
                        map.put("channel", channel);
                        map.put("subchannel", subchannel);
                        map.put("province", province);
                        map.put("staffid", staffid);
                        **/
                        logger.info(JsonUtil.objectToJson(logmap));
                    }
                }
            }
        }
    }


    /**
     * 获取短信内容
     *
     * @param confList
     * @param messagePipe
     * @return
     * @throws Exception 
     */
    public String getSmsContent(List<HashMap> confList, MessagePipe messagePipe) throws Exception {
        String content = "";
        try {
            String resultcode = (String) messagePipe.getBody().get("result");
            String userid = (String) messagePipe.getBody().get("userid");
            //原匹配信息
            String style = (String) messagePipe.getBody().get("style");
            //新匹配信息
            String busiType = (String) messagePipe.getBody().get("busiType");
            //二级渠道
            String subchannel = (String) messagePipe.getBody().get("subchannel");
            //渠道
            String channel = (String) messagePipe.getBody().get("channel");
            //省份
            String province = (String) messagePipe.getBody().get("province");
            //员工工号
            String staffid = (String) messagePipe.getBody().get("staffid");
            //扩展参数
            logger.info("mq取值信息：" + " subchannel:" + subchannel + " channel:" + channel + " busiType:" + busiType + " province:" + province + " staffid:" + staffid);


            String param1 = messagePipe.getBody().get("param1") != null ? (String) messagePipe.getBody().get("param1") : "";
            String param2 = messagePipe.getBody().get("param2") != null ? (String) messagePipe.getBody().get("param2") : "";
            String param3 = messagePipe.getBody().get("param3") != null ? (String) messagePipe.getBody().get("param3") : "";
            //配置信息
            HashMap mqSmsConf = null;
            //获取匹配的配置信息
            //二级渠道信息匹配
            Boolean flag = false;
            if ("cap".equals(channel) || "capftp".equals(channel)) {
                //员工工号优先级高于省份
                if (staffid != null && !"".equals(staffid)) {
                    for (HashMap tmp : confList) {
                        if (busiType != null && !"".equals(busiType.trim()) && tmp.get("BUSITYPE") != null && !"".equals(tmp.get("BUSITYPE"))) {
                            if (staffid.trim().equals(tmp.get("STAFFID")) && tmp.get("SPID").equals(messagePipe.getBody().get("spid"))
                                    && tmp.get("BUSITYPE").equals(busiType.trim())) {
                                if (checkTime(tmp)){
                                    continue;
                                }
                                flag = true;
                                logger.info("staffid:数据库取值" + tmp.get("BUSITYPE") + tmp.get("SPID") + tmp.get("STAFFID"));
                                mqSmsConf = tmp;
                                break;
                            }
                        }
                    }
                }
                if (mqSmsConf == null) {
                    if (province != null && !"".equals(province)) {
                        for (HashMap tmp : confList) {
                            if (busiType != null && !"".equals(busiType.trim()) && tmp.get("BUSITYPE") != null && !"".equals(tmp.get("BUSITYPE"))) {
                                if (province.trim().equals(tmp.get("PROVINCE")) && tmp.get("SPID").equals(messagePipe.getBody().get("spid"))
                                        && tmp.get("BUSITYPE").equals(busiType.trim())) {
                                    if (checkTime(tmp)){
                                        continue;
                                    }
                                    flag = true;
                                    logger.info("province:数据库取值" + tmp.get("BUSITYPE") + tmp.get("SPID") + tmp.get("PROVINCE"));
                                    mqSmsConf = tmp;
                                    break;
                                }
                            }
                        }
                    }
                }
            } else {
                for (HashMap tmp : confList) {
                    if (busiType != null && !"".equals(busiType.trim()) && tmp.get("BUSITYPE") != null && !"".equals(tmp.get("BUSITYPE"))) {
                        if (subchannel != null && channel != null && subchannel.trim().equals(tmp.get("SUBCHANNEL")) && channel.trim().equals(tmp.get("CHANNEL")) && tmp.get("SPID").equals(messagePipe.getBody().get("spid"))
                                && tmp.get("BUSITYPE").equals(busiType.trim())) {
                            if (checkTime(tmp)){
                                continue;
                            }
                            flag = true;
                            logger.info("false:数据库取值" + tmp.get("BUSITYPE") + tmp.get("SUBCHANNEL") + tmp.get("CHANNEL") + tmp.get("SPID"));
                            mqSmsConf = tmp;
                            break;
                        }
                    }
                }
            }
            if (!flag) {
                for (HashMap tmp : confList) {
                    if (checkTime(tmp)){
                        continue;
                    }
                    if (busiType != null && !"".equals(busiType.trim()) && tmp.get("BUSITYPE") != null && !"".equals(tmp.get("BUSITYPE"))) {
                        if (subchannel != null && channel != null && subchannel.trim().equals(tmp.get("SUBCHANNEL")) && channel.trim().equals(tmp.get("CHANNEL")) && tmp.get("SPID").equals(messagePipe.getBody().get("spid"))
                                && tmp.get("BUSITYPE").equals(busiType.trim())) {
                            logger.info("数据库取值1" + tmp.get("BUSITYPE") + tmp.get("SUBCHANNEL") + tmp.get("CHANNEL") + tmp.get("SPID"));
                            mqSmsConf = tmp;
                            break;
                        } else if (tmp.get("SPID").equals(messagePipe.getBody().get("spid"))
                                && tmp.get("BUSITYPE").equals(busiType.trim()) && tmp.get("SUBCHANNEL") == null && tmp.get("PROVINCE") == null && tmp.get("STAFFID") == null) {
                            logger.info("数据库取值2" + tmp.get("BUSITYPE") + tmp.get("SUBCHANNEL") + tmp.get("CHANNEL") + tmp.get("SPID"));
                            mqSmsConf = tmp;
                            break;
                        }
                    } else if (style != null && !"".equals(style.trim()) && tmp.get("STYLE") != null && style.trim().equals(tmp.get("STYLE"))) {
                        mqSmsConf = tmp;
                        break;
                    }
                    //System.out.println(tmp);
                }
            }
            //得到发送短信文本
            if (mqSmsConf != null) {
                content = (String) mqSmsConf.get("SMSTXT");
                //替换参数内容
                if (mqSmsConf.get("PARAMS") != null && !"".equals(mqSmsConf.get("PARAMS"))) {
                    String[] params = ((String) mqSmsConf.get("PARAMS")).split("\\|");
                    for (int i = 0; i < params.length; i++) {
                        if ("MM".equals(params[i])) {
                            content = content.replace("{" + i + "}", DateFormatUtils.format(new Date(), "MM"));
                        } else if ("dd".equals(params[i])) {
                            content = content.replace("{" + i + "}", DateFormatUtils.format(new Date(), "dd"));
                        } else if ("resultcode".equals(params[i])) {
                            content = content.replace("{" + i + "}", resultcode);
                        } else if ("userid".equals(params[i])) {
                            content = content.replace("{" + i + "}", userid);
                        } else if ("param1".equals(params[i])) {
                            content = content.replace("{" + i + "}", param1);
                        } else if ("param2".equals(params[i])) {
                            content = content.replace("{" + i + "}", param2);
                        } else if ("param3".equals(params[i])) {
                            content = content.replace("{" + i + "}", param3);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("获取短信内容出错，" + e.getMessage());
            throw e;
        }
        return content;
    }


    public boolean checkTime(HashMap  mqSmsConf) throws ParseException {
        String sendtime = (String) mqSmsConf.get("SENDTIME");
        if (StringUtils.isNotEmpty(sendtime)) {
            long currentTime = System.currentTimeMillis();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String[] split = sendtime.split("-");
            long startTime = simpleDateFormat.parse(split[0]).getTime();
            long endTime = simpleDateFormat.parse(split[1]).getTime();
            if (currentTime<startTime||currentTime>endTime){
                return true;
            }
        }
        return false;
    }
    /**
     * 发送虚拟短信内容
     *
     * @param userid
     * @param contentid
     * @return
     */
    private String sendSMS(String userid, String contentid) {
        try {
            String smsid = "106550077614";
            String key = "wo6bslq2";
            String timestamp = System.currentTimeMillis() / 1000 + "";
            String usermob = DesUtil.encode(userid, key);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            int month = calendar.get(Calendar.MONTH) + 1;
            int date = calendar.get(Calendar.DAY_OF_MONTH);
            String vars = "{\"userid\":" + userid + ",\"month\":" + month + ",\"date\":" + date + "}";
            String sign = SHAUtil.shaEncode(smsid + usermob + timestamp + vars + contentid + key).toLowerCase();
            usermob = URLEncoder.encode(usermob, "utf-8");
            contentid = URLEncoder.encode(contentid, "utf-8");
            vars = URLEncoder.encode(vars, "utf-8");
            String url = "http://172.16.1.81:809/xsbusi/sms/send?userid=" + usermob + "&smsid=" + smsid + "&timestamp=" + timestamp + "&sign=" + sign + "&contentid=" + contentid + "&vars=" + vars;
            String resp = URLUtil.get(url);
            //log.info("虚商短信路径:" + url);
            //log.info("调用虚商短信后返回的参数:" + resp);
            /**
            Map map = JSON.parseObject(resp, Map.class);
            String resultcode = map.get("resultcode") + "";
            if ("0".equals(resultcode)) {
                log.info("虚商短信发送成功");
            } else {
                log.info("虚商短信发送失败");
            }
			**/
            return resp;
        } catch (Exception e) {
            //logger.info("虚商短信发送失败");
            e.printStackTrace();
            return "虚商短信发送失败，"+e.getMessage();
        }
        //log.info("虚商短信发送失败");
        //return null;
    }

    public static void main(String[] args) {
        HashMap<Object, Object> objectObjectHashMap = new HashMap<Object, Object>();
        System.out.println("null".equals(String.valueOf(objectObjectHashMap.get("22"))));
        System.out.println("null".equals((String)objectObjectHashMap.get("22")));
        System.out.println(StringUtils.isEmpty((String)objectObjectHashMap.get("22")));
        System.out.println(StringUtils.isEmpty(String.valueOf(objectObjectHashMap.get("22"))));

    }
}
