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.BizSupplierSettlementMapper;

/**
 * 结算单编号：JSD + yyyyMMdd + 3 位当日序号。
 */
@Component
public class SettlementNoGenerator
{
    private static final int MAX_SEQ = 999;

    @Autowired
    private BizSupplierSettlementMapper bizSupplierSettlementMapper;

    public String allocateNextSettlementNo()
    {
        String datePrefix = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String maxSuffix = bizSupplierSettlementMapper.selectMaxSettlementNoSuffixByDatePrefix(datePrefix);
        int next = 1;
        if (StringUtils.isNotEmpty(maxSuffix))
        {
            next = Integer.parseInt(maxSuffix.trim()) + 1;
        }
        if (next > MAX_SEQ)
        {
            throw new ServiceException("当日结算单编号已达上限，请联系管理员");
        }
        return "JSD" + datePrefix + String.format("%03d", next);
    }
}
