package com.bohuikeji.frame.module.admin.utils.Huolala;


import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.*;

@Slf4j
public class HuolalaSignUtils {

    /**
     * Description:MD5工具生成token
     * @param value
     * @return
     */
    /*public static String getMD5Value(String value){
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] md5ValueByteArray = messageDigest.digest(value.getBytes());
            BigInteger bigInteger = new BigInteger(1 , md5ValueByteArray);
            return bigInteger.toString(16);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }*/
    public static String encrypt3ToMD5(String str) {
        String md5 = "  ";
        try {
            md5 = DigestUtils.md5DigestAsHex(str.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return md5;
    }

    /**
     * 生成签名
     *
     * @param map 签名参数
     * @param secret 应用密钥
     * @return
     */
    public static String getSignToken(Map<String, Object> map, String secret) {
        String result = "";
        try {
            List<Map.Entry<String, Object>> infoIds =
                    new ArrayList<Map.Entry<String, Object>>(map.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, Object>>() {
                @Override
                public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                    return (o1.getKey()).compareTo(o2.getKey());
                }
            });
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, Object> item : infoIds) {
                if (item.getKey() != null || item.getKey() != "") {
                    String key = item.getKey();
                    Object val = item.getValue();
                    if (!(val == "" || val == null)) {
                        sb.append(key + "=" + val + "&");
                    }
                }
            }
            result = sb.substring(0, sb.length() - 1) + secret;
            //进行MD5加密
            result = encrypt3ToMD5(result).toLowerCase();
        } catch (Exception e) {
            return null;
        }
        return result;
    }

}
