package com.backendsys.modules.common.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TreeUtil {

    /**
     * 构建树型结构
     */
    public static List<Map<String, Object>> buildTree(List<Map<String, Object>> list) {
        // 将原始列表转换为 Map，以便快速查找
        Map<Long, Map<String, Object>> idToMenuMap = list.stream()
                .collect(Collectors.toMap(menu -> (Long) menu.get("id"), menu -> menu));

        // 构建树型结构
        List<Map<String, Object>> treeList = new ArrayList<>();
        for (Map<String, Object> menu : list) {
            Long parentId = (Long) menu.get("parent_id");
            if (parentId == null || parentId == -1) {
                // 如果没有父级，即为根节点，直接添加到树型结构列表中
                treeList.add(menu);
            } else {
                // 如果有父级，找到父级菜单并添加到其 children 列表中
                Map<String, Object> parentMenu = idToMenuMap.get(parentId);
                if (parentMenu != null) {
                    List<Map<String, Object>> children = (List<Map<String, Object>>) parentMenu.get("children");
                    if (children == null) {
                        children = new ArrayList<>();
                        parentMenu.put("children", children);
                    }
                    children.add(menu);
                }
            }
        }

        // 递归构建子级菜单的树型结构
        treeList.forEach(menu -> buildChildrenTree(menu, idToMenuMap));

        return treeList;
    }

    /**
     * 递归构建子级菜单的树型结构
     *
     * @param menu        当前菜单
     * @param idToMenuMap 菜单 ID 到菜单的映射
     */
    private static void buildChildrenTree(Map<String, Object> menu, Map<Long, Map<String, Object>> idToMenuMap) {
        List<Map<String, Object>> children = (List<Map<String, Object>>) menu.get("children");
        if (children != null) {
            for (Map<String, Object> child : children) {
                buildChildrenTree(child, idToMenuMap);
            }
        } else {
            Long id = (Long) menu.get("id");
            List<Map<String, Object>> childList = idToMenuMap.values().stream()
                    .filter(m -> id.equals(m.get("parent_id")))
                    .collect(Collectors.toList());
            if (!childList.isEmpty()) {
                menu.put("children", childList);
                for (Map<String, Object> child : childList) {
                    buildChildrenTree(child, idToMenuMap);
                }
            }
        }
    }

}
