package com.lutao.cloud.common.core.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TokenUtils {
    private static final Logger logger = LoggerFactory.getLogger(TokenUtils.class);
    private static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a",
            "b", "c", "d", "e",
            "f" };
    public static String getSignature(String appPwd, String paramUrl) {
        if (StringUtil.isNotBlank(paramUrl)) {
            try {
                paramUrl = URLDecoder.decode(paramUrl, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("生成 signData 失败:", e);
                throw new RuntimeException("生成 signData 失败:", e);
            }
        }
        String[] paraArray = new String[] {};
        if (StringUtil.isNotBlank(paramUrl)) {
            String[] queryArray = paramUrl.split("&");
            paraArray = (String[]) ArrayUtils.addAll(queryArray, paraArray);
        }
        Arrays.sort(paraArray);
        StringBuffer buffer = new StringBuffer();
        buffer.append(appPwd);
        buffer.append(":");
        for (int i = 0; i < paraArray.length; i++) {
            buffer.append(paraArray[i]);
            buffer.append("&");
        }
        buffer.deleteCharAt(buffer.length() - 1);
        buffer.append(":");
        buffer.append(appPwd);
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-256");
            md.update(buffer.toString().getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            logger.error("生成 signData 失败:", e);
            throw new RuntimeException("生成 signData 失败.", e);
        } catch (UnsupportedEncodingException e) {
            logger.error("生成 signData 失败:", e);
            throw new RuntimeException("生成 signData 失败.", e);
        }
        String encode = byteArrayToHexString(md.digest());
        return encode;
    }
    private static String byteArrayToHexString(byte[] byteArray) {
        StringBuffer sb = new StringBuffer();
        for (byte byt : byteArray) {
            sb.append(byteToHexString(byt));
        }
        return sb.toString();
    }
    private static String byteToHexString(byte byt) {
        int n = byt;
        if (n < 0)
            n = 256 + n;
        return hexDigits[n / 16] + hexDigits[n % 16];
    }
}
