package com.hzs.common.core.utils;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

/**
 * Bean 生成国际编号和国家编号工具类
 *
 * @author hzs
 */
public class RandomNumberGenerator {

    private static final int MIN_VALUE = 10000;
    private static final int MAX_INCREMENT = 5;
    private static final Random RANDOM = new Random();

    public static String generate(String prefix,int count) {
        Set<String> existingNumbers = new HashSet<>();
        // 将当前最新编号添加到集合中
        existingNumbers.add(prefix + String.format("%08d", MIN_VALUE));
        // 尝试生成新的编号
        while (true) {
            String latestNumber = getLatestNumber(existingNumbers, prefix);
            String nextNumber = getNextNumber(latestNumber,count);
            if (existingNumbers.contains(nextNumber)) {
                continue;
            }
            existingNumbers.add(nextNumber);
            return nextNumber;
        }
    }

    private static String getLatestNumber(Set<String> existingNumbers, String prefix) {
        for (int i = MIN_VALUE; i <= Integer.MAX_VALUE; i++) {
            String number = prefix + String.format("%08d", i); // 编号格式化为 8 位数字
            if (!existingNumbers.contains(number)) {
                return prefix + String.format("%08d", i - 1); // 返回上一个编号
            }
        }
        throw new RuntimeException("Failed to get the latest number.");
    }

    /**
     * @description: 生成下一个编号
     * @author: zhang jing
     * @date: 2023/4/26 15:04
     * @param: [number]
     * @param: [count] 首字母个数
     * @return: java.lang.String
     **/
    public static String getNextNumber(String number,int count) {
        String prefix = number.substring(0, count);
        int value = Integer.parseInt(number.substring(count));
        value += RANDOM.nextInt(MAX_INCREMENT) + 1;
        return prefix + String.format("%08d", value);
    }

}
