package com.jiayue.ssi.controller;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiayue.ssi.annotation.InterfaceLimit;

import com.jiayue.ssi.annotation.OperateLog;
import com.jiayue.ssi.annotation.PreventReplay;
import com.jiayue.ssi.backenum.AuditType;
import com.jiayue.ssi.backenum.BusinessType;
import com.jiayue.ssi.constant.CustomException;
import com.jiayue.ssi.constant.UserConstants;
import com.jiayue.ssi.entity.SysParameter;
import com.jiayue.ssi.entity.SysRole;

import com.jiayue.ssi.entity.SysUser;
import com.jiayue.ssi.service.SysRoleService;
import com.jiayue.ssi.util.ResponseVO;
import com.jiayue.ssi.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("/sysRoleController")
@Slf4j
public class SysRoleController {
    @Autowired
    SysRoleService roleService;

    /**
     * 获取参数分页信息
     *
     * @return 参数信息
     */
    @GetMapping(value = "/getAll")
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @PreventReplay
    public ResponseVO getAll(String currentPage, String pageSize, String roleName, String status, String roleKey) throws CustomException {
        try {
            Integer cp;
            if (StringUtils.isNotEmpty(currentPage)) {
                if (NumberUtil.isInteger(currentPage)){
                    cp = Integer.parseInt(currentPage);
                }
                else{
                    return ResponseVO.fail("currentPage不是整数！");
                }
            }
            else{
                return ResponseVO.fail("currentPage不能是空！");
            }

            Integer ps;
            if (StringUtils.isNotEmpty(pageSize)) {
                if (NumberUtil.isInteger(pageSize)){
                    ps = Integer.parseInt(pageSize);
                }
                else{
                    return ResponseVO.fail("pageSize不是整数！");
                }
            }
            else{
                return ResponseVO.fail("pageSize不能是空！");
            }
            if (StringUtils.isNotEmpty(roleName)) {
                if (roleName.length() > 15) {
                    return ResponseVO.fail("角色名称不能超过15个字符！");
                }
            }
            if (StringUtils.isNotEmpty(roleKey)) {
                if (roleKey.length() > 50) {
                    return ResponseVO.fail("角色权限不能超过50个字符！");
                }
            }
            QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(roleName)) {
                wrapper.like("role_name", roleName);
            }
            if (StringUtils.isNotEmpty(status)) {
                wrapper.eq("status", status);
            }
            if (StringUtils.isNotEmpty(roleKey)) {
                wrapper.like("role_key", roleKey);
            }
            wrapper.orderByAsc("role_sort");
            Page<SysRole> result = roleService.page(new Page<>(cp, ps), wrapper);
            return ResponseVO.success(result);
        } catch (Exception e) {
            throw new CustomException("获取角色列表异常", e);
        }
    }

    /**
     * 新增角色
     *
     * @param role 角色
     * @return 执行结果
     */
    @PostMapping(value = "/addRole")
    @OperateLog(title = "角色管理", businessType = BusinessType.INSERT, auditType = AuditType.SYS)
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @PreventReplay
    public ResponseVO addRole(@RequestBody SysRole role) throws CustomException {
        try {
            if (StringUtils.isEmpty(role.getRoleName())) {
                return ResponseVO.fail("角色名称不能为空!");
            } else if (role.getRoleName().length() > 15) {
                return ResponseVO.fail("角色名称不能超过15个字符！");
            }
            if (StringUtils.isEmpty(role.getRoleKey())) {
                return ResponseVO.fail("角色权限不能为空!");
            } else if (role.getRoleKey().length() > 50) {
                return ResponseVO.fail("角色权限不能超过50个字符！");
            } else if ("XTGL".equals(role.getRoleKey()) || "SJGL".equals(role.getRoleKey())) {
                return ResponseVO.fail("内置角色不能再次添加！");
            }
            if (role.getRoleSort() == null) {
                return ResponseVO.fail("角色排序不能为空!");
            }
            if (StringUtils.isEmpty(role.getStatus())) {
                return ResponseVO.fail("角色状态不能为空!");
            }
            if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
                return ResponseVO.fail("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
            }
            if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
                return ResponseVO.fail("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
            }
            role.setCreateBy(SecurityContextUtil.getSysUser().getUsername());
            int i = roleService.insertRole(role);
            if (i > 0) {
                return ResponseVO.success("添加角色成功");
            } else {
                log.error("添加角色失败");
                return ResponseVO.fail("添加角色失败");
            }
        } catch (Exception e) {
            throw new CustomException("添加角色异常", e);
        }
    }

    /**
     * 更新角色
     *
     * @param role 参数
     * @return 执行结果
     */
    @PostMapping(value = "/updateRole")
    @OperateLog(title = "角色管理", businessType = BusinessType.UPDATE, auditType = AuditType.SYS)
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @PreventReplay
    public ResponseVO updateRole(@RequestBody SysRole role) throws CustomException {
        try {
            SysRole existRole = roleService.getById(role.getRoleId());
            if (existRole == null) {
                return ResponseVO.fail("没有角色，不能修改!");
            }
            if (StringUtils.isEmpty(role.getRoleName())) {
                return ResponseVO.fail("角色名称不能为空!");
            } else if (role.getRoleName().length() > 15) {
                return ResponseVO.fail("角色名称不能超过15个字符！");
            }
            if (StringUtils.isEmpty(role.getRoleKey())) {
                return ResponseVO.fail("角色权限不能为空!");
            } else if (role.getRoleKey().length() > 50) {
                return ResponseVO.fail("角色权限不能超过50个字符！");
            } else if ("XTGL".equals(role.getRoleKey()) || "SJGL".equals(role.getRoleKey())) {
                return ResponseVO.fail("内置角色不能修改！");
            }

            if (role.getRoleSort() == null) {
                return ResponseVO.fail("角色排序不能为空!");
            }
            if (StringUtils.isEmpty(role.getStatus())) {
                return ResponseVO.fail("角色状态不能为空!");
            }
            if (!existRole.getRoleName().equals(role.getRoleName())) {
                if (roleService.queryRoleName(role.getRoleName()) != null) {
                    return ResponseVO.fail(role.getRoleName() + "角色名称已存在！");
                }
            }
            if (!existRole.getRoleKey().equals(role.getRoleKey())) {
                if (roleService.queryRoleKey(role.getRoleKey()) != null) {
                    return ResponseVO.fail(role.getRoleKey() + "角色权限已存在！");
                }
            }

            if (roleService.updateRole(role) > 0) {
                return ResponseVO.success("修改角色信息成功");
            } else {
                log.error("修改用户信息失败");
                return ResponseVO.fail("修改角色信息失败");
            }
        } catch (Exception e) {
            throw new CustomException("修改角色信息异常", e);
        }
    }

    /**
     * 根据角色编号获取详细信息
     */
    @GetMapping(value = "getInfo")
    @PreventReplay
    public ResponseVO getInfo(String roleId) throws CustomException {
        try {
            Long roleid;
            if (StringUtils.isNotEmpty(roleId)) {
                if (NumberUtil.isLong(roleId)){
                    roleid = Long.parseLong(roleId);
                }
                else{
                    return ResponseVO.fail("角色id不是类型不对！");
                }
            }
            else{
                return ResponseVO.fail("角色id不能为空！");
            }

            return ResponseVO.success(roleService.selectRoleById(roleid));
        } catch (Exception e) {
            throw new CustomException("角色编号获取异常", e);
        }
    }

    /**
     * 删除角色
     */
    @PostMapping(value = "/delRole")
    @OperateLog(title = "角色管理", businessType = BusinessType.DELETE, auditType = AuditType.SYS)
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @PreventReplay
    public ResponseVO delRole(String roleId) throws CustomException {
        try {
            if (StringUtils.isEmpty(roleId)) {
                return ResponseVO.fail("id不能为空!");
            }
            SysRole existRole = roleService.getById(Long.parseLong(roleId));
            if (existRole == null) {
                return ResponseVO.fail("没有角色，不能修改!");
            }
            else if ("XTGL".equals(existRole.getRoleKey()) || "SJGL".equals(existRole.getRoleKey())){
                return ResponseVO.fail("内置角色不能删除！");
            }

            if (roleService.countUserRoleByRoleId(Long.parseLong(roleId))>0) {
                return ResponseVO.fail("角色已被用户使用,不允许删除");
            }
            int bo = roleService.deleteRoleById(Long.parseLong(roleId));
            if (bo > 0) {
                return ResponseVO.success("删除角色信息成功");
            } else {
                log.error("删除用户信息失败");
                return ResponseVO.fail("删除角色信息失败");
            }
        } catch (Exception e) {
            throw new CustomException("删除角色信息异常", e);
        }
    }

    /**
     * 获取分配角色信息
     *
     * @return
     */
    @GetMapping(value = "/getRoleByType")
    @PreAuthorize("@ss.hasPermi('system:user:role')")
    @PreventReplay
    public ResponseVO getRoleByType(String usertype) throws CustomException {
        try {
            if (StringUtils.isEmpty(usertype)) {
                return ResponseVO.fail("用户类型为空不能获取角色列表！");
            }
            QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
            wrapper.eq("role_type", usertype);
            wrapper.eq("status", "0");
            List<SysRole> result = roleService.list(wrapper);
            return ResponseVO.success(result);
        } catch (Exception e) {
            throw new CustomException("获取分配角色列表异常", e);
        }
    }
}
