package com.chinacreator.video.restful.controller;

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.restful.bean.ChannelOrgBean;
import com.chinacreator.video.restful.bean.SmsCheckBean;
import com.chinacreator.video.restful.dao.SmsNumberDao;
import com.chinacreator.video.restful.dao.SmsWhiteDao;
import com.chinacreator.video.restful.service.SendSmsCodeService;
import com.chinacreator.video.util.DesUtil;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.util.URLUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
public class SmsNumberAction {

    private static Logger logger = Logger.getLogger(SmsNumberAction.class);

    private String times="3"; // = "3";

    @Autowired
    private SmsWhiteDao smsWhiteDao;

    @Autowired
    private ChannelDao channelDao;

    @Autowired
    private SendSmsCodeService sendSmsCodeService;

    @Autowired
    private SmsNumberDao snd;

    @RequestMapping("/smsNumber")
    @ResponseBody
    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 vcode = jsonObject.getString("vcode");
        String timestamp = jsonObject.getString("timestamp");
        String channel = jsonObject.getString("channel");
        String spid = jsonObject.getString("spid");
        String flag = jsonObject.getString("flag");
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setChannel(channel);
        orderInfo.setCpid(cpid);
        orderInfo.setTimestamp(timestamp);
        orderInfo.setUserid(userid);
        orderInfo.setSpid(spid);
        logger.info("参数校验校验开始");
        sendSmsCodeService.busiCheck(jsonObject, "prizeauth", orderInfo);
        String phone = "";//ConfigUtil.decrypt(userid, cpid);
        String fakePhone = ""; //ConfigUtil.getFakeid(phone, cpid);
        ChannelOrgBean channelOrgBean = null;
        //渠道方接入
        channelOrgBean = channelDao.findByChannelId(channel);
        if (channelOrgBean == null || channelOrgBean.getStatus().equals("1")) {
            throw new BusinessException("9001", "渠道参数错误");
        }
        phone = DesUtil.decode(userid, channelOrgBean.getPassword());
        fakePhone = phone;

        logger.info("phone:" + phone + ", fakePhone:" + fakePhone + ", vcode:" + vcode);

        Map<String, Object> dop = new HashMap<>();
        SmsCheckBean smsCheckBean = snd.checkVcode(phone, cpid);
        if (smsWhiteDao.isBlackUserCanValidate(phone, cpid)>0) {
            throw new BusinessException("8007", "黑名单用户,短信验证失败", new String[0]);
        }
        if (smsCheckBean == null) {
            dop.put("userid", null);
            dop.put("resultCode", "8999");
            dop.put("errorInfo", "验证码已失效");
            dop.put("flowwarn", Integer.valueOf(1));
            return dop;
        } else if (smsCheckBean.getTimes() >= Integer.parseInt(times)) {
            dop.put("userid", null);
            dop.put("resultCode", "8998");
            dop.put("errorInfo", "验证码校验次数超过上限");
            dop.put("flowwarn", Integer.valueOf(1));
            return dop;
        }
        if (smsCheckBean.getVercode().equals(vcode)) {
            snd.diabled(smsCheckBean.getRowno());
            if ((cpid.equals("tencent")) && (queryOrder(phone, cpid))) {
                //渠道方接入
                channelOrgBean = channelDao.findByChannelId(channel);
                dop.put("userid", DesUtil.encode(phone, channelOrgBean.getPassword()));

            } else {
                //渠道方接入
                channelOrgBean = channelDao.findByChannelId(channel);
                dop.put("userid", DesUtil.encode(fakePhone, channelOrgBean.getPassword()));

            }
        } else {
            snd.addVcodeTimes(smsCheckBean.getRowno());
            dop.put("userid", null);
        }
        dop.put("resultCode","0");
        dop.put("flowwarn", Integer.valueOf(1));
        return dop;
    }

    public static boolean queryOrder(String userid, String cpid) throws Exception {
        try {
            String[] spids = {"79", "78", "81", "21135", "82", "83"};
            List<String> listspids = Arrays.asList(spids);
            String url = "http://10.199.99.51:809/orderQuery/userOrder?";
            //String url = "http://127.0.0.51:809/orderQuery/userOrder?";
            String channel = "zxOrderQ";
            String times = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
            String params = "userid=" + userid + "&cpid=" + cpid + "&channel=" + channel + "&time=" + times;
            String mkey = MD5.MD5Encode("/orderQuery/userOrder?" + params + "3dae9o03mde74wk4");
            url = url + params + "&mkey=" + mkey;
            String result = URLUtil.get(url);
            Map<?, ?> map = JSONObject.parseObject(result, Map.class);
            if (map.get("errcode").equals("0")) {
                List<Map<String, String>> list = (List<Map<String, String>>) map.get("data");
                for (Map<String, String> map2 : list) {
                    if (listspids.contains(map2.get("spid"))) {
                        if (map2.get("type").equals("0") && NumberUtils.toLong(map2.get("ordertime")) <= NumberUtils.toLong(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"))) {
                            return true;
                        } else {
                            if (NumberUtils.toLong(map2.get("endtime")) >= NumberUtils.toLong(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"))) {
                                return true;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) throws Exception, Exception {
        System.out.println(DesUtil.decode("qaAKeJlfWCnbcsNxH3nUVQ==", "7dea1gd5"));
    }
}