package com.dsk.common.utils;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.Random;

/**
 * 密码工具类
 *
 * @author sxk
 * @date 2023.08.31
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class PasswordUtils {
    private static final String LOWER_CASE = "abcdefghijklmnopqrstuvwxyz";
    private static final String UPPER_CASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String NUMBERS = "0123456789";

    /**
     * 生成随机密码
     * @param length 密码长度
     * @return 新生成的密码
     */
    public static String generatePwd(int length) {
        StringBuilder password = new StringBuilder();
        Random random = new Random();

        // 至少包含一个小写字母
        password.append(LOWER_CASE.charAt(random.nextInt(LOWER_CASE.length())));

        // 至少包含一个大写字母
        password.append(UPPER_CASE.charAt(random.nextInt(UPPER_CASE.length())));


        // 生成剩余部分的密码
        for (int i = 0; i < length - 2; i++) {
            // 至少包含一个数字
            password.append(NUMBERS.charAt(random.nextInt(NUMBERS.length())));
//            String characters = LOWER_CASE + UPPER_CASE + NUMBERS;
//            password.append(characters.charAt(random.nextInt(characters.length())));
        }

        // 打乱密码中字符的顺序
//        return shufflePassword(password.toString());
        return password.toString();
    }

    public static void main(String[] args) {
        System.out.println(PasswordUtils.generatePwd(8));
    }

    public static String shufflePassword(String password) {
        char[] passwordArray = password.toCharArray();
        Random random = new Random();

        for (int i = passwordArray.length - 1; i > 0; i--) {
            int index = random.nextInt(i + 1);
            char temp = passwordArray[index];
            passwordArray[index] = passwordArray[i];
            passwordArray[i] = temp;
        }

        return new String(passwordArray);
    }

}
