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

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;

/**
 * 变化因素多选编码：去重排序后逗号入库。
 */
public final class ChangeFactorsCodec
{
    private ChangeFactorsCodec()
    {
    }

    public static String encode(List<Integer> codes)
    {
        List<Integer> normalized = normalizeCodes(codes);
        if (normalized.isEmpty())
        {
            throw new ServiceException("请至少选择一项变化因素");
        }
        return normalized.stream().map(String::valueOf).collect(Collectors.joining(","));
    }

    public static List<Integer> parseToList(String stored)
    {
        if (StringUtils.isEmpty(stored))
        {
            return Collections.emptyList();
        }
        String[] parts = stored.split(",");
        List<Integer> out = new ArrayList<>();
        for (String part : parts)
        {
            if (StringUtils.isEmpty(part))
            {
                continue;
            }
            try
            {
                int code = Integer.parseInt(part.trim());
                if (!MarketDailyQuoteRules.isChangeFactorCodeValid(code))
                {
                    throw new ServiceException("变化因素无效");
                }
                out.add(code);
            }
            catch (NumberFormatException ex)
            {
                throw new ServiceException("变化因素无效");
            }
        }
        return out;
    }

    public static List<Integer> normalizeCodes(List<Integer> codes)
    {
        if (codes == null || codes.isEmpty())
        {
            return Collections.emptyList();
        }
        Set<Integer> seen = new LinkedHashSet<>();
        for (Integer code : codes)
        {
            if (code == null)
            {
                continue;
            }
            if (!MarketDailyQuoteRules.isChangeFactorCodeValid(code))
            {
                throw new ServiceException("变化因素无效");
            }
            seen.add(code);
        }
        List<Integer> sorted = new ArrayList<>(seen);
        Collections.sort(sorted);
        return sorted;
    }
}
