package com.jiayue.center.controller;

import cn.hutool.core.util.NumberUtil;
import com.jiayue.center.annotation.OperateLog;
import com.jiayue.center.annotation.PreventReplay;
import com.jiayue.center.backenum.AuditType;
import com.jiayue.center.backenum.BusinessType;
import com.jiayue.center.constant.CustomException;
import com.jiayue.center.constant.UserConstants;
import com.jiayue.center.entity.SysDept;
import com.jiayue.center.service.SysDeptService;
import com.jiayue.center.util.ResponseVO;
import com.jiayue.center.util.RyStringUtils;
import com.jiayue.center.util.SecurityContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门接口
 *
 * @author xsl
 * @since 2023/03/21
 */
@RestController
@RequestMapping("/sysDeptController")
@Slf4j
public class SysDeptController {

    @Autowired
    private SysDeptService sysDeptService;

    /**
     * 获取菜单列表
     */
    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @OperateLog(title = "部门管理", businessType = BusinessType.QUERY, auditType = AuditType.SYS,operdesc = "查询部门")
    @PreventReplay
    public ResponseVO list(SysDept dept) throws CustomException {
        try {
            if (StringUtils.isNotEmpty(dept.getDeptName())) {
                if (dept.getDeptName().length() > 50) {
                    return ResponseVO.fail("部门名长度不能超过50个字符！");
                }
            }
            List<SysDept> deptList = sysDeptService.selectDeptList(dept);
            return ResponseVO.success(deptList);
        } catch (Exception e) {
            throw new CustomException("获取部门列表异常", e);
        }
    }

    /**
     * 新增菜单
     */
    @PostMapping(value = "/addDept")
    @OperateLog(title = "部门管理", businessType = BusinessType.INSERT, auditType = AuditType.SYS,operdesc = "新增部门")
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @PreventReplay
    public ResponseVO addDept(@RequestBody SysDept dept) throws CustomException {
        try {
            if (RyStringUtils.isEmpty(dept.getDeptName()) || RyStringUtils.isEmpty(dept.getDeptName().trim())) {
                return ResponseVO.fail("部门名称不能为空！");
            } else {
                String deptName = dept.getDeptName().trim();
                if (deptName.length() > 50) {
                    return ResponseVO.fail("部门名长度不能超过50个字符！");
                }
            }

            if (dept.getOrderNum() == null) {
                return ResponseVO.fail("排序不能为空！");
            } else if (!NumberUtil.isInteger(dept.getOrderNum() + "")) {
                return ResponseVO.fail("排序不是整型数值！");
            }

            if (UserConstants.NOT_UNIQUE.equals(sysDeptService.checkDeptNameUnique(dept))) {
                return ResponseVO.fail(dept.getDeptName() + "'失败，部门名称已存在！");
            }

            dept.setCreateBy(SecurityContextUtil.getSysUser().getUsername());
            int bo = sysDeptService.insertDept(dept);
            if (bo == 1) {
                return ResponseVO.success("添加部门成功");
            } else {
                log.error("添加部门失败");
                return ResponseVO.fail("添加部门失败");
            }
        } catch (Exception e) {
            throw new CustomException("添加部门异常", e);
        }
    }

    /**
     * 更新系统参数
     *
     * @param dept 参数
     * @return 执行结果
     */
    @PostMapping(value = "/updateDept")
    @OperateLog(title = "部门管理", businessType = BusinessType.UPDATE, auditType = AuditType.SYS,operdesc = "修改部门")
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @PreventReplay
    public ResponseVO updateDept(@RequestBody SysDept dept) throws CustomException {
        try {
            if (dept.getDeptId() == null) {
                return ResponseVO.fail("主键为空不能修改!");
            }

            String deptName = dept.getDeptName().trim();
            if (RyStringUtils.isEmpty(deptName)) {
                return ResponseVO.fail("部门名称不能为空！");
            } else if (deptName.length() > 50) {
                return ResponseVO.fail("部门名长度不能超过50个字符！");
            }

            if (dept.getOrderNum() == null) {
                return ResponseVO.fail("排序不能为空！");
            } else if (!NumberUtil.isInteger(dept.getOrderNum() + "")) {
                return ResponseVO.fail("排序不是整型数值！");
            }

            if (sysDeptService.selectDeptById(dept.getDeptId()) == null) {
                return ResponseVO.fail("非法访问不能修改！");
            }
            if (UserConstants.NOT_UNIQUE.equals(sysDeptService.checkDeptNameUnique(dept))) {
                return ResponseVO.fail("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在！");
            }

            int bo = sysDeptService.updateDept(dept);
            if (bo == 1) {
                return ResponseVO.success("修改部门成功");
            } else {
                log.error("修改部门失败");
                return ResponseVO.fail("修改部门失败");
            }
        } catch (Exception e) {
            throw new CustomException("修改部门异常", e);
        }
    }

    /**
     * 删除菜单信息
     */
    @PostMapping(value = "delDept")
    @OperateLog(title = "部门管理", businessType = BusinessType.DELETE, auditType = AuditType.SYS,operdesc = "删除部门")
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @PreventReplay
    public ResponseVO delDept(String deptId) throws CustomException {
        try {
            if (StringUtils.isEmpty(deptId)) {
                return ResponseVO.fail("删除部门的id不能为空!");
            }
            if (sysDeptService.hasChildByDeptId(Long.parseLong(deptId))) {
                return ResponseVO.fail("存在子部门,不允许删除");
            }

            int bo = sysDeptService.deleteDeptById(Long.parseLong(deptId));
            if (bo == 1) {
                return ResponseVO.success("删除部门成功");
            } else {
                log.error("删除部门失败");
                return ResponseVO.fail("删除部门失败");
            }
        } catch (Exception e) {
            throw new CustomException("删除部门异常", e);
        }
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @GetMapping(value = "/{getDetailInfo}")
    @OperateLog(title = "部门管理", businessType = BusinessType.QUERY, auditType = AuditType.SYS,operdesc = "获取部门详细信息")
    @PreventReplay
    public ResponseVO getDetailInfo(String deptId) throws CustomException {
        try {
            Long menuid;
            if (StringUtils.isNotEmpty(deptId)) {
                if (NumberUtil.isLong(deptId)){
                    menuid = Long.parseLong(deptId);
                }
                else{
                    return ResponseVO.fail("部门id不是类型不对！");
                }
            }
            else{
                return ResponseVO.fail("部门id不能为空！");
            }
            SysDept sysDept = sysDeptService.selectDeptById(menuid);
            return ResponseVO.success(sysDept);
        } catch (Exception e) {
            throw new CustomException("获取部门明细异常", e);
        }
    }

}
