package com.microservices.system.controller;

import com.microservices.common.core.constant.UserConstants;
import com.microservices.common.core.domain.R;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.core.web.controller.BaseController;
import com.microservices.common.core.web.domain.AjaxResult;
import com.microservices.common.log.annotation.Log;
import com.microservices.common.log.enums.BusinessType;
import com.microservices.common.security.annotation.InnerAuth;
import com.microservices.common.security.annotation.RequiresPermissions;
import com.microservices.common.security.utils.SecurityUtils;
import com.microservices.system.api.domain.SysDept;
import com.microservices.system.service.ISysDeptService;
import io.swagger.annotations.ApiParam;
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.ArrayList;
import java.util.List;

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

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

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

    /**
     * 通过部门Id列表查询部门列表
     */
    @InnerAuth
    @GetMapping("/listInIds/{ids}")
    public R<List<SysDept>> getDeptInDeptIds(@PathVariable("ids") List<Long> ids) {
        List<SysDept> sysDeptList = deptService.selectDeptListInIds(ids);
        if (StringUtils.isNull(sysDeptList)) {
            return R.fail("部门不存在(部门id列表[" + ids + "])");
        }
        return R.ok(sysDeptList);
    }

    /**
     * 通过部门Id获取自身及子部门Id列表
     *
     * @param deptId 部门Id
     * @return 自身及子部门Id列表
     */
    @InnerAuth
    @GetMapping("/getSelfAndChildrenDeptIdListByDeptId/{deptId}")
    public R<List<Long>> getSelfAndChildrenDeptIdListByDeptId(@PathVariable("deptId") Long deptId) {
        List<Long> sysDeptIdList = deptService.getSelfAndChildrenDeptIdListByDeptId(deptId);
        if (StringUtils.isNull(sysDeptIdList)) {
            return R.ok(new ArrayList<>());
        }
        return R.ok(sysDeptIdList);
    }

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


    /**
     * 通过部门Id查询部门信息
     */
    @InnerAuth
    @GetMapping("/getDeptByDeptId/{deptId}")
    public R<SysDept> getDeptByDeptId(@PathVariable("deptId") Long deptId) {
        //todo:需校验权限
//        deptService.checkDeptDataScope(deptId);
        SysDept sysDept = deptService.selectDeptById(deptId);
        if (StringUtils.isNull(sysDept)) {
            return R.fail("该部门不存在(部门id[" + deptId + "])");
        }
        return R.ok(sysDept);
    }

    /**
     * 基于专区名称新增部门-内部接口
     */
    @InnerAuth
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping("/addDeptByZone")
    public R<Long> addDeptByZone(@RequestBody String zoneName) {
        deptService.checkDeptName(zoneName);
        return R.ok(deptService.addDeptByZone(zoneName));
    }

    /**
     * 基于企业名称新增部门-内部接口
     */
    @InnerAuth
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping("/addDeptByPmsEnterprise")
    public R<Long> addDeptByPmsEnterprise(@RequestBody String pmsEnterpriseName) {
        return R.ok(deptService.addDeptByPmsEnterprise(pmsEnterpriseName));
    }

    /**
     * 根据部门Id更新部门名称-内部接口
     */
    @InnerAuth
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping("/updateDeptNameByDeptId/{deptId}")
    public R<Boolean> updateDeptNameByDeptId(@PathVariable("deptId") Long deptId, @RequestBody String deptName) {
        deptService.checkDeptName(deptName);
        return R.ok(deptService.updateDeptNameByDeptId(deptId, deptName));
    }

    /**
     * 基于企业名称删除部门-内部接口
     */
    @InnerAuth
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteDeptByDeptId")
    public R<Boolean> deleteDeptByDeptId(@RequestBody Long deptId) {
        return R.ok(deptService.deleteDeptByDeptId(deptId));
    }
    /**
     * 基于企业名称删除部门-内部接口
     */
    @InnerAuth
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteDeptByPmsEnterprise")
    public R<Boolean> deleteDeptByPmsEnterprise(@RequestBody String pmsEnterpriseName) {
        return R.ok(deptService.deleteDeptByPmsEnterprise(pmsEnterpriseName));
    }

    /**
     * 新增部门
     */
    @RequiresPermissions("system:dept:add")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept) {
        deptService.checkDeptName(dept.getDeptName());
        if (!deptService.checkDeptNameUnique(dept))
        {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        return toAjax(deptService.insertDept(dept));
    }

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

    /**
     * 删除部门
     */
    @RequiresPermissions("system:dept:remove")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        deptService.checkUnchangeableDept(deptId);
        if (deptService.hasChildByDeptId(deptId)) {
            return warn("存在下级部门,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }

    /**
     * 查询组织编号下拥有传入角色权限字符串的用户名
     *
     * @param deptId 组织Id
     * @param roleKeys 角色权限字符串
     * @return 组织下拥有传入角色权限字符串的用户名列表
     */
    @InnerAuth
    @GetMapping("/getGitLinkUserNamesByDeptIdAndRoleKeys/{deptId}/list")
    public R<List<String>> getGitLinkUserNamesByDeptIdAndRoleKeys(@PathVariable Long deptId,
                                                         @ApiParam(name="roleKeys", value = "角色权限字符串", required = true) String roleKeys) {
        List<String> userNameList = deptService.getGitLinkUserNamesByDeptIdAndRoleKeys(deptId, roleKeys);
        if (StringUtils.isNull(userNameList)) {
            return R.ok(new ArrayList<>());
        }
        return R.ok(userNameList);
    }
}
