package com.chaozhanggui.common.system.util;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Map;
import java.util.TreeMap;

/**
 * 签名工具类
 */
@Slf4j
public class SignUtils {

    /**
     * 获取签名之前的源串 按照ASCII 排序
     *
     * @param object
     * @return
     */
    public static String getSignContent(JSONObject object) {
        TreeMap<String, Object> map = JSONObject.parseObject(JSONObject.toJSONString(object), TreeMap.class);
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> o : map.entrySet()) {
            String key = o.getKey();
            Object value = o.getValue();
            if ("sign".contains(key)) {
                continue;
            }
            if (value != null) {
                sb.append(key).append("=").append(value).append("&");
//                if(value instanceof ArrayList || value instanceof Map){
//                    sb.append(key).append("=").append(JSON.toJSONString(value)).append("&");
//                }else{
//                    sb.append(key).append("=").append(value).append("&");
//                }
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    public static String wapGetSign(JSONObject object,String key) {
        String checkSign = MD5Util.MD5Encode(getSignContent(object) + "&key=" + key, "UTF-8");
        return checkSign;
    }

    /**
     * 获取签名之前的源串 按照ASCII 排序
     *
     * @param object
     * @return
     */
    public static String getYSSignContent(JSONObject object) {
        String s = JSONObject.toJSONString(object);
        TreeMap<String, Object> map = JSONObject.parseObject(s, TreeMap.class);
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> o : map.entrySet()) {
            String key = o.getKey();
            Object value = o.getValue();
            if ("sign".contains(key)) {
                continue;
            }
            if (ObjectUtil.isNotEmpty(value)) {
                sb.append(key).append("=").append(value).append("&");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    public static String getSignContent1(JSONObject object,String appSerct) {
        TreeMap<String, Object> map = JSONObject.parseObject(JSONObject.toJSONString(object), TreeMap.class);
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> o : map.entrySet()) {
            String key = o.getKey();
            Object value = o.getValue();
            if ("sign".contains(key)) {
                continue;
            }
            if (ObjectUtil.isNotEmpty(value)) {
                sb.append(key).append(value);
            }
        }
        sb.append(appSerct);
        return sb.toString();
    }

    public static String sha1Encrypt(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes(StandardCharsets.UTF_8));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;

            for (byte byte0 : md) {
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }
    public static String HMACSHA256BYTE(String data, String key) {
        String hash = "";
        try {
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
            sha256_HMAC.init(secret_key);
            byte[] array = sha256_HMAC.doFinal(data.getBytes());
            hash = Base64.encodeBase64String(array);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hash;
    }

    public static String getSignSha256(JSONObject params, String accessKeySecret) {
        return HMACSHA256BYTE(getSignContent(params),accessKeySecret);
    }

    /**
     * 获取圆通签名
     * @date: 2022/2/24 17:00
     * @param param:
     * @param secret:
     * @param method:
     * @param version:
     * @return java.lang.String
     */
    public static String getYtSign(String param, String secret,String method,String version) {
        String data = param + method + version;
        String sign;
        try {
            byte[] signByte = DigestUtils.md5(data + secret);
            sign = Base64.encodeBase64String(signByte);
        } catch (Throwable e) {
            log.error("加密失败.e:{}.", e.toString());
            sign = "ERROR";
        }
        return sign;
    }
}
