package com.chinacreator.process.job;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Calendar;

import com.chinacreator.process.dao.DictionaryDao;
import com.chinacreator.process.util.DesUtil;
import com.frameworkset.util.StringUtil;
import org.apache.log4j.Logger;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;

import com.chinacreator.common.util.DESUtil;
import com.chinacreator.common.util.URLUtil;
import com.chinacreator.process.bean.MonthlyOrderSmsBean;
import com.chinacreator.process.dao.MonthlyOrderSmsDao;
import com.chinacreator.process.util.SHAUtil;

import net.sf.json.JSONObject;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.PostConstruct;

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class OrderSmsMonthJob  {

    private static Logger logger = Logger.getLogger(OrderSmsMonthJob.class);
    public static final String urlbase = "https://cctv2.mige.tv/smsbusi/sms/send";

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

    @Autowired
    private MonthlyOrderSmsDao monthlyOrderSmsDao;

    @Autowired
    private DictionaryDao dictionaryDao;

//    public static OrderSmsMonthJob orderSmsMonthJob;
//
//    @PostConstruct
//    public  void init () {
//        orderSmsMonthJob = this;
//        orderSmsMonthJob.dictionaryDao = this.dictionaryDao;
//        logger.info("PostConstruct接口的innit()执行");
//    }



    public void doProcess() throws Exception {
        Date now = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(now);
        logger.info("dateStr : " + dateStr);

        //如果是月初就执行任务，发送上个月
        if (isFitstOfMonth(dateStr)) {
            //0 : 复合产品， 1： 非复合产品
        	System.out.println("开始执行");
            doSend("1");
        }
//        log.info("执行发送非复合产品短信的任务");
//        doSend("1"); // 测试，直接发送，发送7月1日当天
    }

    public void doSend(String type) throws Exception {
    	log.info("==========getMonthlyOrderSms==========");
        log.info("type : " + type);
        List<MonthlyOrderSmsBean> beanList =  monthlyOrderSmsDao.queryUsersList(type); //得到要下发短信的用户
        log.info("resultSize : \n" + beanList.size());
        List<String> userList = new ArrayList<String>();
        Map<String, List<MonthlyOrderSmsBean>> maps = new HashMap<String, List<MonthlyOrderSmsBean>>();

        for (MonthlyOrderSmsBean u : beanList) {
            userList.add(u.getUserid());
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        String sendMonth = format.format(new Date());
        removeDuplicate(userList);
        log.info("userListSize :" + userList.size());
        for (String key : userList) {
            List<MonthlyOrderSmsBean> smsList = new ArrayList<MonthlyOrderSmsBean>();
            for (int i = 0; i < beanList.size(); i++) {
                if (key.equals(beanList.get(i).getUserid())) {
                    smsList.add(beanList.get(i));
                }
            }
            maps.put(key, smsList);
        }

        String context = "用户您好，您订购的{0}产品，系统将在本月3日自动为您续送当月会员权益，特此感谢您的理解，请您耐心等待。";
        String s = "";
        for (String key : userList) {
            for (MonthlyOrderSmsBean bean : maps.get(key)) {
                s = context.replace("{0}", bean.getSpname());
                bean.setContext(s);
                bean.setSendmonth(sendMonth);
                log.info("saveInfoBean : " + bean.toString());
                boolean b = monthlyOrderSmsDao.saveInfo(bean);
                if (b) {
//                    sendUser(s, key, bean); //旧方法
                    HashMap<String, String> map = new HashMap<>();
                    map.put("sp_name",bean.getSpname());
                    String result = sendSMSByContentid(key, "202208011446014411", map);//  todo   ，发送短信使用模板
                    saveSMSLog(result,bean);
                }

            }
        }
    }

    /*
        发短信的逻辑：调smsorder的channelSmsSend 接口，经过校验后，把短信保存到wait表，等待下发。
        修改思路：
        1.使用字典表获取smsbusi的地址  ； 待验证：正式环境是否是222库 ？ 已验证，YES
        2.配置contentid 与smsiid
        模板内容：【联通畅视】用户您好，您订购的{$sp_name}产品，系统将在本月3日自动为您续送当月会员权益，特此感谢您的理解，请您耐心等待。
        生产：
            smsid：2022041516441
            pwd：  !qwcpbl@
            contentid：202208011446014411
            vars：sp_name

     */

    private void sendUser(String content,String oldId, MonthlyOrderSmsBean bean) throws Exception {
        content =  URLEncoder.encode(content);
        try {
            String channel= "kczyf01";
            String key = "s9dcso2w";
            String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
            String sign = SHAUtil.shaEncode(channel+oldId+timestamp+key).toLowerCase();
            String usermob =  URLEncoder.encode(DESUtil.encode(oldId,  key),"utf-8");
            String url = "http://111.206.133.54/smsorder/channelSmsSend.do?userid=" + usermob + "&channel="
                    + channel + "&timestamp=" + timestamp + "&sign=" + sign + "&content=" + content;
            String resultTemp = URLUtil.get(url);
            JSONObject jsonObject = JSONObject.fromObject(resultTemp);
            String resultCode = jsonObject.get("resultCode").toString();
            String resultInfo = jsonObject.get("resultInfo").toString();
            log.info(jsonObject.get("resultCode").toString());
            log.info(jsonObject.get("resultInfo").toString());
            bean.setResultcode(resultCode);
            bean.setErrorinfo(resultInfo);
        } catch (Exception e){
            log.info("发送短信异常：" + e.toString());
        } finally {
            //不管任何情况下,记录短信发送情况日志
            monthlyOrderSmsDao.saveSendCaseLog(bean);
        }

    }

    public   String sendSMSByContentid(String userid, String contentid, Map<String, String> map)  {
        String dbUrl = "";
        String nurl = "";
        try {
            //从数据字典表中查询地址，正式环境结果为：https://cctv2.mige.tv/smsbusi/sms/send
            // 测试环境结果为：https://testapi.mige.tv/smsbusi/sms/send
//            dbUrl = orderSmsMonthJob.dictionaryDao.getValue("newSmsSendUrl");
            dbUrl = dictionaryDao.getValue("newSmsSendUrl");
        } catch (Exception e) {
            log.error("smsUtil、dictionaryDao、url存在空指针问题，使用静态地址");
            e.printStackTrace();
        } finally {
            if (dbUrl == null || "".equals(dbUrl)) {
                nurl = urlbase;
                log.info("使用静态地址发短信，地址是：" + nurl);
            } else {
                nurl = dbUrl;
                log.info("发短信，地址是>>>>>>>>>>>>>>>>>：" + nurl);
            }
        }
        String result = "";
        try {
            String smsid = "2022041516441";
            String pwd = "!qwcpbl@";
            userid = DesUtil.encode(userid, pwd);
            String vars = com.alibaba.fastjson.JSONObject.toJSONString(map);
            String timestamp = System.currentTimeMillis() / 1000 + "";
            String sign = SHAUtil.shaEncode(smsid + userid + timestamp + vars + contentid + pwd).toLowerCase();
            userid = URLEncoder.encode(userid, "utf-8");
            vars = URLEncoder.encode(vars, "utf-8");
            String url = nurl + "?smsid=" + smsid + "&userid=" + userid + "&timestamp=" + timestamp + "&sign=" + sign + "&vars=" + vars + "&contentid=" + contentid;
            log.info("send SMS url:"+url);
            result = URLUtil.get(url);
            log.info("send SMS result:"+result);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("send sms error,exception is:"+e +" detail is"+e.getMessage());
        }
        return result;
    }

    public static List removeDuplicate(List list) {
        HashSet h = new HashSet(list);
        list.clear();
        list.addAll(h);
        return list;
    }

    public boolean isFitstOfMonth(String dateStr) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal_1 = Calendar.getInstance();//获取当前日期
        cal_1.setTime(new Date());
        cal_1.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
        String startDay = format.format(cal_1.getTime());
        System.out.println(startDay);
        if (startDay.equals(dateStr)) {
            return true;
        }
        return false;
    }


    public  void saveSMSLog(String result ,MonthlyOrderSmsBean bean){
        String resultCode = "";
        String errorinfo = "";
        if(!StringUtil.isEmpty(result)){
            JSONObject jsonObject = JSONObject.fromObject(result);
            resultCode = jsonObject.get("resultcode").toString();
            errorinfo = jsonObject.get("errorinfo").toString();
        }else{
            resultCode="-1";
            errorinfo="error";
        }
        log.info(resultCode);
        log.info(errorinfo);
        bean.setResultcode(resultCode);
        bean.setErrorinfo(errorinfo);
        monthlyOrderSmsDao.saveSendCaseLog(bean);//保存发送日志
    }

    public static void main(String[] args) {

//        Date now = new Date();
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//        String dateStr = format.format(now);
//        logger.info("dateStr : " + dateStr);
//
//         new OrderSmsMonthJob().isFitstOfMonth(dateStr);


//        HashMap<String, String> map = new HashMap<>();
//        map.put("sp_name","腾讯视频");
//        try {
//            String s = sendSMSByContentid("15581368293", "202208011446014411", map);
//            System.out.println(s); //{"resultcode":"0","errorinfo":"","taskid":"202208171028369988871","ssmsid":null}
//        } catch (Exception e) {
//            e.printStackTrace();
//
//        }


//        String s = "{\"resultcode\":\"0\",\"errorinfo\":\"\",\"taskid\":\"202208171028369988871\",\"ssmsid\":null}";
//        JSONObject jsonObject = JSONObject.fromObject(s);
//        String resultCode = jsonObject.get("resultcode").toString();
//        String resultInfo = jsonObject.get("errorinfo").toString();
//        System.out.println(resultCode);
//        System.out.println(resultInfo);

    }



}

