package com.xunmei.system.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xunmei.common.core.constant.Constants;
import com.xunmei.common.core.domain.R;
import com.xunmei.common.core.utils.StringUtils;
import com.xunmei.common.core.web.controller.BaseController;
import com.xunmei.common.core.web.domain.AjaxResult;
import com.xunmei.common.core.web.page.TableDataInfo;
import com.xunmei.common.log.annotation.Log;
import com.xunmei.common.log.enums.BusinessType;
import com.xunmei.common.security.annotation.InnerAuth;
import com.xunmei.common.security.annotation.RequiresPermissions;
import com.xunmei.common.security.utils.SecurityUtils;
import com.xunmei.system.api.Eto.OrgListByTypesConditionEto;
import com.xunmei.system.api.domain.SysDept;
import com.xunmei.system.api.domain.SysOrg;
import com.xunmei.system.api.domain.SysUser;
import com.xunmei.system.service.ISysDeptService;
import com.xunmei.system.service.ISysOrgService;
import com.xunmei.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
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.Comparator;
import java.util.Date;
import java.util.List;

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

    /**
     * 获取部门列表
     */
    @RequiresPermissions("system:dept:list")
    @GetMapping("/list")
    public TableDataInfo<SysOrg> list(SysOrg dept) {
        return orgService.selectPage(dept);
    }

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

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

    /**
     * 新增部门
     */
    @RequiresPermissions("system:dept:add")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysOrg dept) {
        if (orgService.list(new QueryWrapper<SysOrg>().eq("name", dept.getName())).size() > 0) {
            return error("新增部门'" + dept.getName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getUsername());
        dept.setCreateTime(new Date());

        return toAjax(orgService.saveOrUpdateOrg(dept));
    }

    /**
     * 修改部门
     */
    @RequiresPermissions("system:dept:edit")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysOrg dept) {
        Long deptId = dept.getId();
//        deptService.checkDeptDataScope(deptId);
        if (orgService.list(new QueryWrapper<SysOrg>().eq("name", dept.getName()).eq("deleted", 0L)).size() > 1) {
            return error("修改部门'" + dept.getName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return error("修改部门'" + dept.getName() + "'失败，上级部门不能是自己");
        }
//        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getIsLock()) && deptService.selectNormalChildrenDeptById(deptId) > 0)
//        {
//            return error("该部门包含未停用的子部门！");
//        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        dept.setUpdateTime(new Date());
        return toAjax(orgService.saveOrUpdateOrg(dept));
    }

    /**
     * 删除部门
     */
    @RequiresPermissions("system:dept:remove")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId) {
        if (orgService.list(new QueryWrapper<SysOrg>().eq("parent_id", deptId).eq("deleted", 0L)).size() > 0) {
            return warn("存在下级部门,不允许删除");
        }
        if (userService.list(new QueryWrapper<SysUser>().eq("org_id", deptId).eq("deleted", 0L)).size() > 0) {
            return warn("部门存在用户,不允许删除");
        }
//        deptService.checkDeptDataScope(deptId);
        return toAjax(orgService.removeOrg(deptId));
    }

    /**
     * 获取部门树列表(机构)
     */
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysOrg dept) {
        return success(deptService.selectDeptTreeList(dept));
    }

    /**
     * @param dept
     * @return 获取部门树（真部门）
     */
    @GetMapping("/sysDeptTree")
    public AjaxResult sysDeptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }

    @GetMapping("/selectCheckSubOrgIdList")
    public List<Long> selectCheckSubOrgIdList(Long orgId) {
        return orgService.selectCheckSubOrgIdList(orgId);
    }

    @GetMapping("/selectSysOrgById")
    public SysOrg selectSysOrgById(Long id) {
        return orgService.getById(id);
    }

    @GetMapping("/listByIds")
    public R<List<SysOrg>> listByIds(List<Long> ids) {
        return R.ok(orgService.listByIds(ids));
    }

    @GetMapping("/findListByOrgType")
    public R<List<Long>> findListByOrgType(Integer execOrgType) {
        return R.ok(orgService.findListByOrgType(execOrgType));
    }

    @PostMapping("/findListByOrgTypes")
    public R<List<SysOrg>> listByTypes(@RequestBody OrgListByTypesConditionEto eto) {
        return R.ok(orgService.listByTypes(eto.getOrgId(), eto.getOrgTypes()));
    }

    /**
     * 获取顶级机构
     *
     * @return
     */
    @GetMapping("/top")
    @InnerAuth
    public SysOrg selectSysOrgById() {
        return orgService.selectByParentId(Constants.TOP_ORG_PARENT_ID);
    }

    /**
     * 获取单个机构
     *
     * @return
     */
    @GetMapping("/get/{orgId}")
    @InnerAuth
    public SysOrg selectOrgById(@PathVariable("orgId") Long orgId) {
        return orgService.getById(orgId);
    }


    /**
     * 根据机构类型获取机构数组
     *
     * @return
     */
    @InnerAuth
    @GetMapping("/selectByOrgType/{orgType}")
    List<SysOrg> selectByOrgType(@PathVariable("orgType") Integer orgType) {
        return orgService.selectByOrgType(orgType);
    }

    @ApiOperation(value = "根据id获取机构信息", notes = "根据id获取机构信息")
    @InnerAuth
    @PostMapping("/selectOrgByIdList")
    List<SysOrg> selectOrgByIdList(List<Long> orgList) {
        if (ObjectUtil.isEmpty(orgList)) {
            return new ArrayList<>();
        }
        List<SysOrg> sysOrgs = orgService.listByIds(orgList);
        sysOrgs.sort(Comparator.comparing(SysOrg::getId));
        return sysOrgs;
    }

    @ApiOperation(value = "根据用户id获取机构信息", notes = "根据用户id获取机构信息")
    @InnerAuth
    @GetMapping("/getSysOrgByUserId/{userId}")
    SysOrg getSysOrgByUserId(@PathVariable("userId") Long userId) {
        return orgService.getSysOrgByUserId(userId);
    }
}
