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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.trading.mapper.BizEntryIsolationMapper;
import com.ruoyi.web.modules.trading.mapper.BizIsolationPatrolMapper;
import com.ruoyi.web.modules.trading.mapper.BizMarketEntryEarTagMapper;

/**
 * 市场进栏耳标池：A（入场隔离已结束主表）− B（巡查病死病害）；保存时再剔除他单占用 C。
 */
@Component
public class MarketEntryEarTagResolver
{
    @Autowired
    private BizEntryIsolationMapper bizEntryIsolationMapper;

    @Autowired
    private BizIsolationPatrolMapper bizIsolationPatrolMapper;

    @Autowired
    private BizMarketEntryEarTagMapper bizMarketEntryEarTagMapper;

    /**
     * 供应商可选耳标（/supplierEarTags）：步骤1 按 supplierId 取隔离已结束主表耳标 A；
     * 步骤2 取全部巡查病死耳标 B；返回 A − B。
     */
    public List<String> listSupplierEarTagOptions(Long supplierId)
    {
        if (supplierId == null)
        {
            return Collections.emptyList();
        }
        Set<String> pool = loadPoolA(supplierId);
        pool.removeAll(loadPoolB());
        return toSortedList(pool);
    }

    /**
     * 保存校验可选池：(A − B) − C，编辑时 excludeEntryId 释放本条占用。
     */
    public List<String> listEligible(Long supplierId, Long excludeEntryId)
    {
        if (supplierId == null)
        {
            return Collections.emptyList();
        }
        Set<String> pool = loadPoolA(supplierId);
        pool.removeAll(loadPoolB());
        Set<String> occupied = loadOccupiedEarTags(excludeEntryId);
        List<String> result = new ArrayList<>();
        for (String tag : pool)
        {
            if (StringUtils.isNotEmpty(tag) && !occupied.contains(tag))
            {
                result.add(tag);
            }
        }
        Collections.sort(result);
        return result;
    }

    private static List<String> toSortedList(Set<String> tags)
    {
        List<String> result = new ArrayList<>();
        for (String tag : tags)
        {
            if (StringUtils.isNotEmpty(tag))
            {
                result.add(tag);
            }
        }
        Collections.sort(result);
        return result;
    }

    public Set<String> loadOccupiedEarTags(Long excludeEntryId)
    {
        List<String> rows = bizMarketEntryEarTagMapper.selectOccupiedEarTags(excludeEntryId);
        Set<String> occupied = new LinkedHashSet<>();
        if (rows != null)
        {
            occupied.addAll(rows);
        }
        return occupied;
    }

    private Set<String> loadPoolA(Long supplierId)
    {
        List<String> rows = bizEntryIsolationMapper.selectEndedMainEarTagRowsBySupplier(supplierId);
        return parseEarTagRows(rows);
    }

    private Set<String> loadPoolB()
    {
        List<String> rows = bizIsolationPatrolMapper.selectSickDeadEarTagRows();
        return parseEarTagRows(rows);
    }

    private static Set<String> parseEarTagRows(List<String> rows)
    {
        Set<String> tags = new LinkedHashSet<>();
        if (rows == null)
        {
            return tags;
        }
        for (String raw : rows)
        {
            if (StringUtils.isEmpty(raw))
            {
                continue;
            }
            tags.addAll(EarTagCodec.parse(raw));
        }
        return tags;
    }
}
