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.BussinessException;
import com.chinacreator.video.mapper.DictionaryDao;
import com.chinacreator.video.restful.dao.QueryCapOrderDao;
import com.chinacreator.video.restful.service.QueryCapOrderService;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.util.URLUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class QueryCapOrderController {


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


    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private QueryCapOrderDao queryCapOrderDao;

    @Autowired
    private QueryCapOrderService queryCapOrderService;


    @PostMapping("/queryCapOrder")
    public Map<String, Object> queryCapOrder(@RequestBody OrderInfo orderInfo) {
    	//日志记录
    	Map<String,Object> logmap = new HashMap<String,Object>();
    	logmap.put("invoke", "queryCapOrder");
        String resultCode = "-1";
        String resultInfo = "无订购关系";
        String msg="";
        orderInfo.setType("");
        orderInfo.setInvokeface("queryCapOrder");
        //获取子渠道标识，比如CAP，SHARE
        String subchannel = orderInfo.getSubchannel();
        if (StringUtils.isEmpty(subchannel)) {
        	subchannel = "";
        }
        try {
        queryCapOrderService.check(orderInfo);
        if ("1009".equals(orderInfo.getSpid())){
            throw new BussinessException("9001","芒果合约版产品不处理");
        }
        String productId = queryCapOrderDao.findProduct(orderInfo.getSpid());
        if (StringUtils.isEmpty(productId)){
            throw new BussinessException("8001","该spid:{"+orderInfo.getSpid()+"}没有计费点");
        }
         String url = dictionaryDao.getValue("OrderPushfmrowsURL");
         url = url + "?phone=" + orderInfo.getUserid();
            String resp = URLUtil.get(url);
            logger.info("cap查询返回的日志===="+resp);
            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 map1 = JSONObject.parseObject(String.valueOf(str), Map.class);
                            String product_id = String.valueOf(map1.get("PRODUCT_ID"));
                            if (productId.equals(product_id)) {
                                String endDate = String.valueOf(map1.get("END_DATE"));
                                if (getMaxDayOfThisMonth().equals(endDate)){
                                    resultCode = "1";
                                    resultInfo = "用户已退订";
                                }else{
                                    resultCode = "0";
                                    resultInfo = "用户已订购";
                                    try {
                                    	//添加子渠道标识
                                    	map1.put("SUBCHANNEL", subchannel);
                                        queryCapOrderService.addCapRev(map1);
                                        msg="成功添加反向通知";
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        msg="添加反向通知失败===="+e.getMessage();
                                    }
                                }
                            }
                        }
                    }
                } else {
                    resultCode = respCode;
                    resultInfo = (String) map.get("errorinfo");
                }
            }
        } catch (Exception e) {
            if (e instanceof  BussinessException){
                resultCode=((BussinessException) e).getCode();
                resultInfo=e.getMessage();
            }else{
                resultCode = "8000";
                resultInfo = "系统异常";
            }
            e.printStackTrace();

        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("resultCode", resultCode);
        resultMap.put("resultInfo", resultInfo);
        resultMap.put("msg", msg);
        
        //日志数据
    	logmap.put("reqData", orderInfo);
		logmap.put("rspData",resultMap);	
		
        //logger.info(orderInfo.getUserid() + "=====" + orderInfo.getSpid() + "====返回参数:" + resultMap);
        logger.info(JSON.toJSONString(logmap));
        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) {
        System.out.println(MD5.MD5Encode("changshi" + "1626084254155" + "Hzzxs2#a").equals("649667122e13c043432aaa8adf84fd01"));
    }
}

