package com.chinacreator.video.restful.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.CommConfDao;
import com.chinacreator.video.mapper.DictionaryDao;
import com.chinacreator.video.restful.bean.HsQueryVipBean;
import com.chinacreator.video.restful.dao.HsQueryVipDao;
import com.chinacreator.video.service.CommonService;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.util.URLUtil;
import com.chinacreator.video.validate.*;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

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

/**
 * 音乐侧服务类
 *
 * @author zhengrong.yan
 * @date 20200904
 */
@Component
public class HsQueryVipService {

    @Autowired
    private ChannelValidate channelValidate;

    @Autowired
    private IpValidate ipValidate;

    @Autowired
    private MobValidate mobValidate;

    @Autowired
    private TimetampValidate timetampValidate;

    @Autowired
    private SignValidate signValidate;

    @Autowired
    private ParamValidate paramValidate;

    @Autowired
    private DictionaryDao dictionaryDao;

    @Autowired
    private CommonService commonService;

    @Autowired
    private HsQueryVipDao hsQueryVipDao;

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

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

    public void busiCheck(OrderInfo orderInfo) throws Exception {

        //timetamp验证
        timetampValidate.validate(orderInfo.getTimestamp());
        //渠道验证
        channelValidate.validate(orderInfo.getChannel());
        //ip验证
        orderInfo.setInvokeface("hsqueryvip");
        ipValidate.volidate(orderInfo, "1");
        //签名验证
        signValidate.validate(orderInfo, orderInfo.getUserid() + orderInfo.getChannel() + orderInfo.getTimestamp());
        //手机号码验证
        mobValidate.validateByChannel(orderInfo);
        //并发访问控制
//		vistVali(orderInfo);
    }

