package com.ruoyi.web.modules.trading.support;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.trading.mapper.BizTradeOrderMapper;

/**
 * 交易订单编号：yyyyMMdd + 3 位当日序号。
 */
@Component
public class TradeOrderNoGenerator
{
    @Autowired
    private BizTradeOrderMapper bizTradeOrderMapper;

    public String allocateNextOrderNo()
    {
        String datePrefix = new SimpleDateFormat("yyyyMMdd").format(new Date());
        for (int attempt = 0; attempt < 3; attempt++)
        {
            String orderNo = datePrefix + formatSeq(nextSeq(datePrefix));
            if (bizTradeOrderMapper.countByOrderNo(orderNo) == 0)
            {
                return orderNo;
            }
        }
        throw new ServiceException(TradeOrderRules.MSG_ORDER_NO_CONFLICT);
    }

    private int nextSeq(String datePrefix)
    {
        String maxSuffix = bizTradeOrderMapper.selectMaxOrderNoSuffixByDatePrefix(datePrefix);
        int next = 1;
        if (StringUtils.isNotEmpty(maxSuffix))
        {
            next = Integer.parseInt(maxSuffix.trim()) + 1;
        }
        if (next > TradeOrderRules.MAX_ORDER_SEQ_PER_DAY)
        {
            throw new ServiceException(TradeOrderRules.MSG_ORDER_NO_LIMIT);
        }
        return next;
    }

    private static String formatSeq(int seq)
    {
        return String.format("%03d", seq);
    }
}
