package com.zg.project.wisdom.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class BillNoUtil {
    // 内存缓存：key = prefix + date，value = 当前递增号
    private static final Map<String, AtomicInteger> DAILY_SEQUENCE_MAP = new ConcurrentHashMap<>();

    /**
     * 生成当天单据号（格式：RK20250731_1、CK20250731_2）
     * @param prefix 单据前缀（如 RK 或 CK）
     * @return 单据号
     */
    public static synchronized String generateTodayBillNo(String prefix) {
        if (prefix == null || prefix.trim().isEmpty()) {
            prefix = "RK";
        }

        // 获取当天日期字符串 yyyyMMdd
        String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String key = prefix + today;

        // 获取并递增序号
        AtomicInteger counter = DAILY_SEQUENCE_MAP.computeIfAbsent(key, k -> new AtomicInteger(1));
        int sequence = counter.getAndIncrement();

        return prefix + today + "_" + sequence;
    }
}

