com.base4j.mvc.sys.service.impl.SysDictServiceImpl Maven / Gradle / Ivy
package com.base4j.mvc.sys.service.impl;
import com.base4j.mvc.base.service.impl.BaseServiceImpl;
import com.base4j.mvc.sys.entity.SysDept;
import com.base4j.mvc.sys.entity.SysDict;
import com.base4j.mvc.sys.mapper.SysDictMapper;
import com.base4j.mvc.sys.service.SysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
@Service
public class SysDictServiceImpl extends BaseServiceImpl implements SysDictService {
@Autowired
private SysDictMapper sysDictMapper;
@Override
public List selectOrgTree() {
List sysDicts = sysDictMapper.selectAllOrgs();
return buildTree(sysDicts);
}
@Override
public List selectChildNumListByParentId(long parentId, String code) {
return sysDictMapper.selectChildNumListByParentId(parentId,code);
}
public List buildTree(List sysDicts) {
List res = new ArrayList();
List rootDict = findRootOrg(sysDicts);
findChildrenResource(sysDicts, rootDict);
//构建id为0的虚拟节点
SysDict zeroOrg = new SysDict();
zeroOrg.setId(0L);
zeroOrg.setParentId(-1L);
zeroOrg.setCode("zero");
zeroOrg.setName("组织机构");
zeroOrg.getChildren().addAll(rootDict);
res.add(zeroOrg);
return res;
}
private List findRootOrg(List dictList) {
List rootDictList = new ArrayList();
for (SysDict dict : dictList) {
if (0 == dict.getParentId()) {
rootDictList.add(dict);
}
}
dictList.remove(rootDictList);
return rootDictList;
}
public void findChildrenResource(List orgWithoutRoot, List rootList) {
List subList = new ArrayList(); //本轮未查找到归属的节点集合
Iterator iterator = orgWithoutRoot.iterator();
List children = new ArrayList(); //查找到归属的节点集合
while (iterator.hasNext()) {
SysDict resource = iterator.next();
boolean flag = false; //当为真时,表示当前iterator已经被识别为子节点
for (SysDict parent : rootList) {
if (Objects.equals(resource.getParentId(), parent.getId())) {
parent.getChildren().add(resource);
children.add(resource);
flag = true;
}
}
if(!flag) {
subList.add(resource);
}
}
if (subList.size() > 0 && children.size() > 0) {
findChildrenResource(subList, children);
}
}
}