package com.usky.system.controller.web;


import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.exception.BusinessErrorCode;
import com.usky.common.core.util.StringUtils;
import com.usky.common.log.annotation.Log;
import com.usky.common.log.enums.BusinessType;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.system.domain.SysDept;
import com.usky.system.domain.SysUser;
import com.usky.system.domain.constants.UserConstants;
import com.usky.system.service.ISysDeptService;
import com.usky.system.service.ISysUserService;
import com.usky.system.service.vo.TreeNode;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * 部门信息
 *
 * @author yq
 */
@RestController
@RequestMapping("/dept")
public class SysDeptController extends BaseController {
    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysUserService iSysUserService;

    /**
     * 获取部门列表
     */
    @GetMapping("/list")
    public ApiResult list(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return ApiResult.success(depts);
    }

    @GetMapping("/deptList")
    public ApiResult deptList(SysDept dept) {
        List<SysDept> depts = deptService.selectDept(dept);
        return ApiResult.success(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @GetMapping("/list/exclude/{deptId}")
    public ApiResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext()) {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) {
                it.remove();
            }
        }
        return ApiResult.success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @GetMapping(value = "/{deptId}")
    public ApiResult getInfo(@PathVariable Long deptId) {
        return ApiResult.success(deptService.selectDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public ApiResult treeselect(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return ApiResult.success(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 获取部门人员下拉树列表
     */
    @GetMapping("/deptUserTreeSelect")
    public ApiResult <List<TreeNode>> treeselect(SysDept dept, SysUser user) {
        List<SysDept> depts = deptService.deptList(dept);
        List<SysUser> users = iSysUserService.selectDUserList(user);
        return ApiResult.success(deptService.buildDeptUserTreeSelect(depts, users));
    }

    /**
     * 部门人员下拉树-工时统计
     */
    @GetMapping("/jurisdictionDeptUserTree")
    public ApiResult <List<TreeNode>> jurisdictionDeptUserTree(SysDept dept, SysUser user) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        List<SysUser> users = iSysUserService.selectUserList(user);
        return ApiResult.success(deptService.buildDeptUserTreeSelect(depts, users));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public ApiResult roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
        return ApiResult.success(ajax);
    }

    /**
     * 新增部门
     */
    @Log(title = "新增-部门", businessType = BusinessType.INSERT)
    @PostMapping
    public ApiResult add(@Validated @RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setTenantId(SecurityUtils.getTenantId());
        dept.setCreateBy(SecurityUtils.getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @Log(title = "修改-部门", businessType = BusinessType.UPDATE)
    @PutMapping
    public ApiResult edit(@Validated @RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(dept.getDeptId())) {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0) {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @Log(title = "删除-部门", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public ApiResult remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "部门存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }
}
