package com.chinacreator.video.restful.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chinacreator.video.bean.ChannelBean;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.*;
import com.chinacreator.video.service.CommonService;
import com.chinacreator.video.util.*;
import com.chinacreator.video.validate.*;
import org.apache.commons.lang.StringUtils;
import org.jboss.logging.Logger;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订购关系查询服务类
 *
 * @author zhengrong.yan
 * @date 202105008
 */
@Component
public class RelationQueryService {

    @Autowired
    private ChannelValidate channelValidate;

    @Autowired
    private IpValidate ipValidate;

    @Autowired
    private TimetampValidate timetampValidate;

    @Autowired
    private SignValidate signValidate;

    @Autowired
    private ParamValidate paramValidate;

    @Autowired
    private CommConfDao commConfDao;

    @Autowired
    private CommonService commonService;

    @Autowired
    private RelationQueryDao relationQueryDao;

    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private ChannelDao channelDao;

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

    private static Logger log = Logger.getLogger("relationQuery");

    public void busiCheck(OrderInfo orderInfo) throws Exception {
        //timetamp验证
        timetampValidate.validate(orderInfo.getTimestamp());
        //渠道验证
        channelValidate.validate(orderInfo.getChannel());
        //ip验证
        ipValidate.volidate(orderInfo);
        //签名验证
        signValidate(orderInfo);
        //手机号码验证
        mobValidate(orderInfo);
        //并发访问控制
        vistVali(orderInfo);
    }

    /**
     * 拼接签名信息 orderid+channel+timestamp
     *
     * @param
     * @return
     */
    public String getSign(OrderInfo orderInfo) throws Exception {
        StringBuilder strb = new StringBuilder();
        String userid = orderInfo.getUserid();
        strb.append(userid);
        strb.append(orderInfo.getChannel());
        strb.append(orderInfo.getTimestamp());
        return strb.toString();
    }

    /**
     * 签名验证
     *
     * @param
     * @throws Exception
     */
    public void signValidate(OrderInfo orderInfo) throws Exception {
        String lcalsign = getSign(orderInfo);
        String channel = orderInfo.getChannel();
        lcalsign += channelDao.queryChannel(channel).getPassword();
        System.out.println("local-->" + lcalsign);
        lcalsign = MD5.MD5Encode(lcalsign);
        System.out.println("orderinfo==>" + orderInfo.getSignature());
        System.out.println("lcalsign===>" + lcalsign);
        if (!lcalsign.equals(orderInfo.getSignature())) {
            throw new BussinessException("10006", "签名校验失败");
        }
    }

