package com.zy.asrs.common.utils; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.zy.asrs.common.wms.entity.Tag; import com.zy.asrs.common.wms.service.TagService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; import java.util.*; /** * 树形图工具 * Created by vincent on 2020/10/16 */ @Component public class TreeUtils { @Autowired private TagService tagService; /******************************** 归类树 *********************************/ /** * 获取树图数据结构 */ @Cacheable(cacheNames = "tagTree", key = "#id") public ArrayList getTree(Long id, Long hostId) { ArrayList result = new ArrayList<>(); Tag tag = tagService.getOne(new LambdaQueryWrapper().eq(Tag::getId, id).eq(Tag::getHostId, hostId)); // 主节点 Map map = new HashMap<>(); map.put("title", tag.getName()); map.put("id", tag.getId()); map.put("spread", true); List childrens = new ArrayList<>(); map.put("children", childrens); dealTag(tag, childrens); result.add(map); // 开始处理字节点 // deal(tag, childrens); return result; } /** * 递归获取子节点数据 */ public void dealTag(Tag parent, List list) { List tags = tagService.list( new LambdaQueryWrapper() .eq(Tag::getParentId, parent.getId()) .eq(Tag::getStatus, 1)); for (Tag tag : tags) { Map map = new HashMap<>(); map.put("title", tag.getName()); map.put("id", tag.getId()); map.put("spread", true); List childrens = new ArrayList<>(); map.put("children", childrens); dealTag(tag, childrens); list.add(map); } } /** * 递归获取节点以及子节点数据 */ public void getTagIdList(Long id, List nodes) { if (!nodes.contains(id)) { nodes.add(id); } List tags = tagService.list(new LambdaQueryWrapper().eq(Tag::getParentId, id).eq(Tag::getStatus, 1)); for (Tag tag : tags) { if (!nodes.contains(tag.getId())) { nodes.add(tag.getId()); } getTagIdList(tag.getId(), nodes); } } // ------------------------------------------------------------------------------------------------------- /** * 条件筛选 */ @SuppressWarnings("unchecked") public void remove(String condition, List list) { Iterator iterator = list.iterator(); while (iterator.hasNext()) { Map map = iterator.next(); if (map.get("children") != null) { List children = (List) map.get("children"); if (children.size() > 0) { remove(condition, children); } else { if (!String.valueOf(map.get("title")).contains(condition)) { iterator.remove(); } } } } } }