package com.fdkankan.ucenter.util;


import com.fdkankan.ucenter.entity.Folder;

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

public class FolderTreeUtil {

    private List<FolderTree> resultNodes = new ArrayList<FolderTree>();//树形结构排序之后list内容

    private List<FolderTree> nodes = new ArrayList<FolderTree>();
    //传入list参数

    public FolderTreeUtil(List<Folder> nodesList) {//通过构造函数初始化
        for (Folder n : nodesList) {
            FolderTree treeGrid = new FolderTree();
            treeGrid.setId(n.getId());
            treeGrid.setName(n.getName());
//            treeGrid.setIcon(n.getIcon());
            if (n.getParentId() != null) {
                treeGrid.setParentId(n.getParentId());
            }
            nodes.add(treeGrid);
        }
    }


    /**
     * 构建树形结构list
     *
     * @return 返回树形结构List列表
     */
    public List<FolderTree> buildTree() {
        for (FolderTree node : nodes) {
            Long id = node.getParentId();
            if (id == null) {//通过循环一级节点 就可以通过递归获取二级以下节点
                resultNodes.add(node);//添加一级节点
//                node.setLevel(1);
                build(node, node.getLevel());//递归获取二级、三级、。。。节点
            }
        }
        return resultNodes;
    }

    /**
     * 递归循环子节点
     *
     * @param node 当前节点
     */
    private void build(FolderTree node, int level) {
        List<FolderTree> children = getChildren(node);
        if (!children.isEmpty()) {//如果存在子节点
            node.setChildren(children);
//        	level++;
            for (FolderTree child : children) {//将子节点遍历加入返回值中
//        		child.setLevel(level);
                build(child, child.getLevel());
            }
        }
    }

    /**
     * @param node
     * @return 返回
     */
    private List<FolderTree> getChildren(FolderTree node) {
        List<FolderTree> children = new ArrayList<FolderTree>();
        Long id = node.getId();
        for (FolderTree child : nodes) {
            if (child.getParentId() != null && id.longValue() == child.getParentId().longValue()) {//如果id等于父id
                children.add(child);//将该节点加入循环列表中
            }
        }
        return children;
    }

    public List<FolderTree> buildTree(List<Folder> all, List<Folder> in) {
        for (Folder n : all) {
            FolderTree treeGrid = new FolderTree();
            treeGrid.setId(n.getId());
            treeGrid.setName(n.getName());
            for (Folder nin : in) {
                if (nin.getId().equals(n.getId())) {
                    treeGrid.setChecked(true);
                }
            }
            if (n.getParentId() != null) {
                treeGrid.setParentId(n.getParentId());
            }
            nodes.add(treeGrid);
        }
        return buildTree();
    }


}
