package cn.gintone.encryptionUtils;

import cn.hutool.json.JSONObject;
import com.alibaba.druid.util.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.spec.KeySpec;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

public class DataDesensitizationUtils {

    // 无效化处理(从第几位到第几位)
    public static String invalidatePhone(String str, int beginNum, int endNum) {
        if (StringUtils.isEmpty(str)) {
            return "**";
        }
        if (beginNum > endNum) {
            return "**";
        }

        String score = "";
        for (int i = 0; i < (endNum - beginNum); i++) {
            score += "*";
        }
        if (endNum >= str.length()) {
            return str.substring(0, beginNum) + score + str.substring(str.length() );
        }
        return str.substring(0, beginNum) + score + str.substring(endNum);
    }

    // 随机值替换
    public static String randomPhone(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }

        Random random = new Random();
        char[] chars = str.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            // 生成32到126之间的随机ASCII字符（包含空格和可打印字符）
            chars[i] = (char) (random.nextInt(95) + 32);
        }

        return new String(chars);
    }

    // 数据替换
    public static String replaceRange(String original, String replacement, int start, int end) {
        if (original == null) {
            return null;
        }

        // 处理替换字符串为null的情况
        if (replacement == null) {
            replacement = "";
        }

        // 规范索引范围
        int safeStart = Math.max(0, start);
        int safeEnd = Math.min(end, original.length());

        // 确保起始索引不大于结束索引
        if (safeStart > safeEnd) {
            int temp = safeStart;
            safeStart = safeEnd;
            safeEnd = temp;
        }

        // 构建新字符串
        String prefix = original.substring(0, safeStart);
        String suffix = original.substring(safeEnd);
        return prefix + replacement + suffix;
    }


    // 对称加密（示例）
    public static String encryptAES(String data, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encrypted = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encrypted);
    }
    // 解密方法
    public static String decryptAES(String encryptedData, String key) throws Exception {
        // 1. 创建相同的密钥规范
        SecretKeySpec secretKey = new SecretKeySpec(
                key.getBytes(StandardCharsets.UTF_8),
                "AES"
        );

        // 2. 获取密码器实例（参数必须与加密时完全一致）
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

        // 3. 初始化密码器为解密模式
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        // 4. 执行解密操作
        byte[] decodedData = Base64.getDecoder().decode(encryptedData);
        byte[] decrypted = cipher.doFinal(decodedData);

        return new String(decrypted, StandardCharsets.UTF_8);
    }

    /*// 偏移运算
    public static int offsetAndRound(long value, int offsetRange) {
        int offset = ThreadLocalRandom.current().nextInt(-offsetRange, offsetRange + 1);
        return (int) Math.round(value + offset + ThreadLocalRandom.current().nextDouble());
    }*/

    // 偏移运算
    public static String shiftString(String str, int num) {
        if (str == null || str.isEmpty()) return str;

        StringBuilder sb = new StringBuilder();
        for (char c : str.toCharArray()) {
            // 计算偏移后的字符（自动处理char越界）
            sb.append((char) (c + num));
        }
        return sb.toString();
    }

    public static void main(String[] args) throws Exception {
        /*System.out.println("手机号脱敏: " + invalidatePhone("13812345678", 2, 5));
        System.out.println("随机替换: " + randomPhone("阿斯顿发生大法师大法师放大132123fsdasdfasdfasf"));

        String str = "asdfadfasdfasdfasdfasdfasdfasdfasdfasddfasdfhdfghfdghd";
        str = encryptAES(str, "sx+htIs=6a2t8qt%");
        System.out.println(str);
        System.out.println(decryptAES(str, "sx+htIs=6a2t8qt%"));

        System.out.println(shiftString("asdfjasdfiosdj呼呼收到回复", 12));*/

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "胡懿");
        Long l = 15234609999L;
        jsonObject.put("phone", l);
        long idCard = 142222199514442333L;
        jsonObject.put("idCard", idCard);
        System.out.println(jsonObject.toString());
    }
}