package com.dgtis.dorm.manager.db.util;

import com.google.gson.Gson;

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

public class ListToTreeUtil {

    /**
     * 两层循环实现建树
     *
     * @param treeNodes 传入的树节点列表
     * @return
     */
    public static List<TreeNode> bulid(List<TreeNode> treeNodes) {

        List<TreeNode> trees = new ArrayList<TreeNode>();

        for (TreeNode treeNode : treeNodes) {

            if (treeNode.getParentId() == null) {
                trees.add(treeNode);
            }
            for (TreeNode it : treeNodes) {
                if (it.getParentId() != null && it.getParentId().equals(treeNode.getId())) {
                    if (treeNode.getChildren() == null) {
                        treeNode.setChildren(new ArrayList<>());
                    }
                    treeNode.getChildren().add(it);
                }
            }
        }
        return trees;
    }

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

    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    public static TreeNode findChildren(TreeNode treeNode, List<TreeNode> treeNodes) {
        treeNode.setChildren(new ArrayList<TreeNode>());

        for (TreeNode it : treeNodes) {
            if (it.getParentId() != null && treeNode.getId().equals(it.getParentId())) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<TreeNode>());
                }
                treeNode.getChildren().add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }

    public static void main(String[] args) {
        List<TreeNode> data = new ArrayList<>();

        TreeNode treeNode1 = new TreeNode(1, "河南省", null,1);
        TreeNode treeNode2 = new TreeNode(2, "洛阳市", 1,2);
        TreeNode treeNode3 = new TreeNode(3, "洛龙区", 2,3);
        TreeNode treeNode4 = new TreeNode(4, "新安县", 2,3);
        TreeNode treeNode5 = new TreeNode(5, "许昌市", 1,2);
        TreeNode treeNode6 = new TreeNode(6, "襄城县", 5,3);

        TreeNode treeNode7 = new TreeNode(7, "山东省", null,1);
        TreeNode treeNode8 = new TreeNode(8, "青岛市", 7,2);

        TreeNode treeNode9 = new TreeNode(9, "河北省", null,1);

        data.add(treeNode1);
        data.add(treeNode2);
        data.add(treeNode3);
        data.add(treeNode4);
        data.add(treeNode5);
        data.add(treeNode6);
        data.add(treeNode7);
        data.add(treeNode8);
        data.add(treeNode9);

        List<TreeNode> result = bulid(data);
        System.out.println(new Gson().toJson(result));

    }
}
