package com.fs.watch.utils;

import com.alibaba.fastjson.JSON;
import com.fs.common.core.page.TableDataInfo;
import com.fs.watch.domain.IotSim;
import com.fs.watch.domain.IotSimTable;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class IotUtils {
    private final static String apiAddress = "219.153.134.60:3666";
    private final static String v = "1.0";
    private final static String appid = "240";
//    private final static String apiKey = "3d0193daa1c44dd0ba73c71de70bdf62";
    private final static String apiKey = "38084a19ea3b43b1b39a64cb20e3f7eb";

    private final static MyHttpUtils httpUtils = new MyHttpUtils();

    /**
     * 5.SIM卡资料查询
     * @param iccid
     * @return
     */
    public static IotSim querySIMInfo(String iccid){
        String action = "querySIMInfo";
        HashMap<String, Object> map = new HashMap<>();
        map.put("action",action);
        map.put("v","1.3");
        map.put("appid",appid);
        map.put("iccid",iccid);
        String sign = getSign(map);
        map.put("sign",sign);
        Map request3 = httpUtils.getRequest3(apiAddress, "/iot", map);
        if(request3 != null) {
            if(request3.get("sim") == null) {
                return null;
            }
            return JSON.parseObject(request3.get("sim").toString(), IotSim.class);
        }
        return null;
    }

    /**
     * 6.SIM卡列表获取
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public static TableDataInfo querySIMTable(Integer pageIndex, Integer pageSize){
        IotSimTable iotSimTable = querySIMList(pageIndex, pageSize);
        if(iotSimTable != null) {
            TableDataInfo tableDataInfo = new TableDataInfo();
            //查询最后一页多少条数据
            IotSimTable temp = querySIMList(iotSimTable.getPageTotalCount(), pageSize);
            if(temp!=null){
                tableDataInfo.setTotal(temp.getList().size()+(long) pageSize *(iotSimTable.getPageTotalCount()-1));
            }
            tableDataInfo.setRows(iotSimTable.getList());
            return tableDataInfo;
        }
        return null;
    }

    /**
     * 6.SIM卡列表获取
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public static IotSimTable querySIMList(Integer pageIndex, Integer pageSize){
        String action = "querySIMList";
        HashMap<String, Object> map = new HashMap<>();
        map.put("action",action);
        map.put("v",v);
        map.put("pageIndex",pageIndex);
        map.put("pageSize",pageSize);
        map.put("appid",appid);
        String sign = getSign(map);
        map.put("sign",sign);
        Map request3 = httpUtils.getRequest3(apiAddress, "/m2m", map);
        if(request3 != null) {
            String str = request3.get("list").toString();
            Integer pageTotalCount =(Integer) request3.get("pageTotalCount");
            IotSimTable iotSimTable = new IotSimTable();
            iotSimTable.setList(JSON.parseArray(str, IotSim.class));
            iotSimTable.setPageTotalCount(pageTotalCount);
            return iotSimTable;
        }
        return null;
    }


    private static String getSign(Map<String, Object> params){
        // 将参数按key升序排序
        Map<String, Object> sortedParams = new TreeMap<>(params);

        // 构建待签名字符串
        StringBuilder signBuilder = new StringBuilder(apiKey);
        for (Map.Entry<String, Object> entry : sortedParams.entrySet()) {
            signBuilder.append(entry.getValue());
        }

        // 使用MD5算法生成签名
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hashBytes = md.digest(signBuilder.toString().getBytes(StandardCharsets.UTF_8));
            return bytesToHex(hashBytes);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param bytes 字节数组
     * @return 十六进制字符串
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
