package cn.iocoder.yudao.module.system.controller.admin.dept;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import cn.iocoder.yudao.module.system.controller.admin.dept.vo.dept.DeptListReqVO;
import cn.iocoder.yudao.module.system.controller.admin.dept.vo.dept.DeptRespVO;
import cn.iocoder.yudao.module.system.controller.admin.dept.vo.dept.DeptSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.dept.vo.dept.DeptSimpleRespVO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.validation.Valid;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 部门")
@RestController
@RequestMapping("/system/dept")
@Validated
public class DeptController {

    @Resource
    private DeptService deptService;
    @Autowired
    private WebFrameworkUtils webFrameworkUtils;
    @Autowired
    private AdminUserMapper userMapper;

    @PostMapping("create")
    @Operation(summary = "创建部门")
    @PreAuthorize("@ss.hasPermission('system:dept:create')")
    public CommonResult<Long> createDept(@Valid @RequestBody DeptSaveReqVO createReqVO) {
        Long deptId = deptService.createDept(createReqVO);
        return success(deptId);
    }

    @PutMapping("update")
    @Operation(summary = "更新部门")
    @PreAuthorize("@ss.hasPermission('system:dept:update')")
    public CommonResult<Boolean> updateDept(@Valid @RequestBody DeptSaveReqVO updateReqVO) {
        deptService.updateDept(updateReqVO);
        return success(true);
    }

    @DeleteMapping("delete")
    @Operation(summary = "删除部门")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:dept:delete')")
    public CommonResult<Boolean> deleteDept(@RequestParam("id") Long id) {
        deptService.deleteDept(id);
        return success(true);
    }

    @GetMapping("/list")
    @Operation(summary = "获取部门列表")
    @PreAuthorize("@ss.hasPermission('system:dept:query')")
    public CommonResult<List<DeptRespVO>> getDeptList(DeptListReqVO reqVO) {
        List<DeptDO> list = deptService.getDeptList(reqVO);
        return success(BeanUtils.toBean(list, DeptRespVO.class));
    }

    @GetMapping("/companyLevelDepts")
    @Operation(summary = "获取公司层级的部门", description = "查询公司层级的部门列表")
    @PermitAll
    public CommonResult<List<DeptSimpleRespVO>> companyLevelDepts() {
        List<DeptDO> list = deptService.companyLevelDepts(
                new DeptListReqVO().setStatus(CommonStatusEnum.ENABLE.getStatus()));
        return success(BeanUtils.toBean(list, DeptSimpleRespVO.class));
    }

    @GetMapping("/companyLevelChildrenDepts")
    @Operation(summary = "获取公司层级的部门 及所有子部门", description = "查询公司层级的部门及所有子部门列表")
    @PermitAll
    public CommonResult<List<DeptSimpleRespVO>> companyLevelChildrenDepts() {
        List<DeptDO> list = deptService.companyLevelChildrenDepts(
                new DeptListReqVO().setStatus(CommonStatusEnum.ENABLE.getStatus()));
        return success(BeanUtils.toBean(list, DeptSimpleRespVO.class));
    }

    @GetMapping(value = {"/list-all-simple", "/simple-list"})
    @Operation(summary = "获取部门精简信息列表", description = "只包含被开启的部门，主要用于前端的下拉选项")
    @PermitAll
    public CommonResult<List<DeptSimpleRespVO>> getSimpleDeptList() {
        List<DeptDO> list = deptService.getDeptList(
                new DeptListReqVO().setStatus(CommonStatusEnum.ENABLE.getStatus()));
        return success(BeanUtils.toBean(list, DeptSimpleRespVO.class));
    }

    @GetMapping(value = {"/includeDisabledCompanies", "/includeDisabledCompanies"})
    @Operation(summary = "包含关闭的部门 线上运营会议", description = "包含关闭的部门 线上运营会议")
    @PermitAll
    public CommonResult<List<DeptSimpleRespVO>> includeDisabledCompanies() {
        List<DeptDO> list = deptService.getDeptList(new DeptListReqVO());
        return success(BeanUtils.toBean(list, DeptSimpleRespVO.class));
    }

    @GetMapping("/specifiedSimpleDepts")
    @Operation(summary = "获取指定部门精简信息列表", description = "只包含被开启的部门，主要用于前端的下拉选项")
    @PermitAll
    @Parameter(name = "deptId", description = "部门id", required = true, example = "1024")
    public CommonResult<List<DeptSimpleRespVO>> specifiedSimpleDepts(@RequestParam("deptId") Long deptId) {
        DeptListReqVO reqVO = new DeptListReqVO();
        reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
        reqVO.setDeptId(deptId);
        // 过滤掉数据权限 队伍可以查询上级部门信息
        List<DeptDO> list = deptService.getChildDeptList(deptId);
        // 查询当前用户所属部门 可能是队伍 list 查询结果为0
        if (CollUtil.isEmpty(list)) {
            Long userId = webFrameworkUtils.getLoginUserId();
            if (ObjUtil.isNotEmpty(userId)) {
                // 查询当前登录人所属部门
                AdminUserDO user = userMapper.selectById(userId);
                if (ObjUtil.isNotEmpty(user)) {
                    deptId = user.getDeptId();
                }
            }
        }
        // 查询 deptId 对应的部门 加入 最终返回的集合
        DeptDO currentDept = deptService.getDept(deptId);
        list.add(currentDept);
        return success(BeanUtils.toBean(list, DeptSimpleRespVO.class));
    }

    @GetMapping("/get")
    @Operation(summary = "获得部门信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:dept:query')")
    public CommonResult<DeptRespVO> getDept(@RequestParam("id") Long id) {
        DeptDO dept = deptService.getDept(id);
        return success(BeanUtils.toBean(dept, DeptRespVO.class));
    }

}
