package cn.hnthyy.thmz.Utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class SignUtil {

    public static String getSignValue(Map<String, String> map, String key) throws Exception {
        List<String> list = new ArrayList<>();
        for (Map.Entry<String, String> entry : map.entrySet())
            if (null != entry.getValue() && !StringUtils.isEmpty(entry.getValue() + ""))
                list.add(entry.getKey() + "=" + entry.getValue() + "&");
        int size = list.size();
        String[] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++)
            sb.append(arrayToSort[i]);
        if (!StringUtils.isEmpty(key))
            sb.append(key);
        byte[] target = sb.toString().getBytes(StandardCharsets.UTF_8);
        return DigestUtils.md5Hex(target).toUpperCase();
    }
}
