package com.chinacreator.video.service;

import com.alibaba.fastjson.JSONObject;
import com.chinacreator.video.bean.*;
import com.chinacreator.video.exception.WoInnovateException;
import com.chinacreator.video.mapper.CallerHeadDao;
import com.chinacreator.video.mapper.WoInnovateDao;
import com.chinacreator.video.thread.WoInnovateThread;
import com.chinacreator.video.util.AreaUtil;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.util.URLUtil;
import com.chinacreator.video.validate.WoInnovateValidate;
import com.chinacreator.video.web.WoInnovateController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

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

@Component
public class WoInnovateService {
    private static final Logger logger = LoggerFactory.getLogger(WoInnovateController.class);

    private static final  Logger log = LoggerFactory.getLogger("woInnovate");

    @Autowired
    WoInnovateDao woInnovateDao;

    @Autowired
    WoInnovateValidate woInnovateValidate;

    @Autowired
    CallerHeadDao callerHeadDao;

//1
    public List<String> findBySpInfoTable(){
        return woInnovateDao.findBySpInfoTable();
    }

    public void checkOrder(WoInnovateBean bean) throws Exception {
        woInnovateValidate.valiTime(bean);//验证时间戳

        //kuaiShouValidate.valiChannel(bean);//验证渠道
        woInnovateValidate.validate(bean);//验证参数

        woInnovateValidate.valiAppid(bean);//验证ip

        woInnovateValidate.tockenVali(bean);//验证tocken
    }

    public int checkStatus(String mobile, String skuId) {
        return woInnovateDao.checkStatus(mobile,skuId);
    }

    public String findStatus(String mobile, String skuId) {
        return woInnovateDao.findStatus(mobile,skuId);
    }

    public void checkBusinessNoticeType(WoInnovateBean bean) throws WoInnovateException {
        woInnovateValidate.checkBusinessNoticeType(bean);
    }

    public void checkOrderType(WoInnovateBean bean) throws WoInnovateException{
        woInnovateValidate.checkOrderType(bean);
    }

