package com.ho.filecenter.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.service.RedisService;
import com.ho.filecenter.entity.FlowMonitor;
import com.ho.filecenter.service.FlowMonitorService;
import com.ho.filecenter.service.TelecomApiService;
import com.ho.filecenter.vo.flowMonitor.CardInfoDate;
import com.ho.filecenter.vo.flowMonitor.FlowMonitorAddVo;
import com.ho.filecenter.vo.flowMonitor.FlowMonitorPutVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
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.net.URLEncoder;
import java.util.Base64;
import java.util.Date;
import java.util.List;

/**
 * @author gyan
 * @desc: 电信接口Api调用
 * @DateTime: 2024/1/16 15:37
 */
@Service
@Slf4j
public class TelecomApiServiceImpl implements TelecomApiService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private FlowMonitorService flowMonitorService;

    @Value("${telecom.appId}")
    String appId;
    @Value("${telecom.keyNew}")
    String keyNew;
    @Value("${telecom.url}")
    String url;
    @Value("${telecom.pwd}")
    String pwd;


    /**
     * 电信定时任务
     * 存入的数据（卡的基本信息以及卡的用量数据）
     */
/*    @Override
    public void getTelecomAllData(List<FlowMonitor> telecomFlowMonitors) {
        String monthBatch = getMonthBatch();
        if (monthBatch != null) {
            JSONObject jsonObject = JSONObject.parseObject(monthBatch, JSONObject.class);
            String resultCode = (String) jsonObject.get("resultCode");
            Integer statusInteger = Integer.valueOf(resultCode);
            if (CommonConstant.ZERO.equals(statusInteger)) {
                JSONObject description = (JSONObject) jsonObject.get("description");
                if (description != null) {
                    JSONArray simList = (JSONArray) description.get("simList");
                    for (Object sim : simList) {
                        CardInfoDate cardInfoDate = new CardInfoDate();
                        JSONObject obj = (JSONObject) sim;
                        //卡号
                        String iccId = (String) obj.get("iccid");
                        //状态  激活1  未激活 0  去激活2、停机3、拆机4")
                        String state = (String) obj.get("state"); //已激活、去激活、停机、拆机
                        if (state.equals("已激活")) {
                            cardInfoDate.setStatus(1);
                        } else if (state.equals("去激活")) {
                            cardInfoDate.setStatus(2);
                        } else if (state.equals("停机")) {
                            cardInfoDate.setStatus(3);
                        } else if (state.equals("拆机")) {
                            cardInfoDate.setStatus(4);
                        }
                        //已使用流量  单位 b (字节)
                        String totalVolumnGPRS = (String) obj.get("totalVolumnGPRS");
                        cardInfoDate.setCardNo(iccId);
                        //单位转换 1KB=1024B
                        BigDecimal divide = new BigDecimal(totalVolumnGPRS).divide(new BigDecimal("1024"));
                        cardInfoDate.setUserAmount(divide.toString());
                        String format = DateFormatUtils.format(new Date(), CommonConstant.DATE);
                        cardInfoDate.setUpdateTime(format);
                        String key = "flowMonitor:telecom:appId:" + appId + ":iccId:" + iccId;
                        redisService.set(key, cardInfoDate);
                    }
                }
            }
        }
        //调用卡信息数据
        //SIM 卡列表查询接口
        //getCardList();

    }*/
    @Override
    public void getTelecomAllData(List<FlowMonitor> telecomFlowMonitors) {
        String monthBatch = getCardList();
        if (monthBatch != null) {
            JSONObject jsonObject = JSONObject.parseObject(monthBatch, JSONObject.class);
            String resultCode = (String) jsonObject.get("resultCode");
            Integer statusInteger = Integer.valueOf(resultCode);
            if (CommonConstant.ZERO.equals(statusInteger)) {
                JSONObject description = (JSONObject) jsonObject.get("description");
                if (description != null) {
                    JSONArray simList = (JSONArray) description.get("simList");
                    for (Object sim : simList) {
                        CardInfoDate cardInfoDate = new CardInfoDate();
                        JSONObject obj = (JSONObject) sim;
                        //卡号
                        String iccId = (String) obj.get("iccid");
                        //状态  激活1  未激活 0  去激活2、停机3、拆机4")
                        String state = (String) obj.get("simStatus"); //已激活、去激活、停机、拆机
                        if (state.equals("已激活")) {
                            cardInfoDate.setStatus(1);
                        } else if (state.equals("去激活")) {
                            cardInfoDate.setStatus(2);
                        } else if (state.equals("停机")) {
                            cardInfoDate.setStatus(3);
                        } else if (state.equals("拆机")) {
                            cardInfoDate.setStatus(4);
                        }
                        //已使用流量  单位 b (字节)
                        BigDecimal decimal = new BigDecimal("1024");
                        Object totalVolumnGPRS = obj.get("totalVolumnGPRS");
                        cardInfoDate.setCardNo(iccId);
                        //单位转换 1KB=1024B
                        BigDecimal divide = new BigDecimal(String.valueOf(totalVolumnGPRS)).divide(decimal);
                        cardInfoDate.setUserAmount(divide.toString());
                        String format = DateFormatUtils.format(new Date(), CommonConstant.DATE);
                        //开卡时间
                        String paddleDate = (String) obj.get("paddle_date");
                        if (paddleDate != null) {
                            cardInfoDate.setOpenDate(paddleDate.substring(0, 10));
                        }
                        //激活时间
                        String activateDate = (String) obj.get("activate_date");
                        if (activateDate != null) {
                            cardInfoDate.setActivationDate(activateDate.substring(0, 10));
                        }
                        //套餐id
                        String pid = (String) obj.get("pid");
                        cardInfoDate.setGroupId(pid);
                        cardInfoDate.setUpdateTime(format);
                        String key = "flowMonitor:telecom:appId:" + appId + ":iccId:" + iccId;
                        redisService.set(key, cardInfoDate);
                    }
                }
            }
        }
    }

    /**
     * 获取套餐列表/并存入套餐表中
     */
    @Override
    public String getTelecomRefresh() {
        String allPack = getAllPack();
        if (allPack != null) {
            JSONObject packInfoObject = JSON.parseObject(allPack);
            if (packInfoObject != null) {
                String resultCode = (String) packInfoObject.get("resultCode");
                Integer statusInteger = Integer.valueOf(resultCode);
                if (CommonConstant.ZERO.equals(statusInteger)) {
                    JSONArray packInfoJSONArray = (JSONArray) packInfoObject.get("description");
                    for (int i = 0; i < packInfoJSONArray.size(); i++) {
                        FlowMonitorAddVo vo = new FlowMonitorAddVo();
                        JSONObject JSONObject = (JSONObject) packInfoJSONArray.get(i);
                        Integer pid = (Integer) JSONObject.get("pid");
                        String package_name = (String) JSONObject.get("package_name");
                        String type = (String) JSONObject.get("type");
                        //电信单位B-> 存储的是MB
                        String flow = (String) JSONObject.get("flow");
                        ////运营商（1：中国移动2：中国联通3：中国电信）
                        vo.setPackageName(package_name);
                        vo.setGroupId(pid.toString());
                        //2 是单卡  1 套餐
                        if (type.equals(CommonConstant.TelecomType.SINGLE)) {
                            vo.setSingleOrGroup(CommonConstant.TWO);
                        }
                        if (type.equals(CommonConstant.TelecomType.POOL)) {
                            vo.setSingleOrGroup(CommonConstant.ONE);
                        }
                        vo.setPackageType(CommonConstant.THREE);
                        //1MB=1024KB，1KB=1024B
                        BigDecimal decimal = new BigDecimal("1024");
                        BigDecimal divide = new BigDecimal(flow).divide(decimal);
                        Integer flowValue = divide.intValue();
                        vo.setTotalAmount(flowValue);
                        //根据pid查询看数据是否存在/存在则更新 不存在则新增
                        FlowMonitor flowMonitor = flowMonitorService.selectByPid(vo);
                        if (flowMonitor == null) {
                            int result = flowMonitorService.insertSelective(vo);
                        } else {
                            FlowMonitorPutVo putVo = new FlowMonitorPutVo();
                            putVo.setTotalAmount(flowValue);
                            BeanUtils.copyProperties(flowMonitor, putVo);
                            flowMonitorService.updateByPrimaryKeySelective(putVo);
                        }
                        continue;
                    }
                }
            }
        }
        return allPack;
    }

    /**
     * 电信批量
     */
    public String getMonthBatch() {
        Integer pageIndex = 0;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", appId);
        jsonObject.put("pwd", pwd);
        jsonObject.put("pageIndex", pageIndex);
        String info = XorEncryptAndBaseNew(jsonObject.toJSONString(), keyNew);
        String body = "id=" + appId + "&info=" + info;
        log.info("body:" + body);
        //发送http请求
        String rsp = HttpRequest.post(url).contentType("application/x-www-form-urlencoded")
                .body(body)
                .execute().body();
        log.info("rsp:" + rsp);
        return rsp;
    }

    //查单卡
    //String iccid
    @Override
    public CardInfoDate getSingle(String iccid) {
        String url = "http://global.anhuiyk.cn:8006/m2m_api/v1/query/";
        String method = "getSIMInfo";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", appId);
        jsonObject.put("pwd", pwd);
        jsonObject.put("method", method);
        jsonObject.put("iccid", iccid);
        String info = XorEncryptAndBaseNew(jsonObject.toJSONString(), keyNew);
        String body = "id=" + appId + "&info=" + info;
        log.info("body:" + body);
        //发送http请求
        String rsp = HttpRequest.post(url).contentType("application/x-www-form-urlencoded")
                .body(body)
                .execute().body();
        log.info("rsp:" + rsp);
        CardInfoDate cardInfoDate = new CardInfoDate();
        if (rsp != null) {
            JSONObject json = JSONObject.parseObject(rsp, JSONObject.class);
            String resultCode = (String) json.get("resultCode");
            Integer statusInteger = Integer.valueOf(resultCode);
            if (CommonConstant.ZERO.equals(statusInteger)) {
                JSONObject obj = (JSONObject) json.get("description");
                //卡号
                String iccId = (String) obj.get("iccid");
                //状态  激活1  未激活 0  去激活2、停机3、拆机4")
                String state = (String) obj.get("simStatus"); //已激活、去激活、停机、拆机
                if (state.equals("已激活")) {
                    cardInfoDate.setStatus(1);
                } else if (state.equals("去激活")) {
                    cardInfoDate.setStatus(2);
                } else if (state.equals("停机")) {
                    cardInfoDate.setStatus(3);
                } else if (state.equals("拆机")) {
                    cardInfoDate.setStatus(4);
                }
                //已使用流量  单位 b (字节)
                BigDecimal decimal = new BigDecimal("1024");
                Object totalVolumnGPRS = obj.get("totalVolumnGPRS");
                cardInfoDate.setCardNo(iccId);
                //单位转换 1KB=1024B
                BigDecimal divide = new BigDecimal(String.valueOf(totalVolumnGPRS)).divide(decimal);
                cardInfoDate.setUserAmount(divide.toString());
                String format = DateFormatUtils.format(new Date(), CommonConstant.DATE);
                //开卡时间
                String paddleDate = (String) obj.get("paddle_date");
                if (paddleDate != null) {
                    cardInfoDate.setOpenDate(paddleDate.substring(0, 10));
                }
                //激活时间
                String activateDate = (String) obj.get("activate_date");
                if (activateDate != null) {
                    cardInfoDate.setActivationDate(activateDate.substring(0, 10));
                }
                //套餐id
                String pid = (String) obj.get("pid");
                cardInfoDate.setGroupId(pid);
                cardInfoDate.setUpdateTime(format);
                System.out.println("cardInfoDate:" + cardInfoDate);

            }
        }
        return cardInfoDate;
    }

    //查单卡
    public String getSingleCard(String iccid) {
        // 卡号:89860466121980600213
        String url = "http://global.anhuiyk.cn:8006/m2m_api/v1/query/";
        String id = "SHYXSYYXGS614@2022"; //appid
        String pwd = "4af95d820738fe35";
        String method = "queryTraffic";
        String key = "f3758fdd8a278d60";


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", id);
        jsonObject.put("pwd", pwd);
        jsonObject.put("method", method);
        jsonObject.put("iccid", iccid);
        //将map转为info 字符串

        String info = XorEncryptAndBaseNew(jsonObject.toJSONString(), key);
        String body = "id=" + id + "&info=" + info;
        log.info("body:" + body);
        //发送http请求
        String rsp = HttpRequest.post(url).contentType("application/x-www-form-urlencoded")
                .body(body)
                .execute().body();
        log.info("rsp:" + rsp);

        String totalVolumnGPRS = null;
        if (rsp != null) {
            JSONObject infoObject = JSON.parseObject(rsp);
            if (infoObject != null) {
                String resultCode = (String) infoObject.get("resultCode");
                Integer statusInteger = Integer.valueOf(resultCode);
                if (CommonConstant.ZERO.equals(statusInteger)) {
                    JSONObject packInfoJSONArray = (JSONObject) infoObject.get("description");
                    //{"resultCode":"0","description":{"msisdn":"1440662294313","iccid":"89860466121980600213","totalVolumnGPRS":"98304"},"resultMsg":"查询成功"}
                    //电信单位B-> 存储的是MB
                    String flow = (String) packInfoJSONArray.get("totalVolumnGPRS");
                    //1MB=1024KB，1KB=1024B
                    BigDecimal decimal = new BigDecimal("1024");
                    BigDecimal divide = new BigDecimal(flow).divide(decimal);
                    totalVolumnGPRS = divide.toString();
                }
            }
        }
        return totalVolumnGPRS;
    }

    /**
     * 电信查询所有的套餐
     */
    public String getAllPack() {
        String method = "packageList";
        String cardListUrl = "http://global.anhuiyk.cn:8006/m2m_api/v1/query/";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", appId);
        jsonObject.put("pwd", pwd);
        jsonObject.put("method", method);
        String info = XorEncryptAndBaseNew(jsonObject.toJSONString(), keyNew);
        String body = "id=" + appId + "&info=" + info;
        //发送http请求
        String rsp = HttpRequest.post(cardListUrl).contentType("application/x-www-form-urlencoded")
                .body(body)
                .execute().body();
        log.info("rsp:" + rsp);
        return rsp;
    }


    /**
     * 电信查询SIM 卡列表查询接口
     */
    public String getCardList() {
        String cardListUrl = "http://global.anhuiyk.cn:8006/m2m_api/v1/query/";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", appId);
        jsonObject.put("pwd", pwd);
        jsonObject.put("method", "getSIMList");
        Integer pageIndex = 1;
        jsonObject.put("pageIndex", pageIndex);
        jsonObject.put("cardType", "4G");
        //cardType 卡片类型 4G 根据卡片类型查询卡列表
        //将map转为info 字符串
        String info = XorEncryptAndBaseNew(jsonObject.toJSONString(), keyNew);
        String body = "id=" + appId + "&info=" + info;
        log.info("body:" + body);
        //发送http请求
        String rsp = HttpRequest.post(cardListUrl).contentType("application/x-www-form-urlencoded")
                .body(body)
                .execute().body();
        log.info("rsp:" + rsp);
        return rsp;
        //dealTeleCom(rsp);
    }


    /**
     *  处理电信电信查询SIM 卡列表返回数据
     */
