package cn.base.util;

import cn.im.ptxztree.model.PtxzsNode;

import java.util.ArrayList;
import java.util.List;

public class TreeUtil {

    public static List<PtxzsNode> toTree(List<PtxzsNode> list) {
        List<PtxzsNode> treeList = new ArrayList<PtxzsNode>();
        for (PtxzsNode tree : list) {
            if (tree.getPid().equalsIgnoreCase("-1")) {
                treeList.add(tree);
            }
        }
        for (PtxzsNode tree : list) {
            toTreeChildren(treeList, tree);
        }
        return treeList;
    }

     public static void  toTreeChildren(List<PtxzsNode> treeList, PtxzsNode tree) {
        for (PtxzsNode node : treeList) {
            if(tree.getPid().equalsIgnoreCase(node.getId())){
                if(node.getChildren() == null){
                    node.setChildren(new ArrayList<PtxzsNode>());
                }
                node.getChildren().add(tree);
            }
            if(node.getChildren() != null){
                toTreeChildren(node.getChildren(),tree);
            }
        }
    }

    /**
     * 使用递归方法建树
     * @param treeNodes
     * @return
     */
    public static List<PtxzsNode> buildByRecursive(List<PtxzsNode> treeNodes) {
        List<PtxzsNode> trees = new ArrayList<PtxzsNode>();
        for (PtxzsNode treeNode : treeNodes) {
            if ("-1".equals(treeNode.getPid())) {
                trees.add(findChildren(treeNode,treeNodes));
            }
        }
        return trees;

    }


    /**
     * 使用递归方法建combo树
     * @param treeNodes
     * @return
     */
    public static List<PtxzsNode> buildComboTreeByRecursive(List<PtxzsNode> treeNodes) {
        List<PtxzsNode> trees = new ArrayList<PtxzsNode>();
        for (PtxzsNode treeNode : treeNodes) {
            if ("-1".equals(treeNode.getPid())) {
                trees.add(findChildren(treeNode,treeNodes));
            }
        }
        return trees;

    }

    /**
     * 递归查找子节点
     * @param treeNodes
     * @return
     */
    public static PtxzsNode findChildren(PtxzsNode treeNode,List<PtxzsNode> treeNodes) {
        for (PtxzsNode it : treeNodes) {
            if(treeNode.getId().equals(it.getPid())) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<PtxzsNode>());
                }
                treeNode.getChildren().add(findChildren(it,treeNodes));
            }
        }
        return treeNode;
    }








}
