package top.imwork.commons.core.pojo;

import lombok.Data;

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

/**
 * Copyright (C), 2015-2025
 * FileName: BaseTreeNode
 * Author<作者姓名>:   silos
 * CreateTime<创建时间>:   2025/11/1 10:48
 * UpdateTime<修改时间>:   2025/11/1 10:48
 * Description〈功能简述〉: 递归构建 树形结构辅助类
 * History<历史描述>:
 * Since<版本号>: 1.0.0
 */
@Data
public class BaseTreeNode implements Serializable {
    private String id;
    private String pId;
    private Integer state;
    private String icon;
    private String iconClose;
    private String iconOpen;
    private String name;
    private boolean open;
    private boolean isParent;
    private List<BaseTreeNode> children;

    // 构造方法、getter/setter省略...

    public static List<BaseTreeNode> buildTree(List<BaseTreeNode> nodeList) {
        // 创建根节点列表
        List<BaseTreeNode> rootNodes = new ArrayList<>();

        // 使用Map存储所有节点，key为节点ID
        Map<String, BaseTreeNode> nodeMap = nodeList.stream()
                .collect(Collectors.toMap(BaseTreeNode::getId, node -> node));

        // 遍历所有节点，建立父子关系
        for (BaseTreeNode node : nodeList) {
            if (node.getPId() == null || "0".equals(node.getPId())) {
                // 根节点
                rootNodes.add(node);
            } else {
                // 找到父节点
                BaseTreeNode parentNode = nodeMap.get(node.getPId());
                if (parentNode != null) {
                    if (parentNode.getChildren() == null) {
                        parentNode.setChildren(new ArrayList<>());
                    }
                    parentNode.getChildren().add(node);
                }
            }
        }

        return rootNodes;
    }
}