package com.chinacreator.video.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinacreator.video.bean.KuaiShouHelpBean;
import com.chinacreator.video.bean.WoInnovateBean;
import com.chinacreator.video.dto.DataOutPipe;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.exception.WoInnovateException;
import com.chinacreator.video.service.WoInnovateService;
import com.chinacreator.video.thread.WoInnovateThread;
import com.chinacreator.video.util.URLUtil;
import com.chinacreator.video.validate.WoInnovateValidate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class WoInnovateController {
    private static final Logger log = LoggerFactory.getLogger("woInnovate");

    @Autowired
    WoInnovateService woInnovateService;

    @Autowired
    WoInnovateValidate woInnovateValidate;

    @Autowired
    RedisTemplate redisTemplate;


    /**
     * 验证接口，用于判断用户是否具有资格订购该产品
     * @param
     * @return
     * @throws Exception
     */
    //1
    @RequestMapping(value = "/userqualification",method = RequestMethod.POST)
    public String hand(@RequestBody Map<String,Map<String,String>> map) throws Exception {
        WoInnovateBean bean = new WoInnovateBean();
        Map<String, String> UNI_BSS_BODY = map.get("UNI_BSS_BODY");
        Map<String, String> UNI_WCX_HEAD = map.get("UNI_WCX_HEAD");
        bean.setUNI_BSS_BODY(UNI_BSS_BODY);
        bean.setUNI_WCX_HEAD(UNI_WCX_HEAD);
        Map<String,Object> logmap = new HashMap<String,Object>();
        log.info("请求参数bean"+bean.toString());
        log.info("请求参数map"+map.toString());
        //是否有订购资格，默认为10-无订购资格
        String businessNoticeStatus = "10";
        String respCode = "";
        String respDesc = "";
        String seriesNumber = UUID.randomUUID().toString();
        Map<String, String> head = bean.getUNI_WCX_HEAD();
        Map<String, String> body = bean.getUNI_BSS_BODY();
        System.out.println("查询参数"+bean);

        //设置接口限制参数
        bean.getUNI_BSS_BODY().put("INVOKEFACE","userqualification");
        try {
            logmap.put("reqData", bean);
            //业务验证,需要验证ip,Token等信息
            woInnovateService.checkOrder(bean);
            //验证通过，查询是否具有资格
            //1为购买资格查询
            String businessNoticeType = body.get("businessNoticeType");
            //手机号
            String mobile = body.get("mobile");
            //商品id
            String skuId = body.get("skuId");
            //请求时间
            String timestamp = body.get("timestamp");
            //查询spInfo表中是否有对应产品
            List<String> list = woInnovateService.findBySpInfoTable();
            //循环表中所有产品
            for (String s : list) {
                //得到产品集合判断是否在其中，
                if (s.equals(skuId)){
                    //spinfo表中有可用产品,还需要判断是否有生效的订购关系，用户处于未订购/已退订状态下，应返回“有资格”
                    int i = woInnovateService.checkStatus(mobile,skuId);
                    if(i != 0){
                        //判断是否退订
                            String status = woInnovateService.findStatus(mobile,skuId);
                            if(status.equals("1")){
                                //1为无生效订购关系,0为有生效订购关系
                                businessNoticeStatus = "11";
                        }else {
                                //无订购资格
                                businessNoticeStatus = "10";
                            }
                    }else {
                        //订购关系表中没有相应数据,判断有资格
                        businessNoticeStatus = "11";
                    }
                break;
                }
            }
            respCode = "00000";
            respDesc = "成功";
            //设置响应参数
            body.put("respCode",respCode);
            body.put("businessNoticeStatus",businessNoticeStatus);
            body.put("seriesNumber",seriesNumber);
            body.put("respDesc",respDesc);
        }catch (Exception e){
            e.printStackTrace();
            log.info(e.getMessage());
            respCode = "40009";
            respDesc = "出现异常，"+e.getMessage();
            if(e instanceof WoInnovateException) {
                respCode = ((WoInnovateException) e).getUNI_WCX_BODY().get("respCode");
                respDesc = ((WoInnovateException) e).getUNI_WCX_BODY().get("respDesc");
                logmap.put("rspData", body);
                logmap.put("respCode", respCode);
                logmap.put("respDesc", respDesc);
                //throw new WoInnovateException(logmap, head);
            }else {
                //throw new Exception()/;
            }
        }finally {
            logmap.put("rspData", body);
            logmap.put("respCode", respCode);
            logmap.put("respDesc", respDesc);
            log.info(JSON.toJSONString(logmap)); //写日志文件
        }
        UNI_WCX_HEAD = bean.getUNI_WCX_HEAD();
        UNI_BSS_BODY = bean.getUNI_BSS_BODY();

        Map<String, String> tokenMap = woInnovateService.creatToken();
        JSONObject json = new JSONObject();
        json.put("UNI_WCX_HEAD", tokenMap);
        json.put("UNI_BSS_BODY", UNI_BSS_BODY);
        String s = JSON.toJSONString(json);
        System.out.println(s);
        //将订单号存redis
        //redisTemplate.opsForValue().set(seriesNumber, "1",60, TimeUnit.SECONDS);
        return s;
    }

    /**
     * 订购/退订异步接口，接收参数后先返回success，处理完后进行回调
     */
    /*@RequestMapping("/businessnotice")
    public void business(@RequestBody Map<String,Map<String,String>> map) throws Exception {
        WoInnovateBean bean = new WoInnovateBean();

        Map<String, String> UNI_WCX_BODY = map.get("UNI_WCX_BODY");
        Map<String, String> UNI_WCX_HEAD = map.get("UNI_WCX_HEAD");
        String seriesNumber = UNI_WCX_HEAD.get("seriesNumber");
        String orderId = UNI_WCX_BODY.get("orderId");
        String skuId = UNI_WCX_BODY.get("skuId");
        String mobile = UNI_WCX_BODY.get("mobile");
        String businessNoticeType1 = UNI_WCX_BODY.get("businessNoticeType");
        String notifyUrl = UNI_WCX_BODY.get("notifyUrl");
        bean.setUNI_BSS_BODY(UNI_WCX_BODY);
        bean.setUNI_WCX_HEAD(UNI_WCX_HEAD);
        Map<String,Object> logmap = new HashMap<String,Object>();
        log.info("请求参数bean"+bean.toString());
        log.info("请求参数map"+map.toString());
        String respCode = "";
        String respDesc = "";
        //String seriesNumber = UUID.randomUUID().toString();
        Map<String, String> head = bean.getUNI_WCX_HEAD();
        Map<String, String> body = bean.getUNI_BSS_BODY();
        System.out.println(bean);
        //设置接口验证信息
        bean.getUNI_BSS_BODY().put("INVOKEFACE","businessnotice");
        try {
            //判断是否在redis中能查询到部门流水号
            logmap.put("reqData", bean);
            //业务验证,需要验证ip,Token等信息
            woInnovateService.checkOrder(bean);
            //参数验证通过,判断业务类型
            String businessNoticeType = bean.getUNI_BSS_BODY().get("businessNoticeType");
            //验证业务类型
            woInnovateService.checkBusinessNoticeType(bean);
            //验证订单类型
            woInnovateService.checkOrderType(bean);
            switch (businessNoticeType){
                case "2":
                    //开启订购线程
                    woInnovateService.order(bean);
                    break;
                *//*case "3":
                    //退订
                    woInnovateService.unsubscribe(bean);
                    break;*//*
            }
        }catch (Exception e){
            e.printStackTrace();
            log.info(e.getMessage());
            respCode = "40009";
            respDesc = "出现异常，"+e.getMessage();
            if(e instanceof WoInnovateException) {
                respCode = ((WoInnovateException) e).getUNI_WCX_BODY().get("respCode");
                respDesc = ((WoInnovateException) e).getUNI_WCX_BODY().get("respDesc");
                logmap.put("rspData", body);
                logmap.put("respCode", respCode);
                logmap.put("respDesc", respDesc);
                UNI_WCX_BODY.clear();
                JSONObject json = new JSONObject();
                UNI_WCX_BODY.put("respCode","20003");
                UNI_WCX_BODY.put("respDesc",((WoInnovateException) e).getUNI_WCX_BODY().get("respDesc"));
                UNI_WCX_BODY.put("businessNoticeType",businessNoticeType1);
                UNI_WCX_BODY.put("businessNoticeStatus","21");
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = format.format(new Date());
                UNI_WCX_BODY.put("timeStamp",dateStr);
                UNI_WCX_BODY.put("skuId",skuId);
                UNI_WCX_BODY.put("mobile",mobile);
                UNI_WCX_BODY.put("seriesNumber",seriesNumber);
                UNI_WCX_BODY.put("orderId",orderId);
                //重新创建请求头
                Map<String, String> map1 = woInnovateService.creatToken();
                json.put("UNI_WCX_HEAD", map1);
                json.put("UNI_WCX_BODY", UNI_WCX_BODY);
                URLUtil.postJson(notifyUrl,json.toJSONString());
            }else {
                //throw new Exception()/;
            }
        }finally {
            logmap.put("rspData", body);
            logmap.put("respCode", respCode);
            logmap.put("respDesc", respDesc);
            log.info(JSON.toJSONString(logmap)); //写日志文件
        }
        UNI_WCX_HEAD = bean.getUNI_WCX_HEAD();
        UNI_WCX_BODY = bean.getUNI_BSS_BODY();
        JSONObject json = new JSONObject();
        json.put("UNI_WCX_HEAD", UNI_WCX_HEAD);
        json.put("UNI_WCX_BODY", UNI_WCX_BODY);
        String s = JSON.toJSONString(json);
        return;
    }*/
    //订购
    @RequestMapping("/businessnotice")
    public String business(@RequestBody Map<String,Map<String,String>> map) throws Exception {
        WoInnovateBean bean = new WoInnovateBean();

        Map<String, String> UNI_WCX_BODY = map.get("UNI_WCX_BODY");
        Map<String, String> UNI_WCX_HEAD = map.get("UNI_WCX_HEAD");
        String seriesNumber = UNI_WCX_BODY.get("seriesNumber");
        String orderId = UNI_WCX_BODY.get("orderId");
        String skuId = UNI_WCX_BODY.get("skuId");
        String mobile = UNI_WCX_BODY.get("mobile");
        String businessNoticeType1 = UNI_WCX_BODY.get("businessNoticeType");
        String notifyUrl = UNI_WCX_BODY.get("notifyUrl");
        bean.setUNI_BSS_BODY(UNI_WCX_BODY);
        bean.setUNI_WCX_HEAD(UNI_WCX_HEAD);
        Map<String,Object> logmap = new HashMap<String,Object>();
        log.info("请求参数bean"+bean.toString());
        log.info("请求参数map"+map.toString());
        String respCode = "";
        String respDesc = "";
        //String seriesNumber = UUID.randomUUID().toString();
        Map<String, String> head = bean.getUNI_WCX_HEAD();
        Map<String, String> body = bean.getUNI_BSS_BODY();
        System.out.println(bean);
        //设置接口验证信息
        bean.getUNI_BSS_BODY().put("INVOKEFACE","businessnotice");
        try {
            //判断是否在redis中能查询到部门流水号
            logmap.put("reqData", bean);
            //业务验证,需要验证ip,Token等信息
            //woInnovateValidate.valiTime(bean);
            woInnovateValidate.valiAppid(bean);
            //woInnovateValidate.validate(bean);//验证参数
            //woInnovateValidate.tockenVali(bean);//验证tocken
            //参数验证通过,判断业务类型
            String businessNoticeType = bean.getUNI_BSS_BODY().get("businessNoticeType");
            //验证业务类型
            //woInnovateService.checkBusinessNoticeType(bean);
            //验证订单类型
            //woInnovateService.checkOrderType(bean);
            switch (businessNoticeType){
                case "2":
                    //开启订购线程
                    WoInnovateThread woInnovateThread = new WoInnovateThread(bean);
                    Thread t1 = new Thread(woInnovateThread);
                    t1.start();
                    respCode = "00000";
                    respDesc = "接收成功";
                    body.put("respCode",respCode);
                    body.put("respDesc",respDesc);
                    Map<String, String> tokenMap = woInnovateService.creatToken();
                    JSONObject json = new JSONObject();
                    json.put("UNI_WCX_HEAD", tokenMap);
                    json.put("UNI_WCX_BODY", UNI_WCX_BODY);
                    String s = JSON.toJSONString(json);
                    log.info("接收订购信息success,响应:"+s);
                    return s;
                /*case "3":
                    //退订
                    woInnovateService.unsubscribe(bean);
                    break;*/
            }
        }catch (Exception e){
            e.printStackTrace();
            log.info(e.getMessage());
            respCode = "40009";
            respDesc = "出现异常，"+e.getMessage();
            if(e instanceof WoInnovateException) {
                respCode = ((WoInnovateException) e).getUNI_WCX_BODY().get("respCode");
                respDesc = ((WoInnovateException) e).getUNI_WCX_BODY().get("respDesc");
                logmap.put("rspData", body);
                logmap.put("respCode", respCode);
                logmap.put("respDesc", respDesc);
                UNI_WCX_BODY.clear();
                JSONObject json = new JSONObject();
                UNI_WCX_BODY.put("respCode","20003");
                UNI_WCX_BODY.put("respDesc",((WoInnovateException) e).getUNI_WCX_BODY().get("respDesc"));
                UNI_WCX_BODY.put("businessNoticeType",businessNoticeType1);
                //UNI_WCX_BODY.put("businessNoticeStatus","21");
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = format.format(new Date());
                UNI_WCX_BODY.put("timeStamp",dateStr);
                UNI_WCX_BODY.put("skuId",skuId);
                UNI_WCX_BODY.put("mobile",mobile);
                UNI_WCX_BODY.put("seriesNumber",seriesNumber);
                UNI_WCX_BODY.put("orderId",orderId);
                //重新创建请求头
                Map<String, String> map1 = woInnovateService.creatToken();
                json.put("UNI_WCX_HEAD", map1);
                json.put("UNI_WCX_BODY", UNI_WCX_BODY);
                //URLUtil.postJson(notifyUrl,json.toJSONString());
            }else {
                //throw new Exception()/;
            }
        }finally {
            logmap.put("rspData", body);
            logmap.put("respCode", respCode);
            logmap.put("respDesc", respDesc);
            //log.info(JSON.toJSONString(logmap)); //写日志文件
        }
        UNI_WCX_HEAD = bean.getUNI_WCX_HEAD();
        UNI_WCX_BODY = bean.getUNI_BSS_BODY();
        JSONObject json = new JSONObject();
        json.put("UNI_WCX_HEAD", UNI_WCX_HEAD);
        json.put("UNI_WCX_BODY", UNI_WCX_BODY);
        String s = JSON.toJSONString(json);
        log.info("接收订购信息fail,响应:"+s);
        return s;
    }
}
