com.base4j.mvc.sys.service.impl.SysDeptServiceImpl 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.mapper.SysDeptMapper;
import com.base4j.mvc.sys.service.SysDeptService;
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 SysDeptServiceImpl extends BaseServiceImpl implements SysDeptService {
@Autowired
private SysDeptMapper sysOrgMapper;
@Override
public List selectChildNumListByParentId(long parentId) {
return sysOrgMapper.selectChildNumListByParentId(parentId);
}
@Override
public List selectOrgTree() {
List sysOrgs = sysOrgMapper.selectAllOrgs();
return buildTree(sysOrgs);
}
public List buildTree(List sysOrgs) {
List res = new ArrayList();
List rootOrg = findRootOrg(sysOrgs);
findChildrenResource(sysOrgs, rootOrg);
//构建id为0的虚拟节点
SysDept zeroOrg = new SysDept();
zeroOrg.setId(0L);
zeroOrg.setParentId(-1L);
zeroOrg.setCode("zero");
zeroOrg.setName("组织机构");
zeroOrg.getChildren().addAll(rootOrg);
res.add(zeroOrg);
return res;
}
private List findRootOrg(List orgList) {
List rootOrgList = new ArrayList();
for (SysDept org : orgList) {
if (0 == org.getParentId()) {
rootOrgList.add(org);
}
}
orgList.remove(rootOrgList);
return rootOrgList;
}
public void findChildrenResource(List orgWithoutRoot, List rootList) {
List subList = new ArrayList(); //本轮未查找到归属的节点集合
Iterator iterator = orgWithoutRoot.iterator();
List children = new ArrayList(); //查找到归属的节点集合
while (iterator.hasNext()) {
SysDept resource = iterator.next();
boolean flag = false; //当为真时,表示当前iterator已经被识别为子节点
for (SysDept 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);
}
}
}