package com.jsowell.pile.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.jsowell.common.enums.sim.SimCardStatusCorrespondEnum;
import com.jsowell.common.enums.sim.SimSupplierEnum;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.http.HttpUtils;
import com.jsowell.common.util.id.IdUtils;
import com.jsowell.common.util.sim.SimCardUtils;
import com.jsowell.common.util.sim.XunZhongSimUtils;
import com.jsowell.pile.vo.web.*;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.stream.Collectors;


/**
 * Sim卡Service
 *
 * @author JS-ZZA
 * @date 2022/12/3 15:35
 */
@Service
public class SimCardService {

    @Autowired
    private IPileSimInfoService pileSimInfoService;

    protected final Logger logger = LoggerFactory.getLogger(SimCardService.class);

    @Value("${xunzhong.apiId}")
    private String API_ID;

    @Value("${xunzhong.sim.getSimCardDetailURL}")
    private String getSimCardDetailURL;

    @Value("${xunzhong.trafficPool.poolListURL}")
    private String poolListURL;

    @Value("${xunzhong.sim.renewURL}")
    private String renewURL;

    @Value("${wulian.appId}")
    private String appId;

    @Value("${wulian.appSecret}")
    private String appSecret;

    @Value("${wulian.getWay}")
    private String wuLianGetWay;

    @Value("${wulian.name.getSimInfo}")
    private String getSimInfoName;

    @Value("${wulian.name.WuLianSimRenew}")
    private String WuLianSimRenew;

    /**
     * 不知道iccid属于哪家供应商，就用这个方法查
     * @param iccid
     * @return
     */
    public SimCardVO searchByLoop(String iccid) {
        SimCardVO vo = null;
        // 查XunZhong
        List<SimCardVO> simCardVOS = XunZhongGetSimInfoByIccIds(Lists.newArrayList(iccid));
        if (CollectionUtils.isNotEmpty(simCardVOS)) {
            vo = simCardVOS.get(0);
        }
        // 查WuLian平台
        List<SimCardVO> wuLianSimData = WuLianGetSimInfoByIccIds(Lists.newArrayList(iccid));
        if (CollectionUtils.isNotEmpty(wuLianSimData)) {
            vo = wuLianSimData.get(0);
        }
        // 第三个供应商

        logger.info("查询iccid:{}, 详情信息:{}", iccid, JSON.toJSONString(vo));
        return vo;
    }

    /**
     * 批量续费（后管调用此方法）
     * @param iccIds 卡号
     * @param cycleNumber 续费周期
     */
    public List<SimRenewResultVO> renewSimByLoop(List<String> iccIds, int cycleNumber) {
        if (CollectionUtils.isEmpty(iccIds)) {
            return Lists.newArrayList();
        }
        // 将集合中为空和0的过滤
        iccIds = iccIds.stream()
                .filter(StringUtils::isNotEmpty)
                .filter(x -> !StringUtils.equals(x, "0"))
                .collect(Collectors.toList());

        ArrayList<SimRenewResultVO> list = new ArrayList<>();
        for (String iccId : iccIds) {
            // 查出此卡属于哪家公司(拿到code)
            SimCardVO simCardVO = searchByLoop(iccId);
            String simSupplierCode = simCardVO.getSimCardFactory();

            // 根据不同的公司执行不同的续费方法
            SimRenewResultVO simRenewResultVO = renewSimBySupplier(simSupplierCode, iccId, cycleNumber);
            list.add(simRenewResultVO);
        }
        return list;
    }


