package cn.iocoder.yudao.module.system.api.dept; import cn.hutool.core.util.StrUtil; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.util.object.BeanUtils; import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO; import cn.iocoder.yudao.module.system.controller.admin.dept.vo.dept.DeptListReqVO; import cn.iocoder.yudao.module.system.controller.admin.dept.vo.dept.DeptSaveReqVO; import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO; import cn.iocoder.yudao.module.system.service.dept.DeptService; import org.springframework.stereotype.Service; import jakarta.annotation.Resource; import java.util.Collection; import java.util.List; /** * 部门 API 实现类 * * @author 超级管理员 */ @Service public class DeptApiImpl implements DeptApi { @Resource private DeptService deptService; @Override public DeptRespDTO getDept(Long id) { DeptDO dept = deptService.getDept(id); return BeanUtils.toBean(dept, DeptRespDTO.class); } @Override public List getDeptList(Collection ids) { List depts = deptService.getDeptList(ids); return BeanUtils.toBean(depts, DeptRespDTO.class); } @Override public List getDeptList() { List depts = deptService.getDeptList(new DeptListReqVO()); return BeanUtils.toBean(depts, DeptRespDTO.class); } @Override public void validateDeptList(Collection ids) { deptService.validateDeptList(ids); } @Override public List getChildDeptList(Long id) { List childDeptList = deptService.getChildDeptList(id); return BeanUtils.toBean(childDeptList, DeptRespDTO.class); } @Override public Long getOrCreateDeptByName(String name) { String deptName = StrUtil.trim(name); if (StrUtil.isEmpty(deptName)) { return null; } List depts = getDeptList(); // 1. 已存在:直接复用 for (DeptRespDTO dept : depts) { if (deptName.equals(StrUtil.trim(dept.getName()))) { return dept.getId(); } } // 2. 不存在:补建到根部门下 Long parentId = depts.stream() .filter(dept -> dept.getParentId() == null || dept.getParentId() == 0L) .map(DeptRespDTO::getId) .findFirst() .orElse(0L); DeptSaveReqVO createReqVO = new DeptSaveReqVO(); createReqVO.setName(deptName); createReqVO.setParentId(parentId); createReqVO.setSort(0); createReqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); return deptService.createDept(createReqVO); } }