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

import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.category.domain.BizInformationCategory;
import com.ruoyi.web.modules.category.domain.vo.InformationCategoryTreeVo;

/**
 * 按 parent_code → category_code 组装资讯类别树。
 */
public final class InformationCategoryTreeBuilder
{
    private InformationCategoryTreeBuilder()
    {
    }

    public static List<InformationCategoryTreeVo> build(List<BizInformationCategory> rows)
    {
        if (rows == null || rows.isEmpty())
        {
            return new ArrayList<>();
        }
        Map<String, InformationCategoryTreeVo> nodeMap = new LinkedHashMap<>();
        for (BizInformationCategory row : rows)
        {
            if (row == null || StringUtils.isEmpty(row.getCategoryCode()))
            {
                continue;
            }
            nodeMap.put(row.getCategoryCode(), toNode(row));
        }
        List<InformationCategoryTreeVo> roots = new ArrayList<>();
        for (BizInformationCategory row : rows)
        {
            if (row == null || StringUtils.isEmpty(row.getCategoryCode()))
            {
                continue;
            }
            InformationCategoryTreeVo node = nodeMap.get(row.getCategoryCode());
            String parentCode = normalizeParentCode(row.getParentCode());
            if (parentCode == null || !nodeMap.containsKey(parentCode))
            {
                roots.add(node);
            }
            else
            {
                nodeMap.get(parentCode).getChildren().add(node);
            }
        }
        sortTree(roots);
        return roots;
    }

    private static InformationCategoryTreeVo toNode(BizInformationCategory row)
    {
        InformationCategoryTreeVo node = new InformationCategoryTreeVo();
        node.setCode(row.getCategoryCode());
        node.setName(row.getCategoryName());
        node.setCategoryType(row.getCategoryType());
        node.setModuleId(row.getModuleId());
        return node;
    }

    private static String normalizeParentCode(String parentCode)
    {
        if (StringUtils.isEmpty(parentCode))
        {
            return null;
        }
        return parentCode.trim();
    }

    private static void sortTree(List<InformationCategoryTreeVo> nodes)
    {
        if (nodes == null || nodes.isEmpty())
        {
            return;
        }
        nodes.sort(Comparator.comparing(InformationCategoryTreeVo::getCode, Comparator.nullsLast(String::compareTo)));
        for (InformationCategoryTreeVo node : nodes)
        {
            sortTree(node.getChildren());
        }
    }
}