    /**
     * 根据不同的公司执行不同的续费方法
     * @param code SimSupplierEnum.getCode()
     * @param iccId 卡号
     * @param cycleNumber 续费周期
     */
    private SimRenewResultVO renewSimBySupplier(String code, String iccId, int cycleNumber) {
        SimRenewResultVO vo = new SimRenewResultVO();
        vo.setIccId(iccId);
        vo.setCycleNumber(cycleNumber);

        if (StringUtils.equals(code, SimSupplierEnum.XUN_ZHONG.getCode())) {
            // 讯众
            try {
                vo.setSimSuppler(SimSupplierEnum.XUN_ZHONG.getName());
                XunZhongSimRenewal(Lists.newArrayList(iccId), cycleNumber);
                vo.setResult(true);
            }catch (BusinessException e) {
                vo.setResult(false);
                vo.setReason(e.getMessage());
            }
        }
        // 物联平台
        if (StringUtils.equals(code, SimSupplierEnum.WU_LIAN_INTERNET.getCode())) {
            try {
                vo.setSimSuppler(SimSupplierEnum.WU_LIAN_INTERNET.getName());
                WuLianSimRenew(Lists.newArrayList(iccId), cycleNumber);
                vo.setResult(true);
            }catch (BusinessException e){
                vo.setResult(false);
                vo.setReason(e.getMessage());
            }
        }
        return vo;
    }



    /**
     * 讯众 内部接口
     * 通过iccIds查询讯众Sim卡信息
     * @param iccIds
     */
    public List<SimCardVO> XunZhongGetSimInfoByIccIds(List<String> iccIds) {
        List<SimCardVO> resultList = new ArrayList<>();

        List<XunZhongSimData> dataList = getSimCardDetail(iccIds);
        SimCardVO simCard = null;
        for (XunZhongSimData zhongSimData : dataList) {
            // sim卡套餐
            XunZhongSimData.Products products = null;
            if (CollectionUtils.isNotEmpty(zhongSimData.getCurrent_products())) {
                products = zhongSimData.getCurrent_products().get(0);
            } else {
                if (CollectionUtils.isNotEmpty(zhongSimData.getFuture_products())) {
                    products = zhongSimData.getFuture_products().get(0);
                }
            }
            if (products == null) {
                logger.info("iccid:{}, 没有套餐", zhongSimData.getIccid());
                continue;
            }
            // set
            simCard = new SimCardVO();
            simCard.setIccId(zhongSimData.getIccid()); // 卡号
            simCard.setSimCardFactory(SimSupplierEnum.XUN_ZHONG.getCode()); // 1-讯众物联
            simCard.setSimCardOperator(zhongSimData.getCarrier_type()); // 运营商类型
            simCard.setSimCardStatus(zhongSimData.getNet_status()); // 联网状态
            simCard.setName(products.getName()); // 套餐名称
            simCard.setExpiredTime(products.getExpiration_time()); // 过期时间

            BigDecimal packageCapacity = products.getPackage_capacity(); // 套餐总量（mb）
            simCard.setPackageCapacity(packageCapacity);

            if (products.getCurrent_cycle_usage() != null) {
                BigDecimal current_cycle_usage = products.getCurrent_cycle_usage(); // 当前已用（kb）
                String currentCycleUsage = SimCardUtils.kb2MbOrGb(current_cycle_usage.intValue());
                BigDecimal currentCycleUsageData = new BigDecimal(currentCycleUsage);
                simCard.setUsedFlowRate(currentCycleUsageData);
                BigDecimal residualData = packageCapacity.subtract(currentCycleUsageData); // 套餐剩余
                simCard.setResidualFlowRate(residualData.setScale(2, BigDecimal.ROUND_HALF_UP));
            }

            resultList.add(simCard);
        }
        return resultList;
    }

    public static void main(String[] args) {
        // List<String> iccIds = Lists.newArrayList();
        // iccIds.add("123");
        // iccIds.add(null);
        // iccIds.add("0");
        // iccIds.add("asdf");
        // iccIds.add(null);
        // iccIds.add("0");
        // iccIds.add(null);
        // iccIds.add("0");
        // iccIds.add("9461351351");
        // iccIds = iccIds.stream()
        //         .filter(StringUtils::isNotEmpty)
        //         .filter(x -> !StringUtils.equals(x, "0"))
        //         .collect(Collectors.toList());
        // String iccId = StringUtils.join(iccIds, ",");
        // System.out.println(iccId);


        String packName = "移动 500M/月";
        System.out.println(StringUtils.contains(packName, "移动"));
        // StringUtils.containsAny()
    }


