package com.sckw.core.utils;

import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@Component
public class OrderUtils {
    private static final String ORDER_DATE_FORMAT = "yyyyMMddHHmmss";
    private static final int ORDER_NUMBER_WIDTH = 4;
    private static final SimpleDateFormat sdf = new SimpleDateFormat(ORDER_DATE_FORMAT);
    private static final ConcurrentHashMap<String, AtomicLong> orderCounters = new ConcurrentHashMap<>();
    private static String currentDateStr = "";

    public static String generateOrderNo(String prefix) {
        String currentDateString = sdf.format(new Date());
        if (!currentDateString.equals(currentDateStr)) {
            orderCounters.put(prefix, new AtomicLong(0));
            currentDateStr = currentDateString;
        }
        // 获取或创建与前缀相关联的订单号计数器
        AtomicLong counter = orderCounters.computeIfAbsent(prefix, key -> new AtomicLong(0));
        // 自增并获取当前订单号
        long orderId = counter.incrementAndGet();
        // 格式化订单号
        return String.format("%s%s%0" + ORDER_NUMBER_WIDTH + "d", prefix, currentDateString, orderId);
    }
}
