package org.eco.system.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import org.eco.system.domain.bo.SysDeptBo;
import org.eco.common.core.constant.UserConstants;
import org.eco.common.core.core.domain.CommonResult;
import org.eco.common.core.core.text.Convert;
import org.eco.common.core.utils.StringUtils;
import org.eco.common.log.annotation.Log;
import org.eco.common.log.enums.BusinessType;
import org.eco.common.web.core.BaseController;
import org.eco.system.domain.vo.SysDeptVo;
import org.eco.system.service.ISysDeptService;
import org.eco.system.service.ISysUserService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 部门信息
 *
 * @author wgk
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {
    @Resource
    private ISysDeptService deptService;

    @Resource
    private ISysUserService sysUserService;

    /**
     * 获取部门列表
     */
    @SaCheckPermission("system:dept:list")
    @GetMapping("/list")
    public CommonResult<List<SysDeptVo>> list(SysDeptBo deptBo) {
        List<SysDeptVo> deptVos = deptService.selectDeptList(deptBo);
        return CommonResult.success(deptVos);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @SaCheckPermission("system:dept:list")
    @GetMapping("/list/exclude/{deptId}")
    public CommonResult<List<SysDeptVo>> excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDeptVo> deptVos = deptService.selectDeptList(new SysDeptBo());
        deptVos.removeIf(d -> d.getDeptId().equals(deptId) || StringUtils.splitList(d.getAncestors()).contains(Convert.toStr(deptId)));
        return CommonResult.success(deptVos);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @SaCheckPermission("system:dept:query")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @GetMapping(value = "/{deptId}")
    public CommonResult<SysDeptVo> getInfo(@PathVariable Long deptId) {
        deptService.checkDeptDataScope(deptId);
        return CommonResult.success(deptService.selectDeptById(deptId));
    }

    /**
     * 新增部门
     */
    @SaCheckPermission("system:dept:add")
    @PostMapping
    public CommonResult<Void> add(@Validated @RequestBody SysDeptBo dept) {
        if (!deptService.checkDeptNameUnique(dept)) {
            return CommonResult.fail("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        boolean inserted = deptService.insertDept(dept);
        if (!inserted) {
            return CommonResult.fail("新增部门记录失败！");
        }
        return CommonResult.success();
    }

    /**
     * 修改部门
     */
    @SaCheckPermission("system:dept:edit")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public CommonResult<Void> edit(@Validated @RequestBody SysDeptBo dept) {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept)) {
            return CommonResult.fail("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return CommonResult.fail("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())) {
            if (deptService.selectNormalChildrenDeptById(deptId) > 0) {
                return CommonResult.fail("该部门包含未停用的子部门！");
            } else if (sysUserService.checkDeptExistUser(deptId)) {
                return CommonResult.fail("该部门下存在已分配用户，不能禁用!");
            }
        }
        boolean updated = deptService.updateDept(dept);
        if (!updated) {
            return CommonResult.fail("修改部门'" + dept.getDeptName() + "'失败");
        }
        return CommonResult.success();
    }

    /**
     * 删除部门
     */
    @SaCheckPermission("system:dept:remove")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public CommonResult<Void> remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return CommonResult.warn("存在下级部门,不允许删除");
        }
        if (sysUserService.checkDeptExistUser(deptId)) {
            return CommonResult.warn("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        boolean updated = deptService.deleteDeptById(deptId);
        if (!updated) {
            return CommonResult.fail("删除部门失败");
        }
        return CommonResult.success();
    }
}