    /**
     * 讯众官方接口
     * 获取sim卡详细信息
     * @param iccIds Sim卡集合
     * @return
     */
    public List<XunZhongSimData> getSimCardDetail(List<String> iccIds) {
        String iccId = list2Str(iccIds);

        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

        Hashtable<String, Object> params = new Hashtable<>();
        params.put("api_id", API_ID);
        params.put("timestamp", timestamp);
        params.put("iccids", iccId);

        String signStr = XunZhongSimUtils.getSignStr(params);

        params.put("sign", signStr);

        String postResult = XunZhongSimUtils.sendPost(getSimCardDetailURL, params);
        logger.info("【====讯众物联====】查询Sim卡信息, param:{}, result:{}", params, postResult);
        JSONObject jsonObject = JSONObject.parseObject(postResult);
        if (StringUtils.equals(jsonObject.getString("code"), "0")) {
            String result = jsonObject.getString("result");
            return JSON.parseArray(result, XunZhongSimData.class);
        }
        return Lists.newArrayList();
    }

    /**
     * 讯众官方接口
     * 获取流量池信息
     * @return
     */
    public String getTrafficPoolInfo() {
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

        Hashtable<String, Object> params = new Hashtable<>();
        params.put("api_id", API_ID);
        params.put("timestamp", timestamp);

        String signStr = XunZhongSimUtils.getSignStr(params);
        params.put("sign", signStr);

        String postResult = XunZhongSimUtils.sendPost(poolListURL, params);
        logger.info("【====讯众物联====】获取流量池信息, result:{}", postResult);
        return postResult;
    }


    /**
     * 讯众官方接口
     * sim卡续期
     * @param iccIds 需要续期的sim卡
     * @param cycleNumber 续费周期（0-999），0表示无限周期
     * @return
     */
    public void XunZhongSimRenewal(List<String> iccIds, int cycleNumber) {
        if (CollectionUtils.isEmpty(iccIds)) {
            throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
        }
        String iccId = list2Str(iccIds);

        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

        Hashtable<String, Object> params = new Hashtable<>();
        params.put("api_id", API_ID);
        params.put("timestamp", timestamp);
        params.put("iccids", iccId);
        params.put("cycle_number", cycleNumber);

        String signStr = XunZhongSimUtils.getSignStr(params);

        params.put("sign", signStr);

        String postResult = XunZhongSimUtils.sendPost(renewURL, params);
        logger.info("【====讯众物联====】sim卡续费业务, result:{}", postResult);
        JSONObject jsonResult = JSONObject.parseObject(postResult);
        String code = jsonResult.getString("code");
        if (!StringUtils.equals("0", code)) {
            String message = jsonResult.getString("message");
            throw new BusinessException(code, message);
        }
    }


    /**
     * 物联平台官方接口
     *
     * 查询卡信息
     *
     * @param iccIds 卡号集合
     * @return 卡信息集合
     */
    public List<WuLianSimData> WuLianGetSimInfo(List<String> iccIds) {
        ArrayList<WuLianSimData> list = new ArrayList<>();

        if (CollectionUtils.isEmpty(iccIds)) {
            return list;
        }
        for (String iccId : iccIds) {
            JSONObject param = new JSONObject();
            param.put("appid", appId);
            param.put("appsecret", appSecret);
            param.put("name", getSimInfoName);
            param.put("iccid", iccId);

            String result = HttpUtils.sendPostContentType(wuLianGetWay, param.toJSONString(), "application/json");
            logger.info("【====物联网智能云平台====】查询Sim卡信息, result: {}", result);

            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONArray dataArray = (JSONArray) jsonObject.get("data");

            if (CollectionUtils.isNotEmpty(dataArray)) {
                JSONObject data = dataArray.getJSONObject(0);
                WuLianSimData wuLianSimData = JSONObject.parseObject(data.toJSONString(), WuLianSimData.class);

                list.add(wuLianSimData);
            }
        }
        return list;
    }


