package com.sysu.admin.support.system.menu;

import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.sysu.admin.support.tree.MenuTree;
import com.sysu.admin.support.tree.NavigTree;

import java.util.Collections;
import java.util.List;

/**
 * @title TreeUtils
 * @description
 * @author XIE
 * @date 2020年4月24日下午10:03:57
 */
public class SMenuTreeHelper {

    /**
     * 找出子节点
     *
     * @param parentNode
     * @param nodes
     */
    private static void findMenuChildNodes(MenuTree parentNode, List<MenuTree> nodes) {
        List<MenuTree> children = Lists.newArrayList();
        parentNode.setChildren(children);
        for (MenuTree node : nodes) {
            if (Objects.equal(node.getParent(), parentNode.getId())) {
                children.add(node);
                findMenuChildNodes(node, nodes);
            }
        }
        // 对子节点进行排序
        Collections.sort(children);
    }

    /**
     * 找出根节点
     *
     * @param nodes
     * @return
     */
    private static List<MenuTree> findMenuRootNodes(List<MenuTree> nodes) {
        List<MenuTree> rootNodes = Lists.newArrayList();
        for (MenuTree node : nodes) {
            if (-1 == node.getParent()) {
                rootNodes.add(node);
                findMenuChildNodes(node, nodes);
            }
        }
        // 对父节点进行排序
        Collections.sort(rootNodes);
        return rootNodes;
    }

    /**
     * 找出子节点
     *
     * @param parentNode
     * @param nodes
     */
    private static void findNavigChildNodes(NavigTree parentNode, List<NavigTree> nodes) {
        List<NavigTree> children = Lists.newArrayList();
        for (NavigTree node : nodes) {
            if (Objects.equal(node.getParent(), parentNode.getId())) {
                children.add(node);
                findNavigChildNodes(node, nodes);
            }
        }
        if (!children.isEmpty()) {
            parentNode.setList(children);
            // 对子节点进行排序
            Collections.sort(children);
        }
    }

    //

    /**
     * 找出根节点
     *
     * @param nodes
     * @return
     */
    private static List<NavigTree> findNavigRootNodes(List<NavigTree> nodes) {
        List<NavigTree> rootNodes = Lists.newArrayList();
        for (NavigTree node : nodes) {
            if (-1 == node.getParent()) {
                rootNodes.add(node);
                findNavigChildNodes(node, nodes);
            }
        }
        // 对父节点进行排序
        Collections.sort(rootNodes);
        return rootNodes;
    }

    public static List<MenuTree> getMenuTree(List<MenuTree> nodes) {
        return findMenuRootNodes(nodes);
    }

    public static List<NavigTree> getNavigTree(List<NavigTree> nodes) {
        return findNavigRootNodes(nodes);
    }

}
