package com.nantian.cloud.jljc.vo.util;

import com.nantian.cloud.jljc.vo.TreeMultiVo;
import com.nantian.cloud.jljc.vo.TreeVo;
import lombok.experimental.UtilityClass;
import java.util.ArrayList;
import java.util.List;

@UtilityClass
public class TreeVoUtil {

    public static <T extends TreeVo> List<T> findTree(List<T> treeNodes) {
        List<T> trees = new ArrayList<T>();
        for (T treeNode : treeNodes) {
            if ("0".equals(treeNode.getPvalue()) || "".equals(treeNode.getPvalue()) || null == treeNode.getPvalue()) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    public static <T extends TreeVo> T findChildren(T treeNode, List<T> treeNodes) {
        for (T node : treeNodes) {
            if (treeNode.getValue().equals(node.getPvalue())) {
                treeNode.getChildren().add(findChildren(node, treeNodes));
            }
        }
        return treeNode;
    }

    /**
     * 根据根节点id获取树形结构
     */
    public static <T extends TreeMultiVo> List<T> findTreeMultiByRoot(List<T> treeNodes, Integer rootId) {
        List<T> trees = new ArrayList<T>();
        for (T treeNode : treeNodes) {
            if (rootId.equals(treeNode.getId())) {
                trees.add(findMultiChildrenByRoot(treeNode, treeNodes));
            }
        }
        return trees;
    }

    public static <T extends TreeMultiVo> T findMultiChildrenByRoot(T treeNode, List<T> treeNodes) {
        for (T node : treeNodes) {
            if (treeNode.getId() == node.getParentId()) {
                treeNode.getChildren().add(findMultiChildrenByRoot(node, treeNodes));
            }
        }
        return treeNode;
    }
}
