package com.chinacreator.video.restful.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.chinacreator.video.bean.ChannelBean;
import com.chinacreator.video.bean.CpSpBean;
import com.chinacreator.video.bean.HandleOrgMap;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.*;
import com.chinacreator.video.restful.dao.QueryCapOrderDao;
import com.chinacreator.video.util.DesUtil;
import com.chinacreator.video.util.RedisService;
import com.chinacreator.video.util.URLUtil;
import com.chinacreator.video.validate.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class QueryCapOrderService {

    @Autowired
    private TimetampValidate timetampValidate;

    @Autowired
    private IpValidate ipValidate;

    @Autowired
    private SignValidate signValidate;

    @Autowired
    private ChannelValidate channelValidate;

    @Autowired
    private MobValidate mobValidate;

    @Autowired
    private QueryCapOrderDao queryCapOrderDao;

    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private ChannelDao channelDao;

    private Logger logger = LoggerFactory.getLogger("queryCapOrder");


    public void check(OrderInfo orderInfo) throws Exception {
        //timetamp验证
        timetampValidate.validate(orderInfo.getTimestamp());
        //渠道验证
        channelValidate.validate(orderInfo.getChannel());
        //ip验证
        ipValidate.volidate(orderInfo, "1");
        //签名验证
        signValidate.validate(orderInfo);
        //手机号码验证
       validate(orderInfo);
    }

    public void validate(OrderInfo orderInfo) throws Exception {
        String userid = orderInfo.getUserid();
        if (StringUtils.isEmpty(userid)) {
            throw new BussinessException("10007", "手机号不能为空");
        }
        ChannelBean channelBean = channelDao.queryChannel(orderInfo.getChannel());
        try {
            userid = DesUtil.decode(userid, channelBean.getPassword());
            if (isValid(userid) && userid.length() == 11) {
                orderInfo.setUserid(userid);
            } else {
                throw new BussinessException("10009", "手机号错误");
            }
        } catch (Exception e) {
            if (e instanceof BussinessException) {
                throw e;
            } else {
                throw new BussinessException("10008", "手机号加密错误");
            }
        }
    }

    private boolean isValid(String usermob) {
        if (usermob == null) {
            return false;
        }
        usermob = usermob.replaceAll("[\\s-]", "");

        return usermob.matches(".*(1\\d{10}).*");
    }

    public void addCapRev(Map<String, String> map) {
        queryCapOrderDao.addCapRev(map);
    }


    public Map<String, String> queryCap(OrderInfo orderInfo) throws BussinessException {
        String resultCode = "-1";
        String resultInfo = "无订购关系";
        String syncStatus="-1";
        String msg = "";
        String resp="";
        try {
            //获取子渠道标识，比如CAP，SHARE
            String subchannel = orderInfo.getSubchannel();
            if (StringUtils.isEmpty(subchannel)) {
                subchannel = "";
            }
            if ("1009".equals(orderInfo.getSpid())) {
                throw new BussinessException("9001", "芒果合约版产品不处理");
            }
            List<String> productList = queryCapOrderDao.getProduct(orderInfo.getCpid());
            if (productList == null || productList.size() == 0) {
                throw new BussinessException("8001", "该spid:{" + orderInfo.getSpid() + "}没有计费点");
            }
            String url = dictionaryDao.getValue("OrderPushfmrowsURL");
            url = url + "?phone=" + orderInfo.getUserid();
            try {
                resp = URLUtil.get(url, 30000);
            } catch (Exception e) {
               int count= queryCapOrderDao.insertSyncList(orderInfo);
               if (count>0){
                   syncStatus="0";
                   resultInfo="已添加同步关系表";
               }
                e.printStackTrace();
            }
            logger.info("cap查询返回的日志----" + resp);
            List<Map<String, String>> resultList = new ArrayList<>();
            if (StringUtils.isNotEmpty(resp)) {
                Map map = JSONObject.parseObject(resp, Map.class);
                String respCode = (String) map.get("resultcode");
                if ("0".equals(respCode)) {
                    String data = String.valueOf(map.get("data"));
                    Map dataMap = JSONObject.parseObject(data, Map.class);
                    String dataStr = String.valueOf(dataMap.get("DATA"));
                    List list = JSONObject.parseObject(dataStr, List.class);
                    if (list != null && list.size() > 0) {
                        for (Object str : list) {
                            Map<String, String> bodyMap = JSONObject.parseObject(String.valueOf(str), new TypeReference<HashMap<String, String>>() {
                            });
                            String product_id = bodyMap.get("PRODUCT_ID");
                            if (productList.contains(product_id)) {
                                String endDate = String.valueOf(bodyMap.get("END_DATE"));
                                bodyMap.put("SUBCHANNEL", subchannel);
                                if (getMaxDayOfThisMonth().equals(endDate)) {
                                    resultCode = "1";
                                    resultInfo = "用户已退订";
                                } else {
                                    resultCode = "0";
                                    resultInfo = "用户已订购";
                                }
                                bodyMap.put("resultCode", resultCode);
                                bodyMap.put("resultInfo", resultInfo);
                                resultList.add(bodyMap);
                            }
                        }
                    }
                } else {
                    resultCode = respCode;
                    resultInfo = (String) map.get("errorinfo");
                }
            }
            if (!"-1".equals(resultCode)) {
                for (Map<String, String> map : resultList) {
                    orderInfo.setProductid(map.get("PRODUCT_ID"));
                    String bodyCode = map.get("resultCode");
                    String status = queryCapOrderDao.queryUserOrder(orderInfo);
                    if (StringUtils.isNotEmpty(status) && status.equals(bodyCode)) {
                        try {
                            queryCapOrderDao.insertSync(orderInfo);
                            msg = "已添加同步关系表";
                        } catch (Exception e) {
                            e.printStackTrace();
                            msg = "添加同步关系表失败----" + e.getMessage();
                        }
                    } else {
                        if ("0".equals(bodyCode)) {
                            try {
                                queryCapOrderDao.addCapRev(map);
                                msg = "成功添加反向通知";
                            } catch (Exception e) {
                                e.printStackTrace();
                                msg = "添加反向通知失败----" + e.getMessage();
                            }
                        } else {
                            try {
                                //添加子渠道标识
                                queryCapOrderDao.addCapRevCancel(map);
                                msg = "成功添加反向通知";
                            } catch (Exception e) {
                                e.printStackTrace();
                                msg = "添加反向通知失败----" + e.getMessage();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            if (e instanceof BussinessException) {
                resultCode = ((BussinessException) e).getCode();
                resultInfo = e.getMessage();
            } else {
                resultCode = "8000";
                resultInfo = "系统异常";
            }
            e.printStackTrace();
            throw new BussinessException(resultCode, resultInfo);

        }
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("resultCode", "-1".equals(resultCode) ?syncStatus:resultCode);
        resultMap.put("resultInfo", resultInfo);
        resultMap.put("msg", msg);
        return resultMap;
    }

    public static String getMaxDayOfThisMonth() {
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyyMMdd");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DATE, 1);    //主要就是这个roll方法
        cal.roll(Calendar.DATE, -1);
        return myFormatter.format(cal.getTime()) + "235959";
    }

    public static void main(String[] args) throws Exception {
        System.out.println(DesUtil.encode("18622842320","zxsme2#a"));

    }
}
