package com.usky.system.controller.web;


import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.exception.BusinessErrorCode;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.system.domain.SysRole;
import com.usky.system.domain.constants.UserConstants;
import com.usky.system.service.ISysRoleService;
import com.usky.system.service.SysMobileRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

/**
 * <p>
 * 移动端_角色和菜单关联表 前端控制器
 * </p>
 *
 * @author JCB
 * @since 2023-03-02
 */
@RestController
@RequestMapping("/sysMobileRoleMenu")
public class SysMobileRoleMenuController  extends BaseController{

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private SysMobileRoleMenuService mobileRoleMenuService;

    /**
     * 新增角色
     */
    @PostMapping
    public ApiResult add(@Validated @RequestBody SysRole role)
    {
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setTenantId(SecurityUtils.getTenantId());
        role.setCreateBy(SecurityUtils.getUsername());
        return toAjax(mobileRoleMenuService.insertRole(role));

    }

    /**
     * 修改保存角色
     */
    @PutMapping
    public ApiResult edit(@Validated @RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(mobileRoleMenuService.updateRole(role));
    }


}

