mitao
2 天以前 a637bf49486d072ff65771864c50d1586989d940
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.ruoyi.system.service.impl;
 
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.basic.PageInfo;
import com.ruoyi.common.core.domain.entity.TDept;
import com.ruoyi.system.mapper.TDeptMapper;
import com.ruoyi.system.service.TDeptService;
import org.springframework.stereotype.Service;
 
import java.util.List;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 点位管理 服务实现类
 * </p>
 *
 * @author xiaochen
 * @since 2025-05-28
 */
@Service
public class TDeptServiceImpl extends ServiceImpl<TDeptMapper, TDept> implements TDeptService {
 
    /**
     * 获取部门树结构
     * @return 部门树列表
     */
    public List<TDept> selectDeptTreeList() {
        // 查询所有部门
        List<TDept> depts = this.list();
        // 构建树结构
        return buildDeptTree(depts);
    }
 
    /**
     * 构建部门树结构
     * @param depts 部门列表
     * @return 树结构的部门列表
     */
    private List<TDept> buildDeptTree(List<TDept> depts) {
        return depts.stream()
                // 筛选出顶级部门(parentId为null或0的部门)
                .filter(dept -> dept.getParentId() == null || dept.getParentId() == 0)
                // 为每个顶级部门构建子树
                .peek(dept -> dept.setChildren(getChildren(dept, depts)))
                .collect(Collectors.toList());
    }
 
    /**
     * 递归获取部门的子部门
     * @param root 当前部门
     * @param depts 所有部门列表
     * @return 子部门列表
     */
    private List<TDept> getChildren(TDept root, List<TDept> depts) {
        return depts.stream()
                // 筛选出当前部门的直接子部门
                .filter(dept -> dept.getParentId() != null && dept.getParentId().equals(root.getId()))
                // 为每个子部门递归构建其子树
                .peek(dept -> dept.setChildren(getChildren(dept, depts)))
                .collect(Collectors.toList());
    }
}