package com.bonus.system.controller;

import java.util.ArrayList;
import java.util.List;

import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.web.page.TableDataInfo;
import com.bonus.common.log.annotation.SysLog;
import com.bonus.common.log.enums.OperaType;
import com.bonus.common.security.annotation.InnerAuth;
import com.bonus.common.security.annotation.RequiresPermissionsOrInnerAuth;
import com.bonus.common.security.annotation.RequiresRoles;
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.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
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;

    /**
     * 获取部门列表
     * 根据部门id或上级部门id或部门名或状态（正常或停用）获取部门信息
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @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("系统异常");
    }

    /**
     * 查询部门列表（排除节点）
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @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("系统异常");
    }

    /**
     * 根据部门编号获取详细信息
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @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("系统异常");
    }

    /**
     * 新增部门
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @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("系统异常, " + e.getMessage());
        }
    }

    /**
     * 修改部门
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:dept:edit"))
    @PostMapping("/edit")
    @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("系统异常, " + e.getMessage());
        }
    }

    /**
     * 删除部门
     */
    @RequiresRoles("admin")
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:dept:remove"))
    @PostMapping("/delete/{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("系统异常");
    }

    /**
     * 根据登录用户获取公司详细信息
     */
    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:dept:query"))
    @GetMapping(value = "/company_info")
    public AjaxResult getCompanyInfo() {
        try{
            Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
            return success(deptService.selectDeptById(deptId));
        } catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    @RequiresPermissionsOrInnerAuth(innerAuth = @InnerAuth, requiresPermissions = @RequiresPermissions("system:dept:query"))
    @GetMapping("/deptList")
    @SysLog(title = "获取公司列表", businessType = OperaType.QUERY,logType = 0,module = "系统管理->获取公司列表")
    public TableDataInfo deptList(SysDept dept) {
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            throw new ServiceException("抱歉,您无权查看公司列表!");
        }
        List<SysDept> deptList1 = new ArrayList<>();
        try{
            startPage();
            dept.setCompanyId(SecurityUtils.getLoginUser().getSysUser().getCompanyId());
            deptList1 = deptService.getDeptList(dept);
            List<SysDept> deptList2 = deptService.getCompanyUserCount();
            for (SysDept dept1 : deptList1) {
                for (SysDept dept2 : deptList2) {
                    if (dept1.getDeptId().equals(dept2.getCompanyId())) {
                        dept1.setUserCount(dept2.getUserCount());
                    }
                }
            }
            return getDataTable(deptList1);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(deptList1);
    }

    @PostMapping("/turnOnOff")
    @SysLog(title = "注销或恢复公司", businessType = OperaType.UPDATE,logType = 0,module = "系统管理->注销或恢复公司")
    public AjaxResult turnOnOff(@Validated @RequestBody SysDept dept) {
        try{
            if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
                throw new ServiceException("抱歉,您无权注销或恢复公司!");
            }
            log.info("公司信息{}",dept.getDeptId());
            return toAjax(deptService.turnOnOffDeptById(dept));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

}