    /**
     * 业务处理
     *
     * @param orderInfo
     */
    public com.alibaba.fastjson.JSONArray busiOper(OrderInfo orderInfo) throws Exception {
        com.alibaba.fastjson.JSONArray jsonArray = new com.alibaba.fastjson.JSONArray();
        List<HashMap> maps = new ArrayList<>();
        try {
            String userid = orderInfo.getUserid();
            List<HashMap> orderInfos = relationQueryDao.getRelation(userid);
            logger.info("orderInfos : " + orderInfos);
            List<HashMap> nextMonthInfos = relationQueryDao.getNextMonthRel(userid);
            logger.info("nextMonthInfos : " + nextMonthInfos);
            if (orderInfos != null && orderInfos.size() > 0) {
                if (nextMonthInfos != null && nextMonthInfos.size() > 0) {
                    for (int i = 0; i < orderInfos.size(); i++) {
                        for (HashMap nextMonthInfo : nextMonthInfos) {
                            String spid = (String) orderInfos.get(i).get("SPID");
                            String nextSpid = (String) nextMonthInfo.get("SPID");
                            if (!StringUtils.isEmpty(spid) && !StringUtils.isEmpty(nextSpid)) {
                                if (spid.equals(nextSpid)) {
                                    orderInfos.remove(orderInfos.get(i));
                                }
                            }
                        }
                    }
                    maps.addAll(nextMonthInfos);
                }
                maps.addAll(orderInfos);
            } else {
                maps = nextMonthInfos;
            }
            logger.info("第一次maps : " + maps);

            if (maps != null && maps.size() > 0) {
                for (HashMap map1 : maps) {
                    String spid = (String) map1.get("SPID");
                    System.out.println("userid ==>" + userid + "  spid===>" + spid);
                    HashMap map2 = relationQueryDao.getRec2(userid, spid);
                    if (map2 != null) {
                        relationQueryDao.upRec(map1);//更新表内数据
                    } else {
                        String id = relationQueryDao.getNo();
                        map1.put("ORDERID", map1.get("ID"));
                        map1.put("ID", id);
                        relationQueryDao.addRec(map1);//添加新数据
                    }
                }
            }
            //最后遍历一次将结果输出
            maps = relationQueryDao.getRec(userid);
            logger.info("第二次maps : " + maps);

            if (maps != null && maps.size() > 0) {
                for (HashMap map1 : maps) {
                    String spid = (String) map1.get("SPID");
                    String status = (String) map1.get("STATUS");
//                    if ("3".equals(status)){
//                        map1.put("producttype","1");
//                    }else {
//                        map1.put("producttype","0");
//                    }
                    if (relationQueryDao.queryCancelConf(spid) > 0 && "3".equals(status)) {
                        Integer num = relationQueryDao.getCancelMonth(spid);
                        String ordertime = (String) map1.get("ORDERTIME");
                        String hyendtime = relationQueryDao.getHyendtime(ordertime, num);
                        map1.put("hyendtime", hyendtime);
                        if (relationQueryDao.isCancel(userid, spid, num + 1) > 0) {
                            map1.put("status", "4");
                        }
                    }
                    com.alibaba.fastjson.JSONObject jsonObj = new JSONObject(map1);//转化为json格式
                    jsonObj = transToLowerObject(jsonObj.toString());
                    jsonArray.add(jsonObj);
                }
            }

            try {
                String touTiaoSpid = dictionaryDao.getValue("touTiaoSpid");
                String[] split = touTiaoSpid.split(",");
                String caporderUrl = dictionaryDao.getValue("caporderUrl");
                HashMap<String,String> map = new HashMap<>();
                map.put("usermob",userid);
                String res = URLUtil.postJson(caporderUrl+"/intensive/currencyQryMini", JSON.toJSONString(map));
                log.info(userid+"集约平台返回报文=======>"+res);

                JSONObject object = JSON.parseObject(res);
                if ("0".equals(object.getString("resultcode"))){
                    JSONArray array = object.getJSONArray("data");
                    if (array!=null&&array.size()>0) {
                        for (int j =0;j<array.size();j++){
                            JSONObject jsonObject = array.getJSONObject(j);
                            String spid = relationQueryDao.getSpid(jsonObject.getString("productid"));
                            for (String str:split){
                                String[] strings = str.split("_");
                                if (strings[0].equals(spid)){
                                    boolean flag = true;
                                    for (int i =0;i<jsonArray.size();i++){
                                        if (jsonArray.getJSONObject(i).getString("spid").equals(strings[0])){
                                            jsonArray.remove(i);
                                            JSONObject putobj = new JSONObject();
                                            putobj.put("id",null);
                                            putobj.put("spid",strings[0]);
                                            putobj.put("cpid",strings[1]);
                                            putobj.put("spname",jsonObject.getString("productname"));
                                            putobj.put("fee",jsonObject.getString("price"));
                                            putobj.put("status",jsonObject.getString("orderstatus"));
                                            putobj.put("ordertime",jsonObject.getString("ordertime"));
                                            putobj.put("canceltime",jsonObject.getString("canceltime"));
                                            putobj.put("endtime",jsonObject.getString("endtime"));
                                            putobj.put("channelkey",jsonObject.getString("channel"));
                                            putobj.put("hyendtime",null);
                                            putobj.put("producttype","0");
                                            jsonArray.add(putobj);
                                            flag = false;
                                            break;
                                        }
                                    }
                                    if (flag){
                                        JSONObject putobj = new JSONObject();
                                        putobj.put("id",null);
                                        putobj.put("spid",strings[0]);
                                        putobj.put("cpid",strings[1]);
                                        putobj.put("spname",jsonObject.getString("productname"));
                                        putobj.put("fee",jsonObject.getString("price"));
                                        putobj.put("status",jsonObject.getString("orderstatus"));
                                        putobj.put("ordertime",jsonObject.getString("ordertime"));
                                        putobj.put("canceltime",jsonObject.getString("canceltime"));
                                        putobj.put("endtime",jsonObject.getString("endtime"));
                                        putobj.put("channelkey",jsonObject.getString("channel"));
                                        putobj.put("hyendtime",null);
                                        putobj.put("producttype","0");
                                        jsonArray.add(putobj);
                                    }
                                }
                            }
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            log.info(userid+"jsonarray===>" + jsonArray);
            return jsonArray;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("处理异常" + e.getMessage() + e);
            log.error("处理异常" + e.getMessage() + e);
            throw e;
        }
    }

    /**
     * json大写转小写
     *
     * @return JSONObject
     */
    public static JSONObject transToLowerObject(String json) {
        JSONObject JSONObject2 = new JSONObject();
        JSONObject JSONObject1 = JSON.parseObject(json);
        for (String key : JSONObject1.keySet()) {
            Object object = JSONObject1.get(key);
            if (object.getClass().toString().endsWith("JSONObject")) {
                JSONObject2.put(key.toLowerCase(), transToLowerObject(object.toString()));
            } else if (object.getClass().toString().endsWith("JSONArray")) {
                JSONObject2.put(key.toLowerCase(), transToArray(JSONObject1.getJSONArray(key).toString()));
            } else {
                JSONObject2.put(key.toLowerCase(), object);
            }
        }
        return JSONObject2;
    }

    /**
     * jsonArray转jsonArray
     *
     * @return JSONArray
     */
    public static JSONArray transToArray(String jsonArray) {
        JSONArray jSONArray2 = new JSONArray();
        com.alibaba.fastjson.JSONArray jSONArray1 = JSON.parseArray(jsonArray);
        for (int i = 0; i < jSONArray1.size(); i++) {
            Object jArray = jSONArray1.getJSONObject(i);
            if (jArray.getClass().toString().endsWith("JSONObject")) {
                jSONArray2.add(transToLowerObject(jArray.toString()));
            } else if (jArray.getClass().toString().endsWith("JSONArray")) {
                jSONArray2.add(transToArray(jArray.toString()));
            }
        }
        return jSONArray2;
    }

    /**
     * 验证访问限制，1分钟内同一业务只能办理一次
     *
     * @param orderInfo
     * @throws Exception
     */
    private void vistVali(OrderInfo orderInfo) throws Exception {
        String[] params = new String[3];
        params[0] = orderInfo.getChannel();
        params[1] = orderInfo.getUserid();
        if (commonService.vistVali2(params, "relationQuery")) {
            throw new BussinessException("8001", "指定时间内重复请求");
        }
    }

    /**
     * 手机号码验证
     *
     * @param
     * @throws Exception
     */
    private void mobValidate(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 static void main(String[] args) {
        String aa = "{\"resultcode\":\"0\",\"errorinfo\":\"成功\",\"time\":\"39\",\"data\":\"[{\\\"canceltime\\\":\\\"2023-03-15 21:34:42\\\",\\\"channel\\\":\\\"50342\\\",\\\"endtime\\\":\\\"2023-03-31 23:59:59\\\",\\\"festivalid\\\":\\\"\\\",\\\"orderstatus\\\":\\\"1\\\",\\\"ordertime\\\":\\\"2023-03-06 16:19:51\\\",\\\"price\\\":\\\"9\\\",\\\"productid\\\":\\\"20221226777\\\",\\\"productname\\\":\\\"抖音定向流量5G加油包5GB\\\",\\\"starttime\\\":\\\"2023-03-06 16:19:51\\\",\\\"usertype\\\":\\\"4\\\"}]\"}";
        String bb = "1360_douyin,1358_douyin,1359_jrtt,1361_douyin,1362_douyin";
        JSONArray jsonArray = new JSONArray();
        HashMap<String,String> map = new HashMap<>();
        map.put("20221226777","1360");
        String[] split = bb.split(",");
        JSONObject object = JSON.parseObject(aa);
        if ("0".equals(object.getString("resultcode"))){
            JSONArray array = object.getJSONArray("data");
            System.out.println(array);
            if (array!=null&&array.size()>0) {
                for (int j =0;j<array.size();j++){
                    JSONObject jsonObject = array.getJSONObject(j);
                    String spid = map.get(jsonObject.getString("productid"));
                    for (String str:split){
                        String[] strings = str.split("_");
                        if (strings[0].equals(spid)){
                            boolean flag = true;
                            for (int i =0;i<jsonArray.size();i++){
                                if (jsonArray.getJSONObject(i).getString("spid").equals(strings[0])){
                                    jsonArray.remove(i);
                                    JSONObject putobj = new JSONObject();
                                    putobj.put("id","");
                                    putobj.put("spid",strings[0]);
                                    putobj.put("spname",jsonObject.getString("productname"));
                                    putobj.put("fee",jsonObject.getString("price"));
                                    putobj.put("status",jsonObject.getString("orderstatus"));
                                    putobj.put("ordertime",jsonObject.getString("ordertime"));
                                    putobj.put("canceltime",jsonObject.getString("canceltime")==null?"":jsonObject.getString("canceltime"));
                                    putobj.put("endtime",jsonObject.getString("endtime")==null?"":jsonObject.getString("endtime"));
                                    putobj.put("channelkey",jsonObject.getString("channel"));
                                    putobj.put("hyendtime","");
                                    putobj.put("producttype","0");
                                    jsonArray.add(putobj);
                                    flag = false;
                                    break;
                                }
                            }
                            if (flag){
                                JSONObject putobj = new JSONObject();
                                putobj.put("id","");
                                putobj.put("spid",strings[0]);
                                putobj.put("spname",jsonObject.getString("productname"));
                                putobj.put("fee",jsonObject.getString("price"));
                                putobj.put("status",jsonObject.getString("orderstatus"));
                                putobj.put("ordertime",jsonObject.getString("ordertime"));
                                putobj.put("canceltime",jsonObject.getString("canceltime")==null?"":jsonObject.getString("canceltime"));
                                putobj.put("endtime",jsonObject.getString("endtime")==null?"":jsonObject.getString("endtime"));
                                putobj.put("channelkey",jsonObject.getString("channel"));
                                putobj.put("hyendtime","");
                                putobj.put("producttype","0");
                                jsonArray.add(putobj);
                            }
                        }
                    }
                }
            }
        }


        System.out.println(jsonArray);
    }
}
