package com.yuchen.saas.park.service.util;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;

public class SignUtils {

    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * 提取HmacMD5摘要
     */
    public static String signature(Map<String, String> map, String secret) throws InvalidKeyException,
            NoSuchAlgorithmException {
        return HMACMD5(getSignString(map), secret);
    }

    public static String getSignature(String sign, String secret) throws NoSuchAlgorithmException, InvalidKeyException {
        SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), "HmacMD5");
        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(sign.getBytes());
        return byteArrayToHexString(rawHmac);
    }

    public static String byteArrayToHexString(byte[] b) {
        StringBuffer sb = new StringBuffer(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            int v = b[i] & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString();
    }

    public static String HMACMD5(String sign, String secret) throws NoSuchAlgorithmException, InvalidKeyException {
        System.out.println(" SIGN : " + sign);
        SecretKeySpec signingKey = new SecretKeySpec((secret + "&").getBytes(), "HmacMD5");
        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(sign.getBytes());
        return java.util.Base64.getEncoder().encodeToString(rawHmac);
    }


    public static boolean verifyParam(Map<String, String> map, String secret) throws NoSuchAlgorithmException,
            InvalidKeyException {
        String signValue = map.get("sign");
        if (null == signValue || "".equals(signValue.trim())) {
            return false;
        } else {
            String sign = signature(map, secret);
            return signValue.equals(sign);
        }
    }

    /**
     * 拼接获取签名串
     */
    public static String getSignString(Map<String, String> map) {
        Map<String, String> sortMap = sortMapByKey(map);
        StringBuilder sb = new StringBuilder();

        try {
            sb.append(getAscFromMap(sortMap));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * Map<key,value>排序拼接
     */
    public static String getAscFromMap(Map<String, String> map) {
        StringBuilder sb = new StringBuilder();

        try {
            Iterator iterator = map.entrySet().iterator();

            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry) iterator.next();
                if (!(entry.getKey()).equals("sign")) {
                    String keyEncode = percentEncode(entry.getKey());
                    String valueEncode = percentEncode(entry.getValue());
                    sb.append(keyEncode).append('=').append(valueEncode).append('&');
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return sb.substring(0, sb.length() - 1);
    }

    /**
     * Map<key,value>按字典升序排序
     */
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map != null && !map.isEmpty()) {
            Map<String, String> sortMap = new TreeMap(new Comparator<String>() {
                public int compare(String str1, String str2) {
                    return str1.compareTo(str2);
                }
            });
            map.forEach((key, value) -> {
                sortMap.put(key, value);
            });
            return sortMap;
        } else {
            return null;
        }
    }

    /**
     * URL编码
     */
    public static String percentEncode(String value) throws UnsupportedEncodingException {
        return value != null ? URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A")
                .replace("%7E", "~")
                : null;
    }

    /**
     * URL解码
     */
    public static String percentDecode(String value) throws UnsupportedEncodingException {
        return value != null ? URLDecoder
                .decode(value.replace("%20", "+").replace("%2A", "*").replace("~", "%7E"), "UTF-8")
                : null;
    }

    /**
     * 获取加密秘钥
     */
    private static SecretKeySpec getSecretKey(final String deviceSecret) {
        byte[] enCodeFormat = deviceSecret.getBytes();
        return new SecretKeySpec(enCodeFormat, KEY_ALGORITHM);
    }


    /**
     * AES 加密操作
     */
    public static String encrypt(String data, String deviceSecret) {
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
            byte[] byteContent = data.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(deviceSecret));// 初始化为加密模式的密码器
            byte[] result = cipher.doFinal(byteContent);// 加密
            return java.util.Base64.getEncoder().encodeToString(result);// 通过Base64转码返回
        } catch (Exception ex) {
            java.util.logging.Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }
}
