import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.kang.dto.DeptLevelDto;
import com.kang.mapper.SysDeptMapper;
import com.kang.model.SysDept;
import com.kang.utils.LevelUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;
/**
* 计算部门树形结构
*/
@Service
public class SysTreeService {
@Resource
private SysDeptMapper deptMapper;
public List<DeptLevelDto> deptTree(){
//1.查询所有部门
List<SysDept> deptList = deptMapper.selectAll();
//2.创建dto集合
List<DeptLevelDto> dtoList = new ArrayList();
//3.将所有部门集合转化为Dto集合
for (SysDept dept : deptList) {
dtoList.add(DeptLevelDto.adapt(dept));
}
//4.创建方法组装tree
return deptDtoList2Tree(dtoList);
}
private List<DeptLevelDto> deptDtoList2Tree(List<DeptLevelDto> deptDtoList){
//1.判断非空
if (CollectionUtils.isEmpty(deptDtoList)){
return Lists.newArrayList();
}
Multimap<String, DeptLevelDto> levelDeptMap = ArrayListMultimap.create();
List<DeptLevelDto> rootList = new ArrayList();
for (DeptLevelDto dto : deptDtoList) {
//2.将所有节点拿出来存到一个Multimap中,key是level
levelDeptMap.put(dto.getLevel(), dto);
//3.将根节点拿出来存到一个新的List<DeptLevelDto>中
if (dto.getLevel().equals(LevelUtils.ROOT)){
rootList.add(dto);
}
}
//4.按照seq排序rootList
Collections.sort(rootList, new Comparator<DeptLevelDto>() {
@Override
public int compare(DeptLevelDto o1, DeptLevelDto o2) {
return o1.getSeq()-o2.getSeq();
}
});
//5.递归生成树
transFormDeptTree(rootList,LevelUtils.ROOT,levelDeptMap);
return rootList;
}
private void transFormDeptTree(List<DeptLevelDto> deptLevelList,String level,Multimap<String, DeptLevelDto> levelDeptMap){
//1.遍历当前层级数据
for (DeptLevelDto dto : deptLevelList) {
//2.获取下一层的lever
String nextLevel = LevelUtils.getLevel(dto.getId(), level);
//3.通过下一层的lever从map里拿数据
List<DeptLevelDto> nextDeptList = (List<DeptLevelDto>) levelDeptMap.get(nextLevel);
//4.如果nextDeptList不为空就进行处理
if (CollectionUtils.isNotEmpty(nextDeptList)){
//4.将nextDeptList排序
Collections.sort(nextDeptList, new Comparator<DeptLevelDto>() {
@Override
public int compare(DeptLevelDto o1, DeptLevelDto o2) {
return o1.getSeq()-o2.getSeq();
}
});
//5.组装到rootTree
dto.setDeptList(nextDeptList);
//6.进行下一层迭代
transFormDeptTree(nextDeptList,nextLevel,levelDeptMap);
}
}
}
}
工具类:LevelUtils
import org.apache.commons.lang3.StringUtils;
public class LevelUtils {
public final static String ROOT = "0";
public final static String SEPARATOR = ".";
public static String getLevel(Integer parentId , String parentLevel){
//如果parentId==0或为空,这返回ROOT
if (parentId==null || parentId==0 ){
return ROOT;
}
//否则返回parentLevel.parentId
return StringUtils.join(parentLevel,SEPARATOR,parentId);
}
}