package com.rj.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.sys.UserRole;
import com.rj.service.sys.IUserRoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户角色关联表 前端控制器
 * </p>
 *
 * @author 系统生成
 * @since 2025-08-07
 */
@RestController
@RequestMapping("/api/sys/userRole")
@Tag(name = "用户角色管理", description = "用户角色关联管理相关接口")
public class UserRoleController {

    @Autowired
    private IUserRoleService userRoleService;

    /**
     * 新增用户角色关联
     */
    @PostMapping("/add")
    @Operation(summary = "新增用户角色关联", description = "添加新的用户角色关联信息")
    public ResponseEntity<Map<String, Object>> addUserRole(
            @Parameter(description = "用户角色关联信息", required = true)
            @RequestBody UserRole userRole) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = userRoleService.save(userRole);
            if (success) {
                result.put("success", true);
                result.put("message", "用户角色关联添加成功");
                result.put("data", userRole);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "用户角色关联添加失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "用户角色关联添加异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据用户ID查询用户角色关联
     */
    @GetMapping("/getByUserId/{userId}")
    @Operation(summary = "根据用户ID查询用户角色关联", description = "根据用户ID获取用户角色关联信息")
    public ResponseEntity<Map<String, Object>> getUserRoleByUserId(
            @Parameter(description = "用户ID", required = true)
            @PathVariable Integer userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserRole::getUserId, userId);
            List<UserRole> userRoleList = userRoleService.list(queryWrapper);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", userRoleList);
            result.put("count", userRoleList.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据角色ID查询用户角色关联
     */
    @GetMapping("/getByRoleId/{roleId}")
    @Operation(summary = "根据角色ID查询用户角色关联", description = "根据角色ID获取用户角色关联信息")
    public ResponseEntity<Map<String, Object>> getUserRoleByRoleId(
            @Parameter(description = "角色ID", required = true)
            @PathVariable Integer roleId) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserRole::getRoleId, roleId);
            List<UserRole> userRoleList = userRoleService.list(queryWrapper);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", userRoleList);
            result.put("count", userRoleList.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 分页查询用户角色关联列表
     */
    @GetMapping("/list")
    @Operation(summary = "分页查询用户角色关联列表", description = "分页查询用户角色关联信息列表")
    public ResponseEntity<Map<String, Object>> getUserRoleList(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10")
            @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "用户ID")
            @RequestParam(required = false) Integer userId,
            @Parameter(description = "角色ID")
            @RequestParam(required = false) Integer roleId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<UserRole> page = new Page<>(current, size);
            LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (userId != null) {
                queryWrapper.eq(UserRole::getUserId, userId);
            }
            if (roleId != null) {
                queryWrapper.eq(UserRole::getRoleId, roleId);
            }
            
            // 按用户ID和角色ID排序
            queryWrapper.orderByAsc(UserRole::getUserId).orderByAsc(UserRole::getRoleId);
            
            Page<UserRole> userRolePage = userRoleService.page(page, queryWrapper);
            
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", userRolePage.getRecords());
            result.put("total", userRolePage.getTotal());
            result.put("current", userRolePage.getCurrent());
            result.put("size", userRolePage.getSize());
            result.put("pages", userRolePage.getPages());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 更新用户角色关联信息
     */
    @PutMapping("/update")
    @Operation(summary = "更新用户角色关联信息", description = "更新用户角色关联详细信息")
    public ResponseEntity<Map<String, Object>> updateUserRole(
            @Parameter(description = "用户角色关联信息", required = true)
            @RequestBody UserRole userRole) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (userRole.getUserId() == null || userRole.getRoleId() == null) {
                result.put("success", false);
                result.put("message", "用户ID和角色ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            boolean success = userRoleService.updateById(userRole);
            
            if (success) {
                result.put("success", true);
                result.put("message", "用户角色关联信息更新成功");
                result.put("data", userRole);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "用户角色关联信息更新失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 删除用户角色关联
     */
    @DeleteMapping("/delete")
    @Operation(summary = "删除用户角色关联", description = "根据用户ID和角色ID删除用户角色关联信息")
    public ResponseEntity<Map<String, Object>> deleteUserRole(
            @Parameter(description = "用户ID", required = true)
            @RequestParam Integer userId,
            @Parameter(description = "角色ID", required = true)
            @RequestParam Integer roleId) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserRole::getUserId, userId).eq(UserRole::getRoleId, roleId);
            boolean success = userRoleService.remove(queryWrapper);
            if (success) {
                result.put("success", true);
                result.put("message", "用户角色关联删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "用户角色关联删除失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 批量删除用户角色关联
     */
    @DeleteMapping("/batchDelete")
    @Operation(summary = "批量删除用户角色关联", description = "根据用户角色关联列表批量删除")
    public ResponseEntity<Map<String, Object>> batchDeleteUserRoles(
            @Parameter(description = "用户角色关联列表", required = true)
            @RequestBody List<UserRole> userRoles) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (userRoles == null || userRoles.isEmpty()) {
                result.put("success", false);
                result.put("message", "用户角色关联列表不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            boolean success = userRoleService.removeByIds(userRoles);
            if (success) {
                result.put("success", true);
                result.put("message", "批量删除成功，共删除 " + userRoles.size() + " 条记录");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "批量删除失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取用户角色关联统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取用户角色关联统计信息", description = "获取用户角色关联总数等统计信息")
    public ResponseEntity<Map<String, Object>> getUserRoleStatistics() {
        Map<String, Object> result = new HashMap<>();
        try {
            long totalCount = userRoleService.count();
            
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalUserRoles", totalCount);
            
            result.put("success", true);
            result.put("message", "统计信息获取成功");
            result.put("data", statistics);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "统计信息获取异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}























































































































