package com.yunfeiyun.agmp.common.web.system.controller;

import com.yunfeiyun.agmp.common.constant.ErrorCode;
import com.yunfeiyun.agmp.common.constant.UserConstants;
import com.yunfeiyun.agmp.common.annotation.Log;
import com.yunfeiyun.agmp.common.core.controller.BaseController;
import com.yunfeiyun.agmp.common.core.domain.AjaxResult;
import com.yunfeiyun.agmp.common.core.domain.entity.SysDept;
import com.yunfeiyun.agmp.common.enums.BusinessType;
import com.yunfeiyun.agmp.common.utils.DateUtils;
import com.yunfeiyun.agmp.common.utils.StringUtils;
import com.yunfeiyun.agmp.common.web.system.service.ISysDeptService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

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

//    @Autowired
//    private ISysSyncService sysSyncService;
    /**
     * 获取部门列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public AjaxResult list(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return success(depts);
    }

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

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping("/info")
    public AjaxResult getInfo(String deptId)
    {
        deptService.checkDeptDataScope(deptId);
        return success(deptService.selectDeptById(deptId));
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody SysDept dept)
    {
        if (!deptService.checkDeptNameUnique(dept))
        {
            return error(ErrorCode.ADD_DUPLICATE_ERROR.getCode());
        }
        dept.setDeptCreator(getUserId());
        dept.setDeptCreateddate(DateUtils.dateTimeNow());
        //sysSyncService.syncDept( dept , AmqpConstant.cmdAdd);
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PostMapping("edit")
    public AjaxResult edit(@Validated @RequestBody SysDept dept)
    {
        String deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept))
        {
            return error(ErrorCode.ADD_DUPLICATE_ERROR.getCode());
        }
        else if (dept.getDeptParentid().equals(deptId))
        {
            return error(ErrorCode.ADD_PARENT_ERROR.getCode());
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getDeptDelstatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0)
        {
            return error(ErrorCode.ADD_DEACTIVATED_ERROR.getCode());
        }
        dept.setDeptModifier(getLoginname());
        dept.setDeptModifieddate(DateUtils.dateTimeNow());
        //sysSyncService.syncDept( dept , AmqpConstant.cmdUpdate);
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{deptId}")
    public AjaxResult remove(@PathVariable String deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return error(ErrorCode.ADD_EXISTCHILD_ERROR.getCode());
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return error(ErrorCode.ADD_EXISTRELNODE_ERROR.getCode());

        }
        deptService.checkDeptDataScope(deptId);
        //sysSyncService.syncDept( deptId , AmqpConstant.cmdDelete);
        return toAjax(deptService.deleteDeptById(deptId));
    }
}
