package com.ytpm.util;

import java.security.SecureRandom;
import java.util.HashSet;
import java.util.Set;

public class RandomPasswordGenerator {
    private static final String LOWER_CASE = "abcdefghijklmnopqrstuvwxyz";
    private static final String UPPER_CASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String NUMBERS = "0123456789";
    private static final String SPECIAL_CHARACTERS = "!@#$%^&*()_+-=[]{}|;:,.<>?";
    private static final String ALL_CHARACTERS = LOWER_CASE + UPPER_CASE + NUMBERS;
    private static final SecureRandom RANDOM = new SecureRandom();

    public static String generatePassword(int length) {
        if (length < 3) {
            throw new IllegalArgumentException("Password length must be at least 3");
        }

        StringBuilder password = new StringBuilder(length);
        Set<Character> charSet = new HashSet<>();

        // 确保每种类型的字符至少有一个
        password.append(getRandomChar(LOWER_CASE));
        password.append(getRandomChar(UPPER_CASE));
        password.append(getRandomChar(NUMBERS));
//        password.append(getRandomChar(SPECIAL_CHARACTERS));
        charSet.add(LOWER_CASE.charAt(0)); // 示例，实际应从生成的字符中添加到集合中
        charSet.add(UPPER_CASE.charAt(0)); // 示例，实际应从生成的字符中添加到集合中
        charSet.add(NUMBERS.charAt(0)); // 示例，实际应从生成的字符中添加到集合中
//        charSet.add(SPECIAL_CHARACTERS.charAt(0)); // 示例，实际应从生成的字符中添加到集合中

        // 填充剩余的字符直到达到所需长度
        while (password.length() < length) {
            char randomChar = getRandomChar(ALL_CHARACTERS);
            if (!charSet.contains(randomChar)) { // 确保不会重复添加已存在的字符类型
                password.append(randomChar);
                charSet.add(randomChar); // 添加到已选择字符集合中，以避免重复
            }
        }

        // 打乱顺序以确保随机性
        password = shufflePassword(password);
        return password.toString();
    }

    private static char getRandomChar(String characters) {
        int index = RANDOM.nextInt(characters.length());
        return characters.charAt(index);
    }

    private static StringBuilder shufflePassword(StringBuilder password) {
        char[] passwordArray = password.toString().toCharArray();
        for (int i = passwordArray.length - 1; i > 0; i--) {
            int j = RANDOM.nextInt(i + 1); // 生成一个[0, i]之间的随机数
            char temp = passwordArray[i]; // 交换数组中的两个元素
            passwordArray[i] = passwordArray[j];
            passwordArray[j] = temp;
        }
        return new StringBuilder(new String(passwordArray)); // 返回打乱后的字符串构建器对象
    }

    public static void main(String[] args) {
        System.out.println("Generated Password: " + generatePassword(8));
    }
}
