package com.xy.xyaicpzs.controller;

import com.xy.xyaicpzs.common.response.ApiResponse;
import com.xy.xyaicpzs.common.ResultUtils;
import com.xy.xyaicpzs.common.ErrorCode;
import com.xy.xyaicpzs.domain.entity.VipExchangeRecord;
import com.xy.xyaicpzs.service.VipExchangeRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * VIP兑换记录控制器
 */
@RestController
@RequestMapping("/vip-exchange-record")
@Slf4j
@Tag(name = "VIP兑换记录管理", description = "VIP兑换记录相关接口")
public class VipExchangeRecordController {

    @Autowired
    private VipExchangeRecordService vipExchangeRecordService;

    /**
     * 根据用户ID获取所有兑换记录
     */
    @GetMapping("/user/{userId}")
    @Operation(summary = "获取用户兑换记录", description = "根据用户ID获取该用户的所有VIP兑换记录")
    public ApiResponse<List<VipExchangeRecord>> getExchangeRecordsByUserId(
            @Parameter(description = "用户ID", required = true)
            @PathVariable("userId") Long userId) {
        
        try {
            log.info("获取用户兑换记录，用户ID：{}", userId);
            
            // 参数校验
            if (userId == null || userId <= 0) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "用户ID不能为空且必须大于0");
            }
            
            // 查询用户兑换记录
            List<VipExchangeRecord> records = vipExchangeRecordService.getExchangeRecordsByUserId(userId);
            
            log.info("用户ID：{} 的兑换记录查询成功，共{}条记录", userId, records.size());
            
            return ResultUtils.success(records);
            
        } catch (Exception e) {
            log.error("获取用户兑换记录失败，用户ID：{}", userId, e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "获取兑换记录失败：" + e.getMessage());
        }
    }

    /**
     * 根据用户ID获取兑换记录（带分页）
     */
    @GetMapping("/user/{userId}/page")
    @Operation(summary = "分页获取用户兑换记录", description = "根据用户ID分页获取该用户的VIP兑换记录")
    public ApiResponse<List<VipExchangeRecord>> getExchangeRecordsByUserIdWithPage(
            @Parameter(description = "用户ID", required = true)
            @PathVariable("userId") Long userId,
            @Parameter(description = "页码，从1开始", required = false)
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @Parameter(description = "每页大小", required = false)
            @RequestParam(value = "size", defaultValue = "10") Integer size) {
        
        try {
            log.info("分页获取用户兑换记录，用户ID：{}，页码：{}，每页大小：{}", userId, page, size);
            
            // 参数校验
            if (userId == null || userId <= 0) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "用户ID不能为空且必须大于0");
            }
            
            if (page < 1) {
                page = 1;
            }
            if (size < 1 || size > 100) {
                size = 10;
            }
            
            // 查询用户兑换记录
            List<VipExchangeRecord> allRecords = vipExchangeRecordService.getExchangeRecordsByUserId(userId);
            
            // 手动分页
            int start = (page - 1) * size;
            int end = Math.min(start + size, allRecords.size());
            List<VipExchangeRecord> pageRecords = allRecords.subList(start, end);
            
            log.info("用户ID：{} 的兑换记录分页查询成功，总记录数：{}，当前页记录数：{}", 
                    userId, allRecords.size(), pageRecords.size());
            
            return ResultUtils.success(pageRecords);
            
        } catch (Exception e) {
            log.error("分页获取用户兑换记录失败，用户ID：{}", userId, e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "获取兑换记录失败：" + e.getMessage());
        }
    }

    /**
     * 根据兑换记录ID获取详情
     */
    @GetMapping("/{recordId}")
    @Operation(summary = "获取兑换记录详情", description = "根据兑换记录ID获取详细信息")
    public ApiResponse<VipExchangeRecord> getExchangeRecordById(
            @Parameter(description = "兑换记录ID", required = true)
            @PathVariable("recordId") Long recordId) {
        
        try {
            log.info("获取兑换记录详情，记录ID：{}", recordId);
            
            // 参数校验
            if (recordId == null || recordId <= 0) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "兑换记录ID不能为空且必须大于0");
            }
            
            // 查询兑换记录
            VipExchangeRecord record = vipExchangeRecordService.getById(recordId);
            
            if (record == null) {
                return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "兑换记录不存在");
            }
            
            log.info("兑换记录详情查询成功，记录ID：{}", recordId);
            
            return ResultUtils.success(record);
            
        } catch (Exception e) {
            log.error("获取兑换记录详情失败，记录ID：{}", recordId, e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "获取兑换记录详情失败：" + e.getMessage());
        }
    }
} 