/*    private List<> dealTeleCom(String res) {
        JSONObject jsonObject = JSONObject.parseObject(res, JSONObject.class);
        String resultCode = (String) jsonObject.get("resultCode");
        if ("0".equals(resultCode)) {
            JSONObject description = (JSONObject) jsonObject.get("description");
            JSONArray simList = (JSONArray) description.get("simList");
            for (Object sim : simList) {
                JSONObject obj = (JSONObject) sim;
                //卡号
                String iccid = (String) obj.get("iccid");
                //状态
                String state = (String) obj.get("state"); //已激活、去激活、停机、拆机
                //已使用流量  单位 b (字节)
                String totalVolumnGPRS = (String) obj.get("totalVolumnGPRS");
            }

        }


    }*/

    /**
     * 异或算法加密
     * *
     *
     * @param str 数 据
     * @return 返回解密/加密后的数据
     */
    public static String XorEncryptAndBaseNew(String str, String key) {
        byte[] b1 = str.getBytes();
        byte[] b2 = key.getBytes();
        byte[] out = new byte[b1.length];
        for (int i = 0; i < b1.length; i++) {
            out[i] = (byte) (b1[i] ^ b2[i % b2.length]);
        }
        return URLEncoder.encode(Base64.getEncoder().encodeToString(out));
    }

}
