package org.springblade.system.tree;

import org.springblade.system.custommenu.entity.CustomMenu;
import org.springblade.system.custommenu.vo.CustomMenuVO;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * *解析树形数据工具类
 */
public class TreeParser {
	/**
	 * * 解析树形数据
	 *
	 * @param topId
	 * @param entityList
	 * @return
	 */
	public static List<Map<String, Object>> getTreeList(Long topId, List<CustomMenuVO> entityList) {
		List<Map<String, Object>> resultList = new ArrayList<>();
		// 获取顶层元素集合
		Long parentId;
		for (CustomMenuVO entity : entityList) {
			parentId = entity.getSysParentId();
			if (parentId == null || topId.equals(parentId)) {
				Map<String, Object> map = new HashMap<>();
				map.put("id", entity.getSysMenuId());
				map.put("parentId", entity.getSysParentId());
				map.put("name", entity.getSysMenuName());
				map.put("customId", entity.getId());
				map.put("customName", entity.getMenuName());
				resultList.add(map);
			}
		}
		// 获取每个顶层元素的子数据集合

		for (Map<String, Object> entity : resultList) {
			entity.put("children", getSubList(Long.parseLong(entity.get("id").toString()), entityList));
		}
		return resultList;
	}

	/**
	 * * 获取子数据集合
	 *
	 * @param id
	 * @param entityList
	 * @return
	 */
	private static List<Map<String, Object>> getSubList(Long id, List<CustomMenuVO> entityList) {
		List<Map<String, Object>> childList = new ArrayList<>();
		Long parentId;
		// 子集的直接子对象
		for (CustomMenuVO entity : entityList) {
			parentId = entity.getSysParentId();
			if (id.equals(parentId)) {
				Map<String, Object> map = new HashMap<>();
				map.put("id", entity.getSysMenuId());
				map.put("parentId", entity.getSysParentId());
				map.put("name", entity.getSysMenuName());
				map.put("customId", entity.getId());
				map.put("customName", entity.getMenuName());
				childList.add(map);
			}
		}
		// 子集的间接子对象
		for (Map<String, Object> entity : childList) {
//			entity.setChildren(getSubList(entity.getSysMenuId(), entityList));
			entity.put("children", getSubList(Long.parseLong(entity.get("id").toString()), entityList));
		}
		// 递归退出条件
		if (childList.size() == 0) {
			return null;
		}
		return childList;
	}


}
