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

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.*;

/**
 * 百度交易中台双向RSA签名工具
 * JDK版本要求：1.8+
 */
@Slf4j
public class byteSign {
    private static final String SALT  = "deC9FBTRgoLvI8IV0Nz0Bcxitqp2pHUGnqYAmBoo";

    // paramsMap 参数含义解释同 golang
    public static String getSign(Map<String, Object> paramsMap) {
        List<String> paramsArr = new ArrayList<>();
        for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
            String key = entry.getKey();
            if (key.equals("other_settle_params")) {
                continue;
            }
            String value = entry.getValue().toString();

            value = value.trim();
            if (value.startsWith("\"") && value.endsWith("\"") && value.length() > 1) {
                value = value.substring(1, value.length() - 1);
            }
            value = value.trim();
            if (value.equals("") || value.equals("null")) {
                continue;
            }
            switch (key) {
                case "app_id":
                case "thirdparty_id":
                case "sign":
                    break;
                default:
                    paramsArr.add(value);
                    break;
            }
        }
        paramsArr.add(SALT);
        Collections.sort(paramsArr);
        StringBuilder signStr = new StringBuilder();
        String sep = "";
        for (String s : paramsArr) {
            signStr.append(sep).append(s);
            sep = "&";
        }
        return md5FromStr(signStr.toString());
    }

    public static String md5FromStr(String inStr) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }

        byte[] byteArray = inStr.getBytes(StandardCharsets.UTF_8);
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
    /**
     * 验证签名
     * @param jsonObject
     * @return
     */
    public static boolean checkSignature(JSONObject jsonObject) {
        String[] arr;
        if(jsonObject.getString("type").equals("settle")){
            JSONObject JsonMsg= new JSONObject();
            JSONObject msgjson= JSONObject.parseObject(jsonObject.getString("msg"));
            JsonMsg.put("appid",msgjson.getString("appid"));
            JsonMsg.put("cp_settle_no",msgjson.getString("cp_settle_no"));
            JsonMsg.put("cp_extra",msgjson.getString("cp_extra"));
            JsonMsg.put("status",msgjson.getString("status"));
            JsonMsg.put("rake",msgjson.get("rake"));
            JsonMsg.put("commission",msgjson.get("commission"));
            arr = new String[] {"6PJA6YAQGFPWTY2YNM80VB58FU4IDZNX", jsonObject.getString("timestamp"), jsonObject.getString("nonce"),JsonMsg.toString()};
        }else {
            arr = new String[] {"6PJA6YAQGFPWTY2YNM80VB58FU4IDZNX", jsonObject.getString("timestamp"), jsonObject.getString("nonce"),jsonObject.getString("msg")};
        }

        // 将token、timestamp、nonce三个参数进行字典序排序
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }
        MessageDigest md = null;
        String tmpStr = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            // 将四个参数字符串拼接成一个字符串进行sha1加密
            byte[] digest = md.digest(content.toString().getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        content = null;
        // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
        log.info("-------------tmpStr----------：" + tmpStr );
        log.info("-------------msg_signature----------：" + jsonObject.getString("msg_signature") );
        return Objects.equals(tmpStr, jsonObject.getString("msg_signature"));
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
     * 将字节转换为十六进制字符串
     *
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a', 'b', 'c', 'd', 'e', 'f'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }
}