    /**
     * 订购
     * @param bean
     */
    @Transactional
    public void order(WoInnovateBean bean) throws Exception {
        Map<String, String> UNI_WCX_BODY = bean.getUNI_BSS_BODY();
        Map<String, String> UNI_WCX_HEAD = bean.getUNI_WCX_HEAD();
        Map<String, String> map1 = bean.getUNI_WCX_HEAD();
        try {
            //验证放在service层
            woInnovateValidate.tockenVali(bean);//验证tocken
            woInnovateValidate.validate(bean);//验证参数
        }catch (Exception e){
            UNI_WCX_BODY.put("businessNoticeStatus","21");
            UNI_WCX_HEAD = creatToken();
            JSONObject json = new JSONObject();
            json.put("UNI_WCX_HEAD", UNI_WCX_HEAD);
            json.put("UNI_WCX_BODY", UNI_WCX_BODY);
            String jsonParams = json.toJSONString();
            System.out.println(jsonParams);
            URLUtil.postJson(UNI_WCX_BODY.get("notifyUrl"),jsonParams);
            System.out.println("回调地址"+UNI_WCX_BODY.get("notifyUrl")+";参数"+jsonParams);
            return;
        }
        //回调地址
        String notifyUrl = UNI_WCX_BODY.get("notifyUrl");
        //用户号码
        String mobile = UNI_WCX_BODY.get("mobile");
        //skuid可能有多个
        String skuId = UNI_WCX_BODY.get("skuId");
        //所有商品id
        String[] split = skuId.split(",");
        //商品名称,不参与表中
        String goodsName = UNI_WCX_BODY.get("goodsName");
        //String startDate = UNI_WCX_BODY.get("startDate");
        Map<String, String> tokenMap = creatToken();
        //判断省份城市信息
        String substring = mobile.substring(0, 7);
        //省份判断接口
        AreaInfo areaInfo = AreaUtil.getAreaInfoByUserid(mobile);
        //有待确认，是否需要根据沃创新平台订单号或者我方在线订单号设置DB唯一约束，相同订单到达时判断是否已在库内
        //woInnovateDao.findCount(UNI_WCX_BODY.get(""));
        //城市
       // String area = areaInfo.getArea();
        //省份
        //String province = areaInfo.getProvince();
        //APPID
        //String appId = UNI_WCX_HEAD.get("AppId");
        //订购开始时间
        String orderTime = UNI_WCX_BODY.get("startDate");
        String spid = "";
        String cpid = "";
        String spids = "";
        try {
            for (int i = 0; i < split.length; i++) {
                //判断每一个产品是否有生效的订购关系
                int n = woInnovateDao.checkStatus(mobile,split[i]);
                System.out.println("订购关系共计"+n+"条");
                log.info("订购关系共计"+n+"条");
                if(n != 0){
                    //有订购关系,判断是否退订
                    //判断是否退订
                    String status = woInnovateDao.findStatus(mobile,split[i]);
                    System.out.println("订购状态"+status);
                    log.info("订购状态"+status);
                    if(status.equals("0")){
                        log.error(mobile+"订购失败");
                        System.out.println(mobile+"订购失败");
                        UNI_WCX_BODY.clear();
                        UNI_WCX_BODY.put("businessNoticeStatus","21");
                        UNI_WCX_BODY.put("businessNoticeType","2");
                        UNI_WCX_BODY.put("seriesNumber",map1.get("seriesNumber"));
                        UNI_WCX_BODY.put("orderId",map1.get("orderId"));
                        UNI_WCX_BODY.put("skuId",skuId);
                        UNI_WCX_BODY.put("mobile",mobile);
                        JSONObject json = new JSONObject();
                        UNI_WCX_BODY.put("businessNoticeType", "2");
                        json.put("UNI_WCX_HEAD", tokenMap);
                        json.put("UNI_WCX_BODY", UNI_WCX_BODY);
                        String jsonParams = json.toJSONString();
                        System.out.println(jsonParams);
                        String s = URLUtil.postJson(notifyUrl,jsonParams);
                        log.info("同步沃创新平台订购关系失败-->回调地址:"+notifyUrl+";参数"+jsonParams);
                        System.out.println("同步沃创新平台订购关系失败-->回调地址:"+notifyUrl+";参数"+jsonParams);
                        log.info("沃创新平台响应:"+s);
                        System.out.println("沃创新平台响应:"+s);
                        return;
                    }
                }
            }
            for (int i = 0; i < split.length; i++) {
                OrderRelationsBean orderRelationsBean = new OrderRelationsBean();
                //得到spid和cpid
                Map<String, String> map = woInnovateDao.findSpidBySkuId(split[i]);
                spid = map.get("SPID");
                cpid = map.get("CPID");
                //spids += spid+",";
                orderRelationsBean.setUserid(mobile);
                orderRelationsBean.setCpid(cpid);
                orderRelationsBean.setSpid(spid);
                orderRelationsBean.setStatus(0);
                orderRelationsBean.setProvince(areaInfo.getProvince());
                orderRelationsBean.setArea(areaInfo.getArea());
                orderRelationsBean.setOrderstatus("2");
                orderRelationsBean.setOrdertime(orderTime);
                //渠道方信息
                orderRelationsBean.setOrderchannel(UNI_WCX_HEAD.get("AppId"));
                orderRelationsBean.setChannel(UNI_WCX_HEAD.get("AppId"));
                //先判断当前号码当前产品是否已有订购关系,如果有的话更新订购关系，没有的话存入订购关系表
                int count = woInnovateDao.findRelationCount(mobile,spid);
                System.out.println("当前订购关系共计"+count+"条");
                if(count != 0){
                    //有订购关系，更新当前订购关系
                    System.out.println("有订购关系，更新当前订购关系");
                    log.info("有订购关系，更新当前订购关系");
                    woInnovateDao.updateRelation(orderRelationsBean);
                    log.info("生成活动关系");
                    woInnovateDao.addBusshandle(orderRelationsBean);
                }else {//无订购关系,存入订购关系表
                    System.out.println("无订购关系,存入订购关系表");
                    log.info("无订购关系,存入订购关系表");
                    woInnovateDao.add(orderRelationsBean);
                    log.info("生成活动关系");
                    woInnovateDao.addBusshandle(orderRelationsBean);
                }

            }
            //请求信息存入日志表
            LogBean logBean = new LogBean();
            logBean.setDeductionFailureDesc(UNI_WCX_BODY.get("deductionFailureDesc"));
            logBean.setMobile(mobile);
            logBean.setDeductionStatus(UNI_WCX_BODY.get("deductionStatus"));
            logBean.setGoodsName(goodsName);
            logBean.setSkuPrice(UNI_WCX_BODY.get("skuPrice"));
            logBean.setTdTime(UNI_WCX_BODY.get("tdTime"));
            logBean.setIsFirstOrder(UNI_WCX_BODY.get("isFirstOrder"));
            logBean.setOrderType(UNI_WCX_BODY.get("orderType"));
            logBean.setStartDate(UNI_WCX_BODY.get("startDate"));
            logBean.setSkuId(UNI_WCX_BODY.get("skuId"));
            logBean.setNotifyUrl(UNI_WCX_BODY.get("notifyUrl"));
            logBean.setTimeStamp(UNI_WCX_BODY.get("timeStamp"));
            logBean.setSeriesNumber(UNI_WCX_BODY.get("seriesNumber"));
            logBean.setOrderId(UNI_WCX_BODY.get("orderId"));
            logBean.setBusinessNoticeType(UNI_WCX_BODY.get("businessNoticeType"));
            logBean.setEndDate(UNI_WCX_BODY.get("endDate"));
            woInnovateDao.saveLog(logBean);
            //所有数据封装完毕,存表
            //woInnovateDao.add(list);
            //调用沃创新侧接口响应
            JSONObject json = new JSONObject();
            UNI_WCX_BODY.clear();
            UNI_WCX_BODY.put("businessNoticeStatus","20");
            UNI_WCX_BODY.put("businessNoticeType","2");
            UNI_WCX_BODY.put("seriesNumber",logBean.getSeriesNumber());
            UNI_WCX_BODY.put("orderId",logBean.getOrderId());
            UNI_WCX_BODY.put("skuId",skuId);
            UNI_WCX_BODY.put("mobile",mobile);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = format.format(new Date());
            UNI_WCX_BODY.put("timeStamp",dateStr);
            json.put("UNI_WCX_HEAD", tokenMap);
            json.put("UNI_WCX_BODY", UNI_WCX_BODY);
            String jsonParams = json.toJSONString();
            System.out.println(jsonParams);
            String s = URLUtil.postJson(notifyUrl, jsonParams);
            log.info("同步沃创新平台订购关系成功-->回调地址:"+notifyUrl+";参数"+jsonParams);
            System.out.println("同步沃创新平台订购关系成功-->回调地址:"+notifyUrl+";参数"+jsonParams);
            log.info("沃创新平台响应:"+s);
            System.out.println("沃创新平台响应:"+s);
        }catch (Exception e){
            e.printStackTrace();
            log.error(mobile+"订购失败"+e.getMessage());
            UNI_WCX_BODY.clear();
            UNI_WCX_BODY.put("businessNoticeStatus","21");
            UNI_WCX_BODY.put("businessNoticeType","2");
            UNI_WCX_BODY.put("seriesNumber",map1.get("seriesNumber"));
            UNI_WCX_BODY.put("orderId",map1.get("orderId"));
            UNI_WCX_BODY.put("skuId",skuId);
            UNI_WCX_BODY.put("mobile",mobile);
            JSONObject json = new JSONObject();
            UNI_WCX_BODY.put("businessNoticeType", "2");
            json.put("UNI_WCX_HEAD", tokenMap);
            json.put("UNI_WCX_BODY", UNI_WCX_BODY);
            String jsonParams = json.toJSONString();
            System.out.println(jsonParams);
            URLUtil.postJson(notifyUrl,jsonParams);
            log.info("同步沃创新平台订购关系失败-->回调地址:"+notifyUrl+";参数"+jsonParams);
            System.out.println("同步沃创新平台订购关系失败-->回调地址:"+notifyUrl+";参数"+jsonParams);
        }
    }

