package com.qs.mp.common.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

public class IotTQSignUitls {

    // 随机字符串 后台获取
    private static String nonce = "wQ7rXWMZqnqq0Pus9";
    private static String token  = "bNzWLXxGlx3rbgHkRgFA";


    //API查询callback返回数据校验sign接口
    public static boolean checkSign(String response_content, String timestamp, String sign) {
        // 随机字符串 后台获取
        String buf = response_content + timestamp + nonce;
        String encode = getMD5(buf);
        return encode.equals(sign);
    }


    //订阅推送数据校验接口
    public static boolean checkSign(String response_content, String sign) {
        // 随机字符串 后台获取
        String buf = response_content + token;
        String encode = getMD5(buf);
        return encode.equalsIgnoreCase(sign);
    }


    // 生成签名字符串
    public static String getSign(Map<String, String> data)
    {
        // 获取关键字列表
        List<String> keys = new ArrayList<>(data.keySet());

        // 关键字列表排序
        keys.sort(Comparator.naturalOrder());
        StringBuilder sb = new StringBuilder();
        for (String key : keys)
        {
            // 取各个字段内容拼接字符串
            sb.append(data.get(key));
        }
        // 加上双方约定随机字符串
        String txt = sb.toString() + nonce;

        // 计算哈希值
        return getMD5(txt);
    }

    // md5加密
    public static String getMD5(String password) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        byte[] byteArray = password.getBytes(StandardCharsets.UTF_8);

        byte[] md5Bytes = md5.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }

            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

}
