无关风月
1 天以前 6999d4114eb6d64d0775e2f9ff00572b0e60ee31
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.ruoyi.system.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.ArrayList;
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);
    }
 
    @Override
    public List<Integer> getAllSubDeptIds(String deptId) {
        List<Integer> allSubIds = new ArrayList<>();
        getSubDeptIdsRecursive(Integer.valueOf(deptId), allSubIds);
        return allSubIds.stream().distinct().collect(Collectors.toList());
    }
    private void getSubDeptIdsRecursive(Integer parentId, List<Integer> allSubIds) {
        // 查询直接下级
        List<Integer> directSubIds = this.baseMapper.selectList(new LambdaQueryWrapper<TDept>().eq(TDept::getParentId, parentId)).stream()
                .map(TDept::getId).collect(Collectors.toList());
        for (Integer subId : directSubIds) {
            allSubIds.add(subId);
            // 递归查询下级的下级
            getSubDeptIdsRecursive(subId, allSubIds);
        }
        allSubIds.add(Integer.valueOf(parentId));
 
    }
    /**
     * 构建部门树结构
     * @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());
    }
}