package com.gyee.frame.service.stopanalysis;

import com.gyee.frame.model.custom.StopAnalysisNodeVo;
import com.gyee.frame.util.StringUtils;

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


public class StopAnalysisTreeUtil {

	
//	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<StopAnalysisNodeVo> nodes = new ArrayList<StopAnalysisNodeVo>();

	public StopAnalysisTreeUtil(List<StopAnalysisNodeVo> nodes) {

		super();

		this.nodes = nodes;

	}

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

	public List<StopAnalysisNodeVo> buildJSONTree() {

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

		//String json = JSON.toJSONString(nodeTree);

		return nodeTree;

	}

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

	public List<StopAnalysisNodeVo> buildTree() {

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

		List<StopAnalysisNodeVo> rootNodes = getRootNodes();

		for (StopAnalysisNodeVo rootNode : rootNodes) {

			buildChildNodes(rootNode);

			treeNodes.add(rootNode);

		}

		return treeNodes;

	}

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

	public void buildChildNodes(StopAnalysisNodeVo node) {

		List<StopAnalysisNodeVo> children = getChildNodes(node);

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

				buildChildNodes(child);

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

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

	}

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

	public List<StopAnalysisNodeVo> getChildNodes(StopAnalysisNodeVo pnode) {

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

		for (StopAnalysisNodeVo n : nodes) {

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

				childNodes.add(n);
				
			}

		}

		return childNodes;

	}

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

	public boolean rootNode(StopAnalysisNodeVo node) {

		boolean isRootNode = true;

		for (StopAnalysisNodeVo n : nodes) {

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

				isRootNode = false;

				break;

			}

		}

		return isRootNode;

	}

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

	public List<StopAnalysisNodeVo> getRootNodes() {

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

		for (StopAnalysisNodeVo n : nodes) {

			if (rootNode(n)) {

				rootNodes.add(n);
				
			}

		}

		return rootNodes;

	}


}