    /**
     * 退订接口，收到退订请求后设置退订时间为当月最后一天23:59:59
     * @param bean
     */
    public void unsubscribe(WoInnovateBean bean) throws Exception {

        Map<String, String> UNI_BSS_BODY = bean.getUNI_BSS_BODY();
        Map<String, String> map1 = bean.getUNI_BSS_BODY();
        Map<String, String> UNI_WCX_HEAD = bean.getUNI_WCX_HEAD();
        //回调地址
        String notifyUrl = UNI_BSS_BODY.get("notifyUrl");
        //用户号码
        String mobile = UNI_BSS_BODY.get("mobile");
        //skuid可能有多个
        String skuId = UNI_BSS_BODY.get("skuId");
        //得到商品id数组
        String[] split = skuId.split(",");
        String spid = "";
        String cpid = "";
        try {
            //退订
            for (int i = 0; i < split.length; i++) {
                OrderRelationsBean orderRelationsBean = new OrderRelationsBean();
                //得到spid和cpid
                Map<String, String> map = woInnovateDao.findSpidBySkuId(split[i]);
                spid = map.get("SPID");
                cpid = map.get("CPID");
                //spids += spid+",";

                orderRelationsBean.setUserid(mobile);
                orderRelationsBean.setCpid(cpid);
                orderRelationsBean.setSpid(spid);
                orderRelationsBean.setStatus(0);
                //orderRelationsBean.setProvince(areaInfo.getProvince());
                //orderRelationsBean.setArea(areaInfo.getArea());
                orderRelationsBean.setOrderstatus("2");
                //orderRelationsBean.setOrdertime(orderTime);
                orderRelationsBean.setOrderchannel(UNI_WCX_HEAD.get("AppId"));
                orderRelationsBean.setChannel(UNI_WCX_HEAD.get("AppId"));
                //修改订购关系表订购状态
                woInnovateDao.add(orderRelationsBean);
                //请求信息存入日志表
                LogBean logBean = new LogBean();
                logBean.setDeductionFailureDesc(UNI_BSS_BODY.get("deductionFailureDesc"));
                logBean.setMobile(mobile);
                logBean.setDeductionStatus(UNI_BSS_BODY.get("deductionStatus"));
                logBean.setGoodsName(UNI_BSS_BODY.get("goodsName"));
                logBean.setSkuPrice(UNI_BSS_BODY.get("skuPrice"));
                logBean.setTdTime(UNI_BSS_BODY.get("tdTime"));
                logBean.setIsFirstOrder(UNI_BSS_BODY.get("isFirstOrder"));
                logBean.setOrderType(UNI_BSS_BODY.get("orderType"));
                logBean.setStartDate(UNI_BSS_BODY.get("startDate"));
                logBean.setSkuId(UNI_BSS_BODY.get("skuId"));
                logBean.setNotifyUrl(UNI_BSS_BODY.get("notifyUrl"));
                logBean.setTimeStamp(UNI_BSS_BODY.get("timeStamp"));
                logBean.setSeriesNumber(UNI_BSS_BODY.get("seriesNumber"));
                logBean.setOrderId(UNI_BSS_BODY.get("orderId"));
                logBean.setBusinessNoticeType(UNI_BSS_BODY.get("businessNoticeType"));
                logBean.setEndDate(UNI_BSS_BODY.get("endDate"));
                woInnovateDao.saveLog(logBean);
                //响应
                JSONObject json = new JSONObject();
                UNI_BSS_BODY.clear();
                UNI_BSS_BODY.put("businessNoticeStatus","30");
                UNI_BSS_BODY.put("businessNoticeType","3");
                UNI_BSS_BODY.put("seriesNumber",logBean.getSeriesNumber());
                UNI_BSS_BODY.put("orderId",logBean.getOrderId());
                UNI_BSS_BODY.put("skuId",skuId);
                UNI_BSS_BODY.put("mobile",mobile);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = format.format(new Date());
                UNI_BSS_BODY.put("timeStamp",dateStr);
                json.put("UNI_WCX_HEAD", UNI_WCX_HEAD);
                json.put("UNI_BSS_BODY", UNI_BSS_BODY);
                String jsonParams = json.toJSONString();
                System.out.println(jsonParams);
                URLUtil.postJson(notifyUrl,jsonParams);
                System.out.println("回调地址"+notifyUrl+";参数"+jsonParams);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error(mobile+"退订失败"+e.getMessage());
            UNI_BSS_BODY.clear();
            UNI_BSS_BODY.put("businessNoticeStatus","31");
            UNI_BSS_BODY.put("businessNoticeType","3");
            UNI_BSS_BODY.put("seriesNumber",map1.get("seriesNumber"));
            UNI_BSS_BODY.put("orderId",map1.get("orderId"));
            UNI_BSS_BODY.put("skuId",skuId);
            UNI_BSS_BODY.put("mobile",mobile);
            JSONObject json = new JSONObject();
            UNI_BSS_BODY.put("businessNoticeType", "2");
            json.put("UNI_WCX_HEAD", UNI_WCX_HEAD);
            json.put("UNI_BSS_BODY", UNI_BSS_BODY);
            String jsonParams = json.toJSONString();
            System.out.println(jsonParams);
            URLUtil.postJson(notifyUrl,jsonParams);
            System.out.println("回调地址"+notifyUrl+";参数"+jsonParams);
            //URLUtil.postJson(notifyUrl,jsonParams);

        }
    }

    /**
     * 生成token
     */
    public Map<String,String> creatToken(){
        String APP_ID = "WCX20210428095736620";
        String TRANS_ID = "202104280957366201111";
        String app_secret = "W54261150";
        String unCheckTocken = "APP_ID"+APP_ID+"TRANS_ID"+TRANS_ID+app_secret;
        String md5Encode = MD5.MD5Encode(unCheckTocken);
        String s = md5Encode.toLowerCase();
        Map<String,String> map = new HashMap<>();
        map.put("AppId",APP_ID);
        map.put("Transid",TRANS_ID);
        map.put("Token",s);
        return map;
    }

}
