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

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

/**
 * 耳标号解析与存储编码。
 */
public final class EarTagCodec
{
    private EarTagCodec()
    {
    }

    public static List<String> parse(String raw)
    {
        if (StringUtils.isEmpty(raw))
        {
            return new ArrayList<>();
        }
        String normalized = raw.replace('，', ',');
        String[] parts = normalized.split(",");
        List<String> tags = new ArrayList<>();
        Set<String> seen = new LinkedHashSet<>();
        for (String part : parts)
        {
            if (part == null)
            {
                continue;
            }
            String tag = part.trim();
            if (tag.isEmpty())
            {
                continue;
            }
            validateSingleTag(tag);
            if (!seen.add(tag))
            {
                throw new ServiceException("存在重复耳标：" + tag);
            }
            tags.add(tag);
        }
        return tags;
    }

    public static List<String> parseList(List<String> earTagList)
    {
        if (earTagList == null || earTagList.isEmpty())
        {
            return new ArrayList<>();
        }
        List<String> tags = new ArrayList<>();
        Set<String> seen = new LinkedHashSet<>();
        for (String item : earTagList)
        {
            if (StringUtils.isEmpty(item))
            {
                continue;
            }
            String tag = item.trim();
            if (tag.isEmpty())
            {
                continue;
            }
            validateSingleTag(tag);
            if (!seen.add(tag))
            {
                throw new ServiceException("存在重复耳标：" + tag);
            }
            tags.add(tag);
        }
        return tags;
    }

    public static List<String> resolveMainTags(String earTags, List<String> earTagList)
    {
        if (earTagList != null && !earTagList.isEmpty())
        {
            return parseList(earTagList);
        }
        return parse(earTags);
    }

    public static String encode(List<String> tags)
    {
        if (tags == null || tags.isEmpty())
        {
            return "";
        }
        return String.join(",", tags);
    }

    private static void validateSingleTag(String tag)
    {
        int len = tag.length();
        if (len < EntryIsolationRules.MIN_EAR_TAG_LEN || len > EntryIsolationRules.MAX_EAR_TAG_LEN)
        {
            throw new ServiceException("耳标号格式不正确");
        }
    }
}
