package com.cpxt.web.controller.biz.orderutil;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.SM4;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Base64;

/**
 * TODO
 *
 * @Author Mitch
 * @Date 2024-12-12 16:30
 */
@Slf4j
@Component
public class cityDelivery_SM4Util {



    public static String encryptCBC(String str, String secretKey, String iv) {
        return encryptCBC(str, secretKey, iv, true);
    }

    public static String encryptCBC(String str, String secretKey, String iv, boolean checkBase64) {
        String encryptBase64 = null;
        if (StrUtil.isEmpty(str)) {
            return "";
        }
        if (checkBase64 && isBase64(str)) {
            return str;
        }
        SM4 sm4 = new SM4(Mode.CBC, Padding.PKCS5Padding,
                secretKey.getBytes(CharsetUtil.CHARSET_UTF_8),
                iv.getBytes(CharsetUtil.CHARSET_UTF_8));
        encryptBase64 = sm4.encryptBase64(str);
        return encryptBase64;
    }

    public static String decryptCBC(String str, String secretKey, String iv) {
        return decryptCBC(str, secretKey, iv, true);
    }

    public static String decryptCBC(String str, String secretKey, String iv, boolean checkBase64) {
        String decryptStr = null;
        try {
            if (checkBase64 && !isBase64(str)) {
                return str;
            }
            SM4 sm4 = new SM4(Mode.CBC, Padding.PKCS5Padding,
                    secretKey.getBytes(CharsetUtil.CHARSET_UTF_8),
                    iv.getBytes(CharsetUtil.CHARSET_UTF_8));
            decryptStr = sm4.decryptStr(str);
        } catch (Exception e) {
            log.error("解密参数：{}", str, "国密解密算法工具类异常--->{}", ExceptionUtil.getMessage(e));
            e.printStackTrace();
        }
        return decryptStr;
    }

    public static boolean isBase64(String input) {
        char specificChar = '=';
        if (input == null || input.isEmpty()) {
            return false;
        }
        if (input.length() == 20 && input.matches("[0-9]+")) {
            return false;
        }
        if (input.length() % 4 != 0) {
            return false;
        }
        if (input.length() < 16) {
            return false;
        }
        if (input.length() == 16 && input.matches("[0-9]+")) {
            return false;
        }
        try {
            byte[] decodedBytes = Base64.getDecoder().decode(input);
            // 判断是否以=号结尾的
            if (input.endsWith(String.valueOf(specificChar))) {
                int numEquals = 0;
                for (int i = input.length() - 1; i >= 0; i--) {
                    if (input.charAt(i) == '=') {
                        numEquals++;
                    } else {
                        break;
                    }
                }
                return numEquals >= 0 && numEquals <= 2;
            }
            for (char c : input.toCharArray()) {
                if (!(isBase64Character(c))) {
                    return false;
                }
            }

            return true;
        } catch (IllegalArgumentException e) {
            return false;
        }
    }


    private static boolean isBase64Character(char c) {
        return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
                || (c >= '0' && c <= '9') || c == '+' || c == '/';
    }

    private static String getKey(){
        return RandomUtil.randomString(16);
    }

    public static void main(String[] args) {
        // String content = "我是字符串";
        //16位字符串
        String key = "nCWGwBstWF3MOu8T";
        String iv = "ABtjL78T7vBjhqyb";
        // String s = encryptCBC(content, key, iv);
        // System.out.println(s);
        String m = "1lcPgvBeFGaXJKrDfpOiAw==";
        String string = decryptCBC(m, key, iv);
        System.out.println(string);
    }
}
