package com.gyee.frame.util;

import com.alibaba.fastjson.JSON;
import com.gyee.frame.model.custom.ZtreeNode;

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


public class TreeUtil {

	
//	private final String ROOT="../pages/warningalert/css/zTreeStyle/img/fj.png";
//	private final String PARENT="../pages/warningalert/css/zTreeStyle/img/fu.png";
//	private final String LEAF="../pages/warningalert/css/zTreeStyle/img/zi.png";
	List<ZtreeNode> nodes = new ArrayList<ZtreeNode>();

	public TreeUtil(List<ZtreeNode> nodes) {

		super();

		this.nodes = nodes;

	}

	/**
	 * 构建JSON树形结构
	 * 
	 * @return
	 */

	public String buildJSONTree() {

		List<ZtreeNode> nodeTree = buildTree();
		
		//nodeTree.get(0).setIcon(ROOT);

		String json = JSON.toJSONString(nodeTree);

		return json;

	}

	/**
	 * 构建树形结构
	 * 
	 * @return
	 */

	public List<ZtreeNode> buildTree() {

		List<ZtreeNode> treeNodes = new ArrayList<ZtreeNode>();

		List<ZtreeNode> rootNodes = getRootNodes();

		for (ZtreeNode rootNode : rootNodes) {

			buildChildNodes(rootNode);

			treeNodes.add(rootNode);

		}

		return treeNodes;

	}

	/**
	 * 递归子节点
	 * 
	 * @param node
	 */

	public void buildChildNodes(ZtreeNode node) {

		List<ZtreeNode> children = getChildNodes(node);

		if (!children.isEmpty()) {
			//node.setIcon(PARENT);
			
			for (ZtreeNode child : children) {

				buildChildNodes(child);

			}
			node.setIsParent(true);
			node.setChildren(children);

		}else
		{
			//node.setIcon(LEAF);
		}

	}

	/**
	 * 获取父节点下所有的子节点
	 *
	 * @param pnode
	 * @return
	 */

	public List<ZtreeNode> getChildNodes(ZtreeNode pnode) {

		
		List<ZtreeNode> childNodes = new ArrayList<ZtreeNode>();

		for (ZtreeNode n : nodes) {

			if (pnode.getId().equals(n.getPid())) {

				childNodes.add(n);
				
			}

		}

		return childNodes;

	}

	/**
	 * 判断是否为根节点
	 * 
	 * @return
	 */

	public boolean rootNode(ZtreeNode node) {

		boolean isRootNode = true;

		for (ZtreeNode n : nodes) {

			if (StringUtils.notEmp(node.getPid()) && node.getPid().equals(n.getId())) {

				isRootNode = false;

				break;

			}

		}

		return isRootNode;

	}

	/**
	 * 获取集合中所有的根节点
	 * 
	 * @return
	 */

	public List<ZtreeNode> getRootNodes() {

		List<ZtreeNode> rootNodes = new ArrayList<ZtreeNode>();

		for (ZtreeNode n : nodes) {

			if (rootNode(n)) {

				rootNodes.add(n);
				
			}

		}

		return rootNodes;

	}


}