    /**
     * 业务处理
     *
     * @param orderInfo
     */
    public JSONArray busiOper(OrderInfo orderInfo) throws Exception {
        String errorcode = "0";
        String errorinfo = "";
        try {
            //调用vip接口，获取数据
            if (orderInfo.getUserid() == null || "".equals(orderInfo.getUserid())) {
                throw new BussinessException("10007", "手机号不能为空");
            }
            String result = invoke(orderInfo.getUserid());
            //String result = "{\"data\":[{\"vipTime\":\"2022-05-26 14:59:12\",\"resultCode\":\"0\",\"typeName\":\"权益百宝箱-华盛调用上海权益\",\"errorInfo\":\"成功\",\"remark\":\"\",\"activityType\":\"105\",\"userid\":\"21019\",\"userval\":\"18673167944\",\"status\":\"会员领取\"},{\"vipTime\":\"2022-05-25 21:21:13\",\"resultCode\":\"0\",\"typeName\":\"权益百宝箱-华盛调用上海权益\",\"errorInfo\":\"成功\",\"remark\":\"\",\"activityType\":\"11\",\"userid\":\"21019\",\"userval\":\"18673167944\",\"status\":\"会员领取\"},{\"vipTime\":\"2022-05-25 20:48:15\",\"resultCode\":\"0\",\"typeName\":\"权益百宝箱-华盛调用上海权益\",\"errorInfo\":\"成功\",\"remark\":\"\",\"activityType\":\"test\",\"userid\":\"21019\",\"userval\":\"18673167944\",\"status\":\"会员领取\"},{\"vipTime\":\"2021-07-30 10:50:12\",\"resultCode\":\"1\",\"typeName\":\"芒果16元合约产品会员领取\",\"errorInfo\":\"0\",\"remark\":\"\",\"activityType\":\"54\",\"userid\":\"18673167944\",\"userval\":\"18673167944\",\"status\":\"会员领取\"}],\"errorinfo\":\"\",\"resultcode\":\"0\"}";
            if (result != null && !"".equals(result)) {
                JSONObject jsonObject = JSON.parseObject(result);
                if ("0".equals(jsonObject.getString("resultcode"))) {
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    log.info("jsonarray>>>>>" + jsonArray.toJSONString());
                    //获取
                    //获取续送的log
                    List<HsQueryVipBean> continueVip = hsQueryVipDao.getContinueVip(orderInfo.getUserid());
                    JSONArray dataArray = JSONArray.parseArray(JSON.toJSONString(continueVip));
                    log.info("续送data>>>" + dataArray);
                    jsonArray.addAll(dataArray);
                    log.info("合并>>" + jsonArray.toJSONString());
                    jsonArray = importSpiddata(jsonArray, orderInfo.getUserid());
                    log.info("添加spid和spname后的jsonarray>>>>>" + jsonArray.toJSONString());
                    //排序
                    JSONArray resultjson = jsonArraySort(jsonArray, "vipTime", false);
                    log.info("排序后>>>>>" + resultjson.toJSONString());
                    return resultjson;
                } else {
                    throw new BussinessException(jsonObject.getString("resultcode"), jsonObject.getString("errorinfo"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof BussinessException) {
                errorcode = ((BussinessException) e).getCode();
                errorinfo = ((BussinessException) e).getMessage();
            } else {
                errorcode = "8000";
                errorinfo = "出现异常，" + e.getMessage();
            }
            throw e;
        } finally {
            //记录调用日志

        }
        return null;
    }

    /**
     * 验证访问限制，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();
        params[2] = orderInfo.getSpid();
        if (commonService.vistVali2(params, "muorder")) {
            throw new BussinessException("8001", "指定时间内重复请求");
        }
    }

    public String invoke(String userid) {
        String baseurl = "http://testapi.mige.tv/videovip/hsqueryVip";
        baseurl = dictionaryDao.getValue("hsVipQueryUrl");
        // 正式环境
        //baseurl = "http://csapi.mige.tv:809/videovip/giveVip" ;
        Map<String, String> param = new HashMap<>();
        String userval = userid;
        String orderid = "";
        String channel = "hsqueryvip";
        String vipid = "22608";
        String pwd = "w8idwvat";  // csdywywy
        String timeStamp = System.currentTimeMillis() / 1000L + "";
//		String str = orderid + channel + vipid + userval + pwd + timeStamp;
        String signature = MD5.MD5Encode(orderid + channel + vipid + userval + pwd + timeStamp);

        param.put("orderid", orderid);
        param.put("vipid", vipid);
        param.put("channel", channel);
        param.put("userval", userval);
        param.put("signature", signature);
        param.put("timestamp", timeStamp);

        String url = URLUtil.mapToUrl(baseurl, param);
        log.info("url>>>>" + url);
        String resp = null;

        try {
            resp = URLUtil.get(url, 3000);
            log.info("resp>>>>>" + resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resp;
    }

    //将spid，spname数据补充
    public JSONArray importSpiddata(JSONArray jsonArray, String userid) {
        List<HashMap> activitymap = hsQueryVipDao.findActivityConfig();
        List<HashMap> backbusimap = hsQueryVipDao.findBakBusiConfig();
        //重新定义一个遍历的变量
        JSONArray result_json = new JSONArray();
        Boolean flag = false;
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String invoke_activetype = jsonObject.getString("activityType");
            String invoke_vipid = jsonObject.getString("userid");
            log.info("invoke_activetype==>" + invoke_activetype + "  invoke_vipid==>" + invoke_vipid);
            log.info("activemapsize==>" + activitymap.size());
            int acitivetypenum = 0;
//			try {
//				acitivetypenum = Integer.parseInt(invoke_activetype);
//			}catch (Exception e){
//				e.printStackTrace();
//				logger.info(invoke_activetype+">>>>强转数字失败");
//			}
//			if(acitivetypenum!=0){
//
//			}
            boolean isContinueStatus = false;//是否是续送标识
            if ("续送".equals(jsonObject.getString("status"))) {
                isContinueStatus = true;
            }

            if (!isContinueStatus) {
                for (HashMap map : activitymap) {
                    String activetype = map.get("ACTIVETYPE") + "";
                    if (activetype.equals(invoke_activetype)) {
                        log.info("---一致，退出循环");
                        //存入spid
                        jsonObject.put("spid", map.get("SPID"));
                        jsonObject.put("spname", map.get("SPNAME"));
                        jsonObject.put("usertypeName", "产品订购");
                        //result_json.add(jsonObject);
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    log.info("backbusimap==>" + backbusimap.size());
                    for (HashMap map : backbusimap) {
                        String vipid = map.get("vipid") + "";
                        if (vipid.equals(invoke_vipid)) {
                            log.info("---vipid一致，退出循环");
                            //存入spid
                            jsonObject.put("spid", map.get("SPID"));
                            jsonObject.put("spname", map.get("SPNAME"));
                            jsonObject.put("usertypeName", "产品订购");
                            //result_json.add(jsonObject);
                            flag = true;
                            break;
                        }
                    }
                }
            }
            //跳出循环or循环结束时发现没有匹配上的spid
            if (jsonObject.get("spid") == null || "".equals(jsonObject.get("spid"))) {
                jsonObject.put("spid", "");
                jsonObject.put("spname", "");
                jsonObject.put("usertypeName", "会员直充");
                jsonObject.put("receiverule", "");//领取规则
                //result_json.add(jsonObject);
            } else {
                //根据spid 查到领取规则
                String spid  = null;
                if (!StringUtils.isEmpty(jsonObject.getString("fhspid"))){
                    spid = jsonObject.getString("fhspid");
                }else {
                    spid = jsonObject.getString("spid");
                }
                List<HashMap> channelData = hsQueryVipDao.findUserChannelData(userid, spid);
                //取第一条
                String channel = "";
                String subchannel = "";
                String ordertime = null;
                if (channelData != null && channelData.size() > 0) {
                    channel = channelData.get(0).get("ORDERCHANNEL") == null ? "" : channelData.get(0).get("ORDERCHANNEL").toString();
                    subchannel = channelData.get(0).get("ORDERCHANNEL2") == null ? "" : channelData.get(0).get("ORDERCHANNEL2").toString();
                    ordertime = channelData.get(0).get("ORDERTIME") == null ? "" : channelData.get(0).get("ORDERTIME").toString();
                }
                String time = "20221101000000";
                long time_long = Long.parseLong(time);
                long ordertime_long = 0;
                if (ordertime != null) {
                    ordertime_long = Long.parseLong(ordertime);

				/*final SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
				long ordertime_long = 0;
				long time_long = 0;
				try {
					 ordertime_long = format.parse(ordertime).getTime();
					 time_long = format.parse(time).getTime();
				} catch (ParseException e) {
					e.printStackTrace();
				}*/

                    /**
                     * 原逻辑
                     订购当月务必手动领取会员，次月续订时会员自动续送。 --既不在 tb_order_sendvip_conf （查渠道） 也不在 tb_vip_joinspid_conf （查渠道）
                     订购期间，会员权益每月将自动入充值到您当前手机号。--在tb_order_sendvip_conf  （查渠道），不在tb_vip_joinspid_conf （查渠道）
                     订购期间务必每月手动领取当月会员逾期不补。--在tb_vip_joinspid_conf   （查渠道）,不在tb_order_sendvip_conf  （查渠道）
                     **/
//                    List<HashMap> sendvipMap = hsQueryVipDao.getSendvip_conf(channel, subchannel, spid);
					List<HashMap> sendvipMap = hsQueryVipDao.getSendvip_conf_new(channel,subchannel,spid);
                    List<HashMap> joinvipMap = hsQueryVipDao.getJoinspid_conf(channel, subchannel, spid, ordertime);
                    List<HashMap> joinvipMap_new = hsQueryVipDao.getJoinspid_conf_new(channel, subchannel, spid, ordertime);
                    // 2022年11月1号之前订购的用户保持原来的逻辑
                    if (ordertime_long < time_long) {
                        log.info("11.1之前订购的老用户原来的逻辑" + userid + "===>" + spid);
                        if ((sendvipMap != null && sendvipMap.size() > 0) && (joinvipMap == null || joinvipMap.size() == 0)) {
                            jsonObject.put("receiverule", "订购期间，会员权益每月将自动入充值到您当前手机号。");//领取规则
                        } else if ((joinvipMap != null && joinvipMap.size() > 0) && (sendvipMap == null || sendvipMap.size() == 0)) {
                            jsonObject.put("receiverule", "订购期间务必每月手动领取当月会员逾期不补.");//领取规则
                        } else if ((sendvipMap == null || sendvipMap.size() == 0) && (joinvipMap == null || joinvipMap.size() == 0)) {
                            jsonObject.put("receiverule", "订购当月务必手动领取会员，次月续订时会员自动续送。");//领取规则
                        } else {
                            jsonObject.put("receiverule", "");//领取规则
                        }
                    } else {
					/*
					原来次月续送的用户改为每月需手动领取
					除部分特殊渠道的产品还是原来首月手动领取次月续送
					*/
                        log.info("11.1之后订购的新用户新逻辑" + userid + "===>" + spid);
                        if ((sendvipMap != null && sendvipMap.size() > 0) && (joinvipMap_new == null || joinvipMap_new.size() == 0)) {
                            jsonObject.put("receiverule", "订购期间，会员权益每月将自动入充值到您当前手机号。");//领取规则
                        } else if ((joinvipMap_new != null && joinvipMap_new.size() > 0)) {

                         /*   if ((sendvipMap == null || sendvipMap.size() == 0)) {
                                jsonObject.put("receiverule", "订购期间务必每月手动领取当月会员逾期不补.");//领取规则
                            } else {
                                String specialchannels = dictionaryDao.getValue("specialchannels");
                                if (!StringUtils.isEmpty(subchannel) && specialchannels.contains(subchannel)) {
                                    jsonObject.put("receiverule", "订购期间，会员权益每月将自动入充值到您当前手机号。");//领取规则
                                }else {
                                    jsonObject.put("receiverule", "订购期间务必每月手动领取当月会员逾期不补.");//领取规则
                                }
                            }*/

                            String specialchannels = dictionaryDao.getValue("specialchannels_" + spid);
                            log.info("specialchannels " + specialchannels);
                            if ((sendvipMap == null || sendvipMap.size() == 0)) {
                                if (!StringUtils.isEmpty(specialchannels)){
                                    if (!StringUtils.isEmpty(subchannel) && specialchannels.contains(subchannel)) {
                                        jsonObject.put("receiverule", "订购当月务必手动领取会员，次月续订时会员自动续送。");//领取规则
                                    }else {
                                        jsonObject.put("receiverule", "订购期间务必每月手动领取当月会员逾期不补。");//领取规则
                                    }
                                }else {
                                    jsonObject.put("receiverule",  "订购期间务必每月手动领取当月会员逾期不补。");//领取规则
                                }
                            } else {
                                if (!StringUtils.isEmpty(specialchannels)){
                                    if (!StringUtils.isEmpty(subchannel) && specialchannels.contains(subchannel)) {
                                        jsonObject.put("receiverule", "订购期间，会员权益每月将自动充值到您当前手机号。");//领取规则
                                    }else {
                                        jsonObject.put("receiverule", "订购期间务必每月手动领取当月会员逾期不补。");//领取规则
                                    }
                                }else {
                                    jsonObject.put("receiverule",  "订购期间务必每月手动领取当月会员逾期不补。");//领取规则
                                }
                            }

                        } else if ((sendvipMap == null || sendvipMap.size() == 0) && (joinvipMap_new == null || joinvipMap_new.size() == 0)) {
                            jsonObject.put("receiverule", "订购当月务必手动领取会员，次月续订时会员自动续送。");//领取规则
                        } else {
                            jsonObject.put("receiverule", "");//领取规则
                        }
                    }
                } else {
                    log.info("该数据无订购关系" + channelData + "========>" + "spid:" + spid + "=====>" + "userid:" + userid);
                }
            }

            result_json.add(jsonObject);
        }
        return result_json;
    }

    /**
     * array 传入待排序的 JSONArray
     * sortColName 排序字段
     * isAsc 升序还是降序，true表示升序
     * sortColName,isAsc 需要加 final,否则现有环境 jenkins 打版本会失败
     */
    public static JSONArray jsonArraySort(JSONArray array, final String sortColName,
                                          final boolean isAsc) {
        JSONArray sortedJsonArray = new JSONArray();
        List<JSONObject> jsonList = new ArrayList<JSONObject>();
        for (int i = 0; i < array.size(); i++) {
            jsonList.add(array.getJSONObject(i));
        }

        //将 JSONArray 转换成 List,本质上还是对 List 进行排序
        Collections.sort(jsonList, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                int result = 0;
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String valA = o1.getString(sortColName);
                String valB = o2.getString(sortColName);
                try {
                    Date map1_time = format.parse(valA);
                    Date map2_time = format.parse(valB);
                    if (map1_time.after(map2_time)) {
                        return -1;
                    } else if (map1_time.before(map2_time)) {
                        return 1;
                    } else if (map1_time.equals(map2_time)) {
                        return 0;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
        // 此时jsonList已经是排完序的集合了
        for (JSONObject obj : jsonList) {
            sortedJsonArray.add(obj);
        }
        return sortedJsonArray;
    }
}
