package com.gxwebsoft.common.system.controller;

import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserRoleService;
import com.gxwebsoft.common.system.entity.UserRole;
import com.gxwebsoft.common.system.param.UserRoleParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户角色控制器
 *
 * @author 科技小王子
 * @since 2025-06-16 20:39:53
 */
@Tag(name = "用户角色管理")
@RestController
@RequestMapping("/api/system/user-role")
public class UserRoleController extends BaseController {
  @Resource
  private UserRoleService userRoleService;

  @Operation(summary = "查询角色下的用户")
  @GetMapping("/user-list-in-role/{id}")
  public ApiResult<List<UserRole>> userListInRole(@PathVariable Integer id) {
    return success(userRoleService.listByRoleId(id));
  }

  @Operation(summary = "分页查询用户角色")
  @GetMapping("/page")
  public ApiResult<PageResult<UserRole>> page(UserRoleParam param) {
    // 使用关联查询
    return success(userRoleService.pageRel(param));
  }

  @Operation(summary = "查询全部用户角色")
  @GetMapping()
  public ApiResult<List<UserRole>> list(UserRoleParam param) {
    // 使用关联查询
    return success(userRoleService.listRel(param));
  }


  @Operation(summary = "根据id查询用户角色")
  @GetMapping("/{id}")
  public ApiResult<UserRole> get(@PathVariable("id") Integer id) {
    // 使用关联查询
    return success(userRoleService.getByIdRel(id));
  }

  @PreAuthorize("hasAuthority('sys:userRole:save')")
  @OperationLog
  @Operation(summary = "添加用户角色")
  @PostMapping()
  public ApiResult<?> save(@RequestBody UserRole userRole) {
    // 记录当前登录用户id（请求体未指定 userId 时，回退到当前登录用户）
    User loginUser = getLoginUser();
    if (userRole.getUserId() == null && loginUser != null) {
      userRole.setUserId(loginUser.getUserId());
    }
    if (userRoleService.save(userRole)) {
      return success("添加成功");
    }
    return fail("添加失败");
  }

  @Operation(summary = "修改用户角色")
  @PutMapping()
  public ApiResult<?> update(@RequestBody UserRole userRole) {
    final User loginUser = getLoginUser();
    if (loginUser == null) {
      return fail("请先登录");
    }
    if (userRoleService.updateById(userRole)) {
      return success("修改成功");
    }
    return fail("修改失败");
  }

  @PreAuthorize("hasAuthority('sys:userRole:remove')")
  @OperationLog
  @Operation(summary = "删除用户角色")
  @DeleteMapping("/{id}")
  public ApiResult<?> remove(@PathVariable("id") Integer id) {
    if (userRoleService.removeById(id)) {
      return success("删除成功");
    }
    return fail("删除失败");
  }

  @PreAuthorize("hasAuthority('sys:userRole:save')")
  @OperationLog
  @Operation(summary = "批量添加用户角色")
  @PostMapping("/batch")
  public ApiResult<?> saveBatch(@RequestBody List<UserRole> list) {
    if (userRoleService.saveBatch(list)) {
      return success("添加成功");
    }
    return fail("添加失败");
  }

  @PreAuthorize("hasAuthority('sys:userRole:update')")
  @OperationLog
  @Operation(summary = "批量修改用户角色")
  @PutMapping("/batch")
  public ApiResult<?> removeBatch(@RequestBody BatchParam<UserRole> batchParam) {
    if (batchParam.update(userRoleService, "id")) {
      return success("修改成功");
    }
    return fail("修改失败");
  }

  @PreAuthorize("hasAuthority('sys:userRole:remove')")
  @OperationLog
  @Operation(summary = "批量删除用户角色")
  @DeleteMapping("/batch")
  public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
    if (userRoleService.removeByIds(ids)) {
      return success("删除成功");
    }
    return fail("删除失败");
  }

}
