package cn.newfeifan.mall.module.distri.service.sharepath.builder;

import cn.newfeifan.mall.module.distri.controller.app.sharepath.vo.TreeNode;
import cn.newfeifan.mall.module.distri.dal.dataobject.sharepath.SharePathDO;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
public class TreeBuilder {
    private Map<Long, List<SharePathDO>> childrenMap = new HashMap<>();

    public TreeNode buildTree(List<SharePathDO> paths) {
        // 初始化childrenMap
        for (SharePathDO path : paths) {
            childrenMap.computeIfAbsent(path.getAncestor(), k -> new ArrayList<>()).add(path);
        }

        // 假设根节点的ancestor为null或特定值，这里以null为例
        return buildTreeNode(null);
    }

    private TreeNode buildTreeNode(Long parentId) {
        List<SharePathDO> children = childrenMap.get(parentId);
        if (children == null) {
            return null;
        }

        TreeNode node = new TreeNode(); // TreeNode是自定义的树节点类，需要包含子节点列表等信息
        List<TreeNode> childNodes = new ArrayList<>();

        for (SharePathDO child : children) {
            TreeNode childNode = buildTreeNode(child.getDescendant());
            if (childNode != null) {
                childNodes.add(childNode);
            }
        }

        node.setChildren(childNodes);
        return node;
    }
}
