package com.example.controller; import com.example.common.Result; import com.example.entity.Department; import com.example.security.UserContext; import com.example.service.DepartmentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/department") public class DepartmentController { @Autowired private DepartmentService departmentService; @GetMapping("/list") public Result> list() { String currentDeptCode = UserContext.getCurrentDeptCode(); return Result.success(departmentService.getDepartmentTreeWithPermission(currentDeptCode)); } @GetMapping("/tree") public Result> tree() { String currentDeptCode = UserContext.getCurrentDeptCode(); return Result.success(departmentService.getDepartmentTreeWithPermission(currentDeptCode)); } @GetMapping("/{id}") public Result getById(@PathVariable Long id) { Department dept = departmentService.getById(id); if (dept == null) { return Result.error("部门不存在"); } String currentDeptCode = UserContext.getCurrentDeptCode(); List deptCodes = departmentService.getChildDeptCodes(currentDeptCode); if (!deptCodes.contains(dept.getDeptCode())) { return Result.error("无权限查看该部门"); } return Result.success(dept); } @PostMapping public Result save(@RequestBody Department department) { String currentDeptCode = UserContext.getCurrentDeptCode(); List deptCodes = departmentService.getChildDeptCodes(currentDeptCode); if (!deptCodes.contains(department.getParentCode())) { return Result.error("无权限在该父部门下创建部门"); } if (departmentService.checkDeptCodeExists(department.getDeptCode())) { return Result.error("部门编码已存在"); } return Result.success(departmentService.save(department)); } @PutMapping public Result update(@RequestBody Department department) { Department existDept = departmentService.getById(department.getId()); if (existDept == null) { return Result.error("部门不存在"); } String currentDeptCode = UserContext.getCurrentDeptCode(); List deptCodes = departmentService.getChildDeptCodes(currentDeptCode); if (!deptCodes.contains(existDept.getDeptCode())) { return Result.error("无权限修改该部门"); } Department checkDept = departmentService.getByDeptCode(department.getDeptCode()); if (checkDept != null && !checkDept.getId().equals(department.getId())) { return Result.error("部门编码已存在"); } return Result.success(departmentService.updateById(department)); } @DeleteMapping("/{id}") public Result delete(@PathVariable Long id) { Department dept = departmentService.getById(id); if (dept == null) { return Result.error("部门不存在"); } String currentDeptCode = UserContext.getCurrentDeptCode(); List deptCodes = departmentService.getChildDeptCodes(currentDeptCode); if (!deptCodes.contains(dept.getDeptCode())) { return Result.error("无权限删除该部门"); } List childCodes = departmentService.getChildDeptCodes(dept.getDeptCode()); if (childCodes.size() > 1) { return Result.error("该部门下存在子部门,无法删除"); } return Result.success(departmentService.removeById(id)); } }