package com.chushang.system.controller;

import com.chushang.common.core.web.AjaxResult;
import com.chushang.common.log.annotation.SysLog;
import com.chushang.common.log.enums.BusinessType;
import com.chushang.security.annotation.RequiresPermissions;
import com.chushang.security.utils.SecurityUtils;
import com.chushang.system.entity.dto.ListDeptDTO;
import com.chushang.system.entity.po.SysDept;
import com.chushang.system.service.ISysDeptService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * @author by zhaowenyuan create 2022/8/22 16:43
 * 部门相关
 */
@RestController
@RequestMapping("/dept")
public class DeptController {

    @Autowired
    ISysDeptService sysDeptService;

    /**
     * 获取部门列表
     */
    @GetMapping("/list")
    @RequiresPermissions("system:dept:list")
    public AjaxResult list(ListDeptDTO listDept)
    {
        return AjaxResult.success(sysDeptService.selectDeptList(listDept));
    }

    /**
     * 查询部门列表（排除节点）
     */
    @RequiresPermissions("system:dept:list")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Integer deptId)
    {
        List<SysDept> deptList = sysDeptService.selectDeptList(new ListDeptDTO());
        deptList.removeIf(d -> Objects.equals(d.getDeptId(), deptId)
                || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return AjaxResult.success(deptList);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @RequiresPermissions("system:dept:query")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        sysDeptService.checkDeptDataScope(deptId);

        return AjaxResult.success(sysDeptService.getById(deptId));

    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/tree")
    public AjaxResult treeSelect(ListDeptDTO listDept)
    {
        List<SysDept> deptList = sysDeptService.selectDeptList(listDept);
        return AjaxResult.success(sysDeptService.buildDeptTreeSelect(deptList));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDept/tree/{roleId}")
    @RequiresPermissions("system:role:query")
    public AjaxResult roleDeptTreeSelect(@PathVariable("roleId") Long roleId)
    {
        List<SysDept> deptList = sysDeptService.selectDeptList(new ListDeptDTO());
        return AjaxResult.success()
                .add("checkedKeys", sysDeptService.selectDeptListByRoleId(roleId))
                .add("depts", sysDeptService.buildDeptTreeSelect(deptList));
    }

    /**
     * 新增部门
     */
    @RequiresPermissions("system:dept:add")
    @SysLog(value = "部门", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody SysDept dept)
    {
        if (sysDeptService.checkDeptNameUnique(dept))
        {
            return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getUsername());

        sysDeptService.add(dept);
        return AjaxResult.success();
    }

    /**
     * 修改部门
     */
    @RequiresPermissions("system:dept:edit")
    @SysLog(value = "部门", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Valid @RequestBody SysDept dept)
    {
        Long deptId = dept.getDeptId();

        sysDeptService.checkDeptDataScope(deptId);

        if (sysDeptService.checkDeptNameUnique(dept))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(deptId))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (dept.getStatus() && sysDeptService.selectNormalChildrenDeptById(deptId) > 0)
        {
            return AjaxResult.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());

        sysDeptService.updateDept(dept);

        return AjaxResult.success();
    }

    /**
     * 删除部门
     */
    @RequiresPermissions("system:dept:remove")
    @SysLog(value = "部门", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        if (sysDeptService.hasChildByDeptId(deptId))
        {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (sysDeptService.checkDeptExistUser(deptId))
        {
            return AjaxResult.error("部门存在用户,不允许删除");
        }
        sysDeptService.checkDeptDataScope(deptId);

        sysDeptService.removeById(deptId);
        return AjaxResult.success();
    }

}
