package com.example.demo.util;

import java.security.SecureRandom;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 用户ID生成器
 * 格式: yyMMdd + 5位随机数字
 * 示例: 24121112345
 */
public class UserIdGenerator {
    
    // 只使用数字
    private static final String CHARS = "0123456789";
    private static final SecureRandom RANDOM = new SecureRandom();
    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyMMdd");
    
    /**
     * 生成用户ID
     * @return 格式: yyMMdd + 5位随机数字 (共11位)
     */
    public static String generate() {
        String datePart = LocalDate.now().format(DATE_FORMAT);
        String randomPart = generateRandomString(5);
        return datePart + randomPart;
    }
    
    /**
     * 生成指定长度的随机字符串
     */
    private static String generateRandomString(int length) {
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(CHARS.charAt(RANDOM.nextInt(CHARS.length())));
        }
        return sb.toString();
    }
    
    /**
     * 验证用户ID格式是否正确
     */
    public static boolean isValid(String userId) {
        if (userId == null || userId.length() != 11) {
            return false;
        }
        // 检查是否全为数字
        return userId.matches("\\d{11}");
    }
}
