package com.yeejoin.amos.iec104.core.util;

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

import com.yeejoin.amos.iec104.core.common.datastructure.TreeNode;

/**
 * 
 * <pre>
 * 树相关操作
 * </pre>
 *
 * @author as-chenjiajun
 * @version $Id: TreeUtil.java, v 0.1 2018年3月8日 下午5:37:36 as-chenjiajun Exp $
 */
public class TreeUtil
{
	/**
	 * 
	 * <pre>
	 * 两层循环实现建树
	 * </pre>
	 *
	 * @param treeNodes 传入的树节点列表
	 * @return
	 */
	public static List<TreeNode> bulid(List<TreeNode> treeNodes)
	{
		List<TreeNode> trees = new ArrayList<TreeNode>();
		for (TreeNode treeNode : treeNodes)
		{
			if ("0".equals(treeNode.getParentKey()))
			{
				trees.add(treeNode);
			}
			for (TreeNode it : treeNodes)
			{
				if (it.getParentKey() == treeNode.getKey())
				{
					if (treeNode.getChildren() == null)
					{
						treeNode.setChildren(new ArrayList<TreeNode>());
					}
					treeNode.getChildren().add(it);
				}
			}
		}
		return trees;
	}

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

	/**
	 * 
	 * <pre>
	 * 递归查找子节点
	 * </pre>
	 *
	 * @param treeNode
	 * @param treeNodes
	 * @return
	 */
	public static TreeNode findChildren(TreeNode treeNode,
			List<TreeNode> treeNodes)
	{
		for (TreeNode it : treeNodes)
		{
			if (treeNode.getKey().equals(it.getParentKey()))
			{
				if (treeNode.getChildren() == null)
				{
					treeNode.setChildren(new ArrayList<TreeNode>());
				}
				treeNode.getChildren().add(findChildren(it, treeNodes));
			}
		}
		return treeNode;
	}
	
	/**
	 * 
	 * <pre>
	 * 搜索树
	 * </pre>
	 *
	 * @param treeNodes
	 * @param keyList 所有key值
	 * @return
	 */
	public static List<String> deepSearch(List<TreeNode> treeNodes,List<String> keyList)
	{
		List<String> currentList = new ArrayList<String>();
		for (TreeNode treeNode : treeNodes)
		{
			currentList.add(treeNode.getKey());
			if (treeNode.getChildren() != null)
			{
				currentList.addAll(deepSearch(treeNode.getChildren(),keyList));
			}
		}
		return currentList;
	}
}