    /**
     * 物联平台 内部接口
     * 通过iccIds查询物联平台Sim卡信息
     *
     * @param iccIds
     * @return
     */
    public List<SimCardVO> WuLianGetSimInfoByIccIds(List<String> iccIds) {
        List<SimCardVO> resultList = new ArrayList<>();

        List<WuLianSimData> list = WuLianGetSimInfo(iccIds);
        SimCardVO vo = null;

        for (WuLianSimData wuLianSimData : list) {
            String WuLianCardStatus = wuLianSimData.getCardStatus();

            // 卡状态不一致，需做对应
            String dataBaseCardStatus = SimCardStatusCorrespondEnum.getDataBaseCardStatus(WuLianCardStatus);

            BigDecimal packageCanUsage = new BigDecimal(wuLianSimData.getPackageCanUsage()); // 可用流量(MB)
            BigDecimal packageHasUsage = new BigDecimal(wuLianSimData.getPackageHasUsage()); // 已用流量(MB)
            BigDecimal residualFlowRate = packageCanUsage.subtract(packageHasUsage); // 剩余

            // 运营商
            String packageName = wuLianSimData.getPackageName();
            String operator = "";
            if (StringUtils.contains(packageName, "移动")) {
                operator = "china_mobile";
            }else if (StringUtils.contains(packageName, "电信")) {
                operator = "china_telecom";
            } else if (StringUtils.contains(packageName, "联通")) {
                operator = "china_unicom";
            }

            //将信息封装到SimCardVO
            vo = new SimCardVO();
            vo.setIccId(wuLianSimData.getIccId());
            vo.setSimCardFactory(SimSupplierEnum.WU_LIAN_INTERNET.getCode()); // 2-物联网智能云平台
            vo.setSimCardOperator(operator); // 运营商
            vo.setSimCardStatus(dataBaseCardStatus); // 卡状态
            vo.setName(packageName); // 套餐名称
            vo.setExpiredTime(wuLianSimData.getCardEndTime()); // 卡到期时间
            vo.setPackageCapacity(packageCanUsage); // 套餐容量
            vo.setUsedFlowRate(packageHasUsage); // 已用流量
            vo.setResidualFlowRate(residualFlowRate); // 剩余流量


            resultList.add(vo);

        }
        return resultList;

    }


    /**
     * 物联平台续费接口
     *
     * @param iccIds
     * @param cycleNumber
     * @return
     */
    public void WuLianSimRenew(List<String> iccIds, int cycleNumber) {
        List<WuLianSimRenewVO> resultList = new ArrayList<>();
        if (CollectionUtils.isEmpty(iccIds)) {
            return;
        }
        // 先查出卡的信息
        List<WuLianSimData> wuLianSimData = WuLianGetSimInfo(iccIds);
        for (WuLianSimData data : wuLianSimData) {
            JSONObject param = new JSONObject();
            param.put("appid", appId);
            param.put("appsecret", appSecret);
            param.put("name", WuLianSimRenew);
            param.put("msisdn", data.getMsisdn());
            param.put("packageId", data.getPackageId()); // 套餐id
            param.put("outOrderNo", IdUtils.generateTransactionCode(data.getMsisdn())); // 外部业务订单号
            param.put("period", cycleNumber); // 续费周期

            String result = HttpUtils.sendPostContentType(wuLianGetWay, param.toJSONString(), "application/json");
            logger.info("【====物联网智能云平台====】Sim卡续费, result: {}", result);
            JSONObject resultJson = JSONObject.parseObject(result);
            String resultCode = resultJson.getString("code");
            WuLianSimRenewVO vo = null;
            if (!StringUtils.equals("0", resultCode)) {
                throw new BusinessException(resultCode, resultJson.getString("msg"));
            }
        }
    }

    /**
     * 将list数组转化为逗号分隔的字符串
     *
     * @param iccIds
     * @return
     */
    private String list2Str(List<String> iccIds) {
        iccIds = iccIds.stream()
                .filter(StringUtils::isNotEmpty)
                .filter(x -> !StringUtils.equals(x, "0"))
                .collect(Collectors.toList());
        // 数组转成逗号分割的字符串
        String iccId = StringUtils.join(iccIds, ",");
        return iccId;
    }
}
