package com.backendsys.modules.system.controller;

import com.backendsys.exception.CustException;
import com.backendsys.modules.common.aspect.SysLog;
import com.backendsys.modules.common.utils.Result;
import com.backendsys.modules.system.entity.SysUserRole;
import com.backendsys.modules.system.service.SysUserRoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
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.Arrays;

@Validated
@RestController
@Tag(name = "系统用户角色")
public class SysUserRoleController {

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Operation(summary = "获取系统用户角色列表")
    @PreAuthorize("@sr.hasPermission('4.1')")
    @GetMapping("/api/system/user/getUserRoleList")
    public Result getUserRoleList(@Validated SysUserRole sysUserRole) {
        return Result.success().put("data", sysUserRoleService.selectUserRoleList(sysUserRole));
    }

    @Operation(summary = "获取系统用户角色详情")
    @PreAuthorize("@sr.hasPermission('4.1.1')")
    @GetMapping("/api/system/user/getUserRoleDetail")
    public Result getUserRoleDetail(@Validated(SysUserRole.Detail.class) SysUserRole sysUserRole) {
        return Result.success().put("data", sysUserRoleService.selectUserRoleDetail(sysUserRole));
    }

    @SysLog("创建系统用户角色")
    @Operation(summary = "创建系统用户角色")
    @PreAuthorize("@sr.hasPermission('4.1.2')")
    @PostMapping("/api/system/user/createUserRole")
    public Result createUserRole(@Validated(SysUserRole.Create.class) @RequestBody SysUserRole sysUserRole) {
        return Result.success().put("data", sysUserRoleService.insertUserRole(sysUserRole));
    }

    @SysLog("更新系统用户角色")
    @Operation(summary = "更新系统用户角色")
    @PreAuthorize("@sr.hasPermission('4.1.3')")
    @PutMapping("/api/system/user/updateUserRole")
    public Result updateUserRole(@Validated(SysUserRole.Update.class) @RequestBody SysUserRole sysUserRole) {
        return Result.success().put("data", sysUserRoleService.updateUserRole(sysUserRole));
    }

    @SysLog("删除系统用户角色")
    @Operation(summary = "删除系统用户角色")
    @PreAuthorize("@sr.hasPermission('4.1.4')")
    @DeleteMapping("/api/system/user/deleteUserRole")
    public Result deleteUserRole(@Validated(SysUserRole.Delete.class) @RequestBody SysUserRole sysUserRole) {
        // 不可删除 角色ID: (1管理员, 2游客)
        if (Arrays.asList(1L, 2L).contains(sysUserRole.getRole_id())) throw new CustException("该角色不可删除");
        return Result.success().put("data", sysUserRoleService.deleteUserRole(sysUserRole));
    }

}
