package com.sdtool.common.tool;

import com.sdtool.common.entity.system.Dept;

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

/**
 * Created by xl on 2020-08-07.
 */
public class TreeDeptUtils {
    /**
     * 生成树形菜单
     *
     * @param list
     * @param parentId
     * @return
     */
    public static List<Dept> generateTreeDepts(List<Dept> list, long parentId) {
        List<Dept> returnList = new ArrayList<>();
        for (Dept t : list) {
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    private static void recursionFn(List<Dept> list, Dept t) {
        // 得到子节点列表
        List<Dept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (Dept tChild : childList) {
            if (hasChild(list, tChild)) {
                // 判断是否有子节点
                for (Dept n : childList) {
                    recursionFn(list, n);
                }
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private static List<Dept> getChildList(List<Dept> list, Dept t) {

        List<Dept> tlist = new ArrayList<>();
        Iterator<Dept> it = list.iterator();
        while (it.hasNext()) {
            Dept n = (Dept) it.next();
            if (n.getParentId() == t.getId()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private static boolean hasChild(List<Dept> list, Dept t) {
        return !getChildList(list, t).isEmpty();
    }
}
