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

import java.math.BigDecimal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.trading.domain.BizGradeWeightConfig;
import com.ruoyi.web.modules.trading.domain.BizTradeOrderLine;
import com.ruoyi.web.modules.trading.mapper.BizGradeWeightConfigMapper;

/**
 * 按重量匹配 {@link BizGradeWeightConfig} 并写入明细 {@code grade_code}、{@code grade_name}。
 */
@Component
public class TradeOrderGradeResolver
{
    @Autowired
    private BizGradeWeightConfigMapper bizGradeWeightConfigMapper;

    /**
     * 为每行明细根据重量写入等级编码与名称（闭区间 [min_weight, max_weight]）。
     */
    public void assignGrades(List<BizTradeOrderLine> lines)
    {
        if (lines == null || lines.isEmpty())
        {
            return;
        }
        List<BizGradeWeightConfig> configs = bizGradeWeightConfigMapper.selectAllOrderBySort();
        if (configs == null || configs.isEmpty())
        {
            throw new ServiceException(TradeOrderRules.MSG_GRADE_CONFIG_EMPTY);
        }
        for (BizTradeOrderLine line : lines)
        {
            BizGradeWeightConfig matched = resolveGradeConfig(line.getWeight(), configs);
            if (matched == null)
            {
                throw new ServiceException(String.format(
                        TradeOrderRules.MSG_GRADE_NOT_MATCHED, line.getWeight()));
            }
            line.setGradeCode(matched.getGradeCode());
            line.setGradeName(matched.getGradeName());
        }
    }

    /**
     * 在配置列表中查找首个包含该重量的等级配置。
     */
    public static BizGradeWeightConfig resolveGradeConfig(BigDecimal weight, List<BizGradeWeightConfig> configs)
    {
        if (weight == null || configs == null)
        {
            return null;
        }
        for (BizGradeWeightConfig config : configs)
        {
            if (config == null || config.getGradeCode() == null)
            {
                continue;
            }
            if (inClosedRange(weight, config.getMinWeight(), config.getMaxWeight()))
            {
                return config;
            }
        }
        return null;
    }

    /**
     * 在配置列表中查找首个包含该重量的等级编码。
     */
    public static String resolveGradeCode(BigDecimal weight, List<BizGradeWeightConfig> configs)
    {
        BizGradeWeightConfig config = resolveGradeConfig(weight, configs);
        return config != null ? config.getGradeCode() : null;
    }

    private static boolean inClosedRange(BigDecimal value, BigDecimal min, BigDecimal max)
    {
        if (min == null || max == null)
        {
            return false;
        }
        return value.compareTo(min) >= 0 && value.compareTo(max) <= 0;
    }
}
