SysOrgServiceImpl.java 2.79 KB
package com.youjia.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.spring.service.impl.ServiceImpl;
import com.youjia.common.constant.CommonConstants;
import com.youjia.system.entity.SysOrg;
import com.youjia.system.mapper.SysOrgMapper;
import com.youjia.system.service.SysOrgService;
import com.youjia.system.vo.TreeNodeVO;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 组织服务实现。
 */
@Service
public class SysOrgServiceImpl extends ServiceImpl<SysOrgMapper, SysOrg> implements SysOrgService {

    @Override
    public List<TreeNodeVO> listOrgTree() {
        List<SysOrg> orgs = this.list(new LambdaQueryWrapper<SysOrg>()
                .eq(SysOrg::getStatus, CommonConstants.STATUS_ENABLED)
                .orderByAsc(SysOrg::getSort)
                .orderByAsc(SysOrg::getOrgId));
        Map<Long, List<SysOrg>> childrenMap = orgs.stream()
                .collect(Collectors.groupingBy(o -> o.getParentId() == null ? 0L : o.getParentId()));
        return buildChildren(0L, childrenMap);
    }

    @Override
    public List<Long> listSelfAndChildOrgIds(Long orgId) {
        if (orgId == null) {
            return new ArrayList<>();
        }
        SysOrg org = getById(orgId);
        if (org == null) {
            return new ArrayList<>();
        }
        List<Long> result = new ArrayList<>();
        result.add(orgId);
        if (StringUtils.hasText(org.getPath())) {
            this.list(new LambdaQueryWrapper<SysOrg>().likeRight(SysOrg::getPath, org.getPath()))
                    .forEach(child -> result.add(child.getOrgId()));
        }
        return result.stream().distinct().collect(Collectors.toList());
    }

    private List<TreeNodeVO> buildChildren(Long parentId, Map<Long, List<SysOrg>> childrenMap) {
        List<SysOrg> children = childrenMap.get(parentId);
        if (children == null || children.isEmpty()) {
            return new ArrayList<>();
        }
        return children.stream()
                .sorted(Comparator.comparing(SysOrg::getSort, Comparator.nullsLast(Integer::compareTo)))
                .map(org -> {
                    TreeNodeVO node = new TreeNodeVO();
                    node.setId(org.getOrgId());
                    node.setParentId(org.getParentId());
                    node.setLabel(org.getOrgName());
                    node.setSort(org.getSort());
                    node.setStatus(org.getStatus());
                    node.setChildren(buildChildren(org.getOrgId(), childrenMap));
                    return node;
                })
                .collect(Collectors.toList());
    }
}