package com.bonus.system.controller;

import java.util.List;

import com.bonus.common.log.annotation.SysLog;
import com.bonus.common.log.enums.OperaType;
import lombok.extern.slf4j.Slf4j;
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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bonus.common.core.constant.UserConstants;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.annotation.RequiresPermissions;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.api.domain.SysDept;
import com.bonus.system.service.ISysDeptService;

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

    /**
     * 获取部门列表
     */
    @RequiresPermissions("system:dept:list")
    @GetMapping("/list")
    @SysLog(title = "部门管理", businessType = OperaType.QUERY,logType = 0,module = "系统管理->部门管理")
    public AjaxResult list(SysDept dept) {
       try{
           List<SysDept> depts = deptService.selectDeptList(dept);
           return success(depts);
       }catch (Exception e){
           log.error(e.toString(),e);
       }
        return error("系统异常");
    }

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

    /**
     * 根据部门编号获取详细信息
     */
    @RequiresPermissions("system:dept:query")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId) {
        try{
            deptService.checkDeptDataScope(deptId);
            return success(deptService.selectDeptById(deptId));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 新增部门
     */
    @RequiresPermissions("system:dept:add")
    @SysLog(title = "部门管理", businessType = OperaType.INSERT,logType = 0,module = "系统管理->部门管理")
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept) {
        try{
            if (!deptService.checkDeptNameUnique(dept)) {
                return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
            }
            dept.setCreateBy(SecurityUtils.getUsername());
            return toAjax(deptService.insertDept(dept));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 修改部门
     */
    @RequiresPermissions("system:dept:edit")
    @PutMapping
    @SysLog(title = "部门管理", businessType = OperaType.UPDATE,logType = 0,module = "系统管理->部门管理")
    public AjaxResult edit(@Validated @RequestBody SysDept dept) {
        try{
            Long deptId = dept.getDeptId();
            deptService.checkDeptDataScope(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));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 删除部门
     */
    @RequiresPermissions("system:dept:remove")
    @DeleteMapping("/{deptId}")
    @SysLog(title = "部门管理", businessType = OperaType.DELETE,logType = 0,module = "系统管理->部门管理")
    public AjaxResult remove(@PathVariable Long deptId) {
        try{
            if (deptService.hasChildByDeptId(deptId)) {
                return warn("存在下级部门,不允许删除");
            }
            if (deptService.checkDeptExistUser(deptId)) {
                return warn("部门存在用户,不允许删除");
            }
            deptService.checkDeptDataScope(deptId);
            return toAjax(deptService.deleteDeptById(deptId));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }
}
