package com.chinacreator.video.restful.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BusinessException;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.ChannelDao;
import com.chinacreator.video.mapper.DictionaryDao;
import com.chinacreator.video.restful.bean.ChannelOrgBean;
import com.chinacreator.video.restful.bean.TlVerifiCationCodeBean;
import com.chinacreator.video.restful.dao.SendSmsCodeDao;
import com.chinacreator.video.restful.dao.SmsContentDao;
import com.chinacreator.video.restful.dao.SmsWhiteDao;
import com.chinacreator.video.restful.service.SendSmsCodeService;
import com.chinacreator.video.service.QryBusiService;
import com.chinacreator.video.util.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class SendSmsCodeAction {
    @Autowired
    private SmsContentDao smsContentDao;
    @Autowired
    private SmsWhiteDao smsWhiteDao;
    @Autowired
    private SendSmsCodeDao sscd;

    @Autowired
    private ChannelDao channelDao;

    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private SendSmsCodeService sendSmsCodeService;

    @Autowired
    private QryBusiService service;

    private static Logger logger = Logger.getLogger("sendSms");

    @RequestMapping("/sendSmsCode")
    public Map<String, Object> doNet(@RequestBody String params) throws Exception {
        if (StringUtils.isEmpty(params)){
            throw  new BussinessException("80015","参数不合法");
        }
        JSONObject jsonObject = JSONObject.parseObject(params);
        String cpid = jsonObject.getString("cpid");
        String userid = jsonObject.getString("userid");
        String spid = jsonObject.getString("spid");
        String timestamp = jsonObject.getString("timestamp");
        String channel = jsonObject.getString("channel");
        String flag = jsonObject.getString("flag");
        String type = jsonObject.getString("type");
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setChannel(channel);
        orderInfo.setCpid(cpid);
        orderInfo.setSpid(spid);
        orderInfo.setTimestamp(timestamp);
        orderInfo.setUserid(userid);
        logger.info("参数校验校验开始");
        sendSmsCodeService.busiCheck(jsonObject,"prizeauth",orderInfo);
        logger.info("渠道短信次数校验");
        service.valiVisitLimit(orderInfo);
        String phone = "";
        Map<String, Object> dop = new HashMap<String, Object>();
        try {
               //渠道方接入
                ChannelOrgBean channelOrgBean = channelDao.findByChannelId(channel);
                if (channelOrgBean == null || channelOrgBean.getStatus().equals("1")) {
                    throw new BusinessException("9001", "渠道参数错误");
                }
                System.out.println(userid + "   " + channelOrgBean.getPassword());
                phone = DesUtil.decode(userid, channelOrgBean.getPassword());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error((Object) ("cpid=" + cpid + "userid=" + userid + "spid=" + spid + "channel=" + channel + "Error" + e.getMessage()));
            throw new BusinessException("8009", "手机号解密失败", new String[0]);
        }
        if ((this.smsWhiteDao.isBlackUserCanSend(phone, cpid) > 0L)) {
            throw new BusinessException("8007", "黑名单用户,短信发送失败", new String[0]);
        }
        this.concurrentCheck(phone, cpid);
        System.out.println(sscd.checkValidatTime(cpid, phone));
        long timeDifference = Long.parseLong(StringUtils.isEmpty(sscd.checkValidatTime(cpid, phone)) ? "61" : sscd.checkValidatTime(cpid, phone).substring(0,sscd.checkValidatTime(cpid, phone).lastIndexOf(".")));
        long vercode = (long) (Math.random() * 1000000.0);
        if (vercode < 100000L) {
            vercode += 100000L;
        }
        //如果是湖北订购页面及领取会员页面时间超过5秒就可以再发短信
        if (timeDifference > 60L || (("chinacreator".equals(channel) || "hubeijoin".equals(channel)) && timeDifference > 5L)) {
            if (!(this.smsWhiteDao.isWhiteUserCanSend(phone, cpid) > 0L)) {
                this.totalCheck(phone);
            }
            try {
                String content = this.getSmsContent(cpid, spid, String.valueOf(vercode),type);

                logger.info("userid:" + phone + ", vercode:" + vercode + ", smscontent:" + content);
                String sendStatus = "";
                if (StringUtils.isNotEmpty(phone) && phone.length() > 3) {
                    String substring = phone.substring(0, 3);
                    if ("167".equals(substring) || "171".equals(substring) || "170".equals(substring)) {
                        //虚商短信发送
                        sendStatus = sendSmsCode(phone, "20200722001", vercode);
                        dop.put("resultcode","0");
                        service.setVisitcount(orderInfo);

                    } else {
                        //发送短信
                        sendStatus = SendSmsUtil.send(phone, content);
                        dop.put("resultcode","0");
                        logger.info("短信发送成功");
                        service.setVisitcount(orderInfo);
                    }
                } else {
                    throw new BusinessException("8009", "手机号不存在", new String[0]);
                }
                dop.put("vercode", (Object) vercode);
                dop.put("smsContent", (Object) content);
                TlVerifiCationCodeBean tvcc = new TlVerifiCationCodeBean();
                logger.info("sendStatus:" + sendStatus);
                tvcc.setCpid(cpid);
                tvcc.setUserid(phone);
                tvcc.setSendStatus(sendStatus);
                tvcc.setVercode(String.valueOf(vercode));
                tvcc.setChannel("");
                Date date = new Date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                tvcc.setMakeTime(simpleDateFormat.format(date));
                tvcc.setRemark("成功");
                sscd.insertTlVerifiCationCode(tvcc);
            } catch (Exception e2) {
                e2.printStackTrace();

                if (e2 instanceof BusinessException){
                    dop.put("resultcode", ((BusinessException) e2).getErrorcode());
                    dop.put("errorinfo",e2.getMessage());
                }else{
                    dop.put("resultcode","8000");
                    dop.put("errorinfo",e2.getMessage());
                }
                dop.put("remaintime", (Object) timeDifference);
                logger.error((Object) ("cpid=" + cpid + "phone=" + phone + "spid=" + spid + "channel=" + channel + "Error" + e2.getMessage()));
            }
        }
        dop.put("remaintime", (Object) timeDifference);
        if ("0".equals(flag)) {
            try {
                int i = StringUtils.isEmpty(sscd.checkTransfer(phone.trim())) ? 0 : Integer.parseInt(sscd.checkTransfer(phone.trim()));
                if (i > 0) {
                    dop.put("validflag", (Object) "0");
                } else {
                    i = StringUtils.isEmpty(sscd.checkArea(phone.substring(0, 7))) ? 0 : Integer.parseInt(sscd.checkArea(phone.substring(0, 7)));
                    if (i > 0) {
                        dop.put("validflag", (Object) "0");
                    } else {
                        dop.put("validflag", (Object) "1");
                    }
                }
            } catch (Exception e2) {
                e2.printStackTrace();

                if (e2 instanceof BusinessException){
                    dop.put("resultcode", ((BusinessException) e2).getErrorcode());
                    dop.put("errorinfo",e2.getMessage());
                }else{
                    dop.put("resultcode","8000");
                    dop.put("errorinfo",e2.getMessage());
                }
                logger.error((Object) ("cpid=" + cpid + "phone=" + phone + "spid=" + spid + "channel=" + channel + "Error" + e2.getMessage()));
                dop.put("validflag", (Object) "1");
            }
        }
        return dop;
    }

    public void concurrentCheck(String userid, String cpid) throws Exception {
        String url = this.dictionaryDao.getValue("smscheckurl");
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000L);
        String pwd = this.dictionaryDao.getValue("smscheckpwd");
        String channel = this.dictionaryDao.getValue("smscheckcchannel");
        String key = "controlsendsms" + userid + channel + cpid;
        String result = "";
        try {
            key = DesUtil.encode(key, pwd);
            String sign = MD5.MD5Encode("channel=" + channel + "&key=" + key + "&timestamp=" + timestamp + pwd);
            url = url + "?key=" + URLEncoder.encode(key, "utf-8") + "&channel=" + channel + "&sign=" + sign + "&timestamp=" + timestamp;
            result = URLUtil.get(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotEmpty(result)) {
            Map<?, ?> map = JSONObject.parseObject(result, Map.class);
            ;

            if (map.get("count") != null && NumberUtils.toLong((String) map.get("count")) > 1L) {
                logger.error((Object) (userid + "用户发送短信次数超过总量上限"));
                throw new BusinessException("8008", "并发请求，请稍后再试", new String[0]);
            }
        }
    }

    public void totalCheck(String userid) throws Exception {
        String url = this.dictionaryDao.getValue("smscheckurl");
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000L);
        String pwd = this.dictionaryDao.getValue("smscheckpwd");
        String channel = this.dictionaryDao.getValue("smschecktchannel");
        String key = "totalControlsendsms" + userid + channel;
        String result = "";
        try {
            key = DesUtil.encode(key, pwd);
            String sign = MD5.MD5Encode("channel=" + channel + "&key=" + key + "&timestamp=" + timestamp + pwd);
            url = url + "?key=" + URLEncoder.encode(key, "utf-8") + "&channel=" + channel + "&sign=" + sign + "&timestamp=" + timestamp;
            result = URLUtil.get(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotEmpty(result)) {
            Map<?, ?> map = JSONObject.parseObject(result, Map.class);
            if (map.get("count") != null && NumberUtils.toLong((String) map.get("count")) > NumberUtils.toLong(this.dictionaryDao.getValue("smschecktotalnum"))) {
                logger.error((Object) (userid + "用户发送短信次数超过总量上限"));
                throw new BusinessException("8008", "用户发送短信次数超过总量上限", new String[0]);
            }
        }
    }

    /**
     * 发送虚拟短信内容
     *
     * @param userid
     * @param contentid
     * @return
     */
    private String sendSmsCode(String userid, String contentid, Long code) throws BusinessException {
        String resp="";
        String url="";

        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());
            String vars = "{\"code\":" + code + "}";
            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");
            url = "http://111.206.134.43:809/xsbusi/sms/send?userid=" + usermob + "&smsid=" + smsid + "&timestamp="
                    + timestamp + "&sign=" + sign + "&contentid=" + contentid + "&vars=" + vars;
            resp = URLUtil.get(url);
        } catch (Exception e) {
            logger.info("虚商验证码发送失败");
            e.printStackTrace();
        }
        logger.info("虚商验证码路径:" + url);
        logger.info("调用虚商验证码后返回的参数:" + resp);
        Map map = JSON.parseObject(resp, Map.class);
        String resultcode = map.get("resultcode") + "";
        if ("0".equals(resultcode)) {
            logger.info("虚商验证码发送成功");
            return resultcode;
        } else {
            logger.info("虚商验证码发送失败");
            throw new BusinessException(resultcode,"虚商短信接口:"+map.get("errorinfo")+"",new String[0]);
        }

    }

    public String getSmsContent(String cpid, String spid, String vcode, String channel) throws SQLException {
        String content = "";
        content = this.smsContentDao.getContent(cpid, (spid == null) ? "" : spid, (channel == null) ? "" : channel);
        content = content.replace("${randomCode}", vcode);
        return content;
    }
}
