package com.tofly.watermeter.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.security.MessageDigest;
import java.util.*;

public class SignHelperUtil {
    private static String machKey = "30ad4fe6b2a6aeed";

    public static String Sign(String data) {
        if (data == null) {
            return "";
        }
        Map<String, String> map = JSON.parseObject(data, new TypeReference<Map<String, String>>() {
        });
        map.remove("SING");
        Set<String> keys = map.keySet();
        //Array.Sort(keys, string.CompareOrdinal);排序后生成错误，生成的是倒序跟验证类不一致，导致生成签名错误
        List<String> list = new ArrayList<>();
        keys.forEach(k -> {
            Object o = map.get(k);
            list.add(k.toString().toLowerCase() + "=" + o.toString());
        });

        String stringSignTemp = String.join("&", list) + machKey;
        return SHA1(stringSignTemp);
    }

    private static String SHA1(String content) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(content.getBytes("UTF-8"));
            byte[] messageDigest = digest.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte message : messageDigest) {
                String shaHex = Integer.toHexString(message & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString().replace("-", "").toLowerCase();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}

