package com.xy.xyaicpzs.controller;

import com.xy.xyaicpzs.common.ErrorCode;
import com.xy.xyaicpzs.common.ResultUtils;
import com.xy.xyaicpzs.common.response.ApiResponse;
import com.xy.xyaicpzs.domain.entity.DltDrawRecord;
import com.xy.xyaicpzs.domain.entity.User;
import com.xy.xyaicpzs.service.DltDrawRecordService;
import com.xy.xyaicpzs.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 大乐透开奖记录控制器
 * 提供大乐透开奖记录查询的API接口
 */
@Slf4j
@RestController
@RequestMapping("/dlt-draw")
@Tag(name = "大乐透开奖记录", description = "大乐透开奖记录查询API")
public class DltDrawController {

    @Autowired
    private DltDrawRecordService dltDrawRecordService;

    @Autowired
    private UserService userService;

    /**
     * 获取近期大乐透开奖信息
     * @param limit 获取条数，可选参数，默认10条
     * @return 近期开奖信息列表
     */
    @GetMapping("/recent-draws")
    @Operation(summary = "获取近期大乐透开奖信息", description = "获取最近的大乐透开奖信息，默认返回10条，按开奖日期倒序排列")
    public ApiResponse<List<DltDrawRecord>> getRecentDraws(
            @Parameter(description = "获取条数，默认10条", required = false)
            @RequestParam(required = false, defaultValue = "10") Integer limit, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR, "您还未登录，请登录后查看");
        }
        try {
            log.info("接收到获取近期大乐透开奖信息请求：条数={}", limit);
            
            // 调用服务获取近期开奖信息，按开奖日期倒序排列
            List<DltDrawRecord> result = dltDrawRecordService.lambdaQuery()
                    .orderByDesc(DltDrawRecord::getDrawDate)
                    .last("LIMIT " + limit)
                    .list();
            
            log.info("获取近期大乐透开奖信息完成，返回{}条记录", result.size());
            return ResultUtils.success(result);
            
        } catch (Exception e) {
            log.error("获取近期大乐透开奖信息失败：{}", e.getMessage(), e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "获取近期大乐透开奖信息失败：" + e.getMessage());
        }
    }

    /**
     * 根据日期范围查询大乐透开奖信息
     * @param startDate 开始日期（可选，格式：yyyy-MM-dd）
     * @param endDate 结束日期（可选，格式：yyyy-MM-dd）
     * @return 开奖信息列表
     */
    @GetMapping("/query-draws")
    @Operation(summary = "按日期范围查询大乐透开奖信息", description = "根据日期范围查询大乐透开奖信息，支持单边日期查询")
    public ApiResponse<List<DltDrawRecord>> queryDraws(
            @Parameter(description = "开始日期，格式：yyyy-MM-dd，例如：2025-01-01", required = false)
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            
            @Parameter(description = "结束日期，格式：yyyy-MM-dd，例如：2025-01-31", required = false)
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR, "您还未登录，请登录后查看");
        }
        
        try {
            log.info("接收到按日期范围查询大乐透开奖信息请求：开始日期={}，结束日期={}", startDate, endDate);
            
            // 日期范围验证
            if (startDate != null && endDate != null && startDate.after(endDate)) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "开始日期不能晚于结束日期");
            }
            
            // 构建查询条件
            var queryWrapper = dltDrawRecordService.lambdaQuery();
            
            if (startDate != null) {
                queryWrapper.ge(DltDrawRecord::getDrawDate, startDate);
            }
            
            if (endDate != null) {
                queryWrapper.le(DltDrawRecord::getDrawDate, endDate);
            }
            
            // 按开奖日期倒序排列
            List<DltDrawRecord> result = queryWrapper
                    .orderByDesc(DltDrawRecord::getDrawDate)
                    .list();
            
            log.info("按日期范围查询大乐透开奖信息完成，返回{}条记录", result.size());
            return ResultUtils.success(result);
            
        } catch (Exception e) {
            log.error("按日期范围查询大乐透开奖信息失败：{}", e.getMessage(), e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "查询大乐透开奖信息失败：" + e.getMessage());
        }
    }

    /**
     * 根据期号精准查询单条大乐透开奖信息
     * @param drawId 开奖期号
     * @return 开奖信息
     */
    @GetMapping("/draw/{drawId}")
    @Operation(summary = "根据期号查询大乐透开奖信息", description = "根据期号精准查询单条大乐透开奖信息")
    public ApiResponse<DltDrawRecord> getDrawById(
            @Parameter(description = "开奖期号，例如：07001", required = true)
            @PathVariable String drawId,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR, "您还未登录，请登录后查看");
        }
        
        try {
            log.info("接收到根据期号查询大乐透开奖信息请求：期号={}", drawId);
            
            // 调用服务查询开奖信息
            DltDrawRecord result = dltDrawRecordService.lambdaQuery()
                    .eq(DltDrawRecord::getDrawId, drawId)
                    .one();
            
            if (result == null) {
                log.warn("未找到期号为{}的大乐透开奖信息", drawId);
                return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "未找到期号为" + drawId + "的大乐透开奖信息");
            }
            
            log.info("根据期号查询大乐透开奖信息完成：{}", result.getDrawId());
            return ResultUtils.success(result);
            
        } catch (Exception e) {
            log.error("根据期号查询大乐透开奖信息失败：{}", e.getMessage(), e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "查询大乐透开奖信息失败：" + e.getMessage());
        }
    }

    /**
     * 根据开奖期号查询大乐透开奖球号
     * @param drawId 开奖期号
     * @return 7个中奖球号（5个前区+2个后区）
     */
    @GetMapping("/draw/{drawId}/numbers")
    @Operation(summary = "根据开奖期号查询大乐透开奖球号", description = "根据开奖期号查询7个中奖球号（5个前区+2个后区）")
    public ApiResponse<List<Integer>> getDrawNumbersById(
            @Parameter(description = "开奖期号，例如：07001", required = true)
            @PathVariable String drawId,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR, "您还未登录，请登录后查看");
        }

        try {
            log.info("接收到根据期号查询大乐透开奖球号请求：期号={}", drawId);

            // 调用服务查询开奖信息
            DltDrawRecord result = dltDrawRecordService.lambdaQuery()
                    .eq(DltDrawRecord::getDrawId, drawId)
                    .one();

            if (result == null) {
                log.warn("未找到期号为{}的大乐透开奖信息", drawId);
                return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "未找到期号为" + drawId + "的大乐透开奖信息");
            }

            List<Integer> winningNumbers = new ArrayList<>();
            // 前区5个球号
            winningNumbers.add(result.getFrontBall1());
            winningNumbers.add(result.getFrontBall2());
            winningNumbers.add(result.getFrontBall3());
            winningNumbers.add(result.getFrontBall4());
            winningNumbers.add(result.getFrontBall5());
            // 后区2个球号
            winningNumbers.add(result.getBackBall1());
            winningNumbers.add(result.getBackBall2());

            log.info("根据期号查询大乐透开奖球号完成：{}，球号：{}", drawId, winningNumbers);
            return ResultUtils.success(winningNumbers);

        } catch (Exception e) {
            log.error("根据期号查询大乐透开奖球号失败：{}", e.getMessage(), e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "查询大乐透开奖球号失败：" + e.getMessage());
        }
    }

    /**
     * 获取近10期大乐透开奖期号
     * @return 近10期开奖期号列表
     */
    @GetMapping("/recent-10-draw-ids")
    @Operation(summary = "获取近10期大乐透开奖期号", description = "获取dlt_draw_record表中最新的10期开奖期号，按开奖日期倒序排列")
    public ApiResponse<List<String>> getRecent10DrawIds(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR, "您还未登录，请登录后查看");
        }
        try {
            log.info("接收到获取近10期大乐透开奖期号请求");
            
            // 查询最近10期开奖期号，按开奖日期倒序
            List<String> drawIds = dltDrawRecordService.lambdaQuery()
                    .select(DltDrawRecord::getDrawId)
                    .orderByDesc(DltDrawRecord::getDrawDate)
                    .last("LIMIT 10")
                    .list()
                    .stream()
                    .map(DltDrawRecord::getDrawId)
                    .collect(java.util.stream.Collectors.toList());
            
            log.info("获取近10期大乐透开奖期号完成，返回{}条记录", drawIds.size());
            return ResultUtils.success(drawIds);
            
        } catch (Exception e) {
            log.error("获取近10期大乐透开奖期号失败：{}", e.getMessage(), e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "获取近10期大乐透开奖期号失败：" + e.getMessage());
        }
    }

    /**
     * 获取近10期大乐透开奖信息
     * @return 近10期开奖信息列表
     */
    @GetMapping("/recent-10-draws")
    @Operation(summary = "获取近10期大乐透开奖信息", description = "获取dlt_draw_record表中最新的10期开奖信息，按开奖日期倒序排列")
    public ApiResponse<List<DltDrawRecord>> getRecent10Draws(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR, "您还未登录，请登录后查看");
        }
        try {
            log.info("接收到获取近10期大乐透开奖信息请求");
            
            // 调用服务获取近10期开奖信息，按开奖日期倒序
            List<DltDrawRecord> result = dltDrawRecordService.lambdaQuery()
                    .orderByDesc(DltDrawRecord::getDrawDate)
                    .last("LIMIT 10")
                    .list();
            
            log.info("获取近10期大乐透开奖信息完成，返回{}条记录", result.size());
            return ResultUtils.success(result);
            
        } catch (Exception e) {
            log.error("获取近10期大乐透开奖信息失败：{}", e.getMessage(), e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "获取近10期大乐透开奖信息失败：" + e.getMessage());
        }
    }

    /**
     * 获取近100期大乐透开奖信息
     * @return 近100期开奖信息列表
     */
    @GetMapping("/recent-100-draws")
    @Operation(summary = "获取近100期大乐透开奖信息", description = "获取dlt_draw_record表中最新的100期开奖信息，按开奖日期倒序排列")
    public ApiResponse<List<DltDrawRecord>> getRecent100Draws(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR, "您还未登录，请登录后查看");
        }
        Date now = new Date();
        if (loginUser.getVipExpire() == null || loginUser.getVipExpire().before(now)) {
            return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "VIP会员已过期，请续费后使用");
        }
        try {
            log.info("接收到获取近100期大乐透开奖信息请求");
            
            // 调用服务获取近100期开奖信息，按开奖日期倒序
            List<DltDrawRecord> result = dltDrawRecordService.lambdaQuery()
                    .orderByDesc(DltDrawRecord::getDrawDate)
                    .last("LIMIT 100")
                    .list();
            
            log.info("获取近100期大乐透开奖信息完成，返回{}条记录", result.size());
            return ResultUtils.success(result);
            
        } catch (Exception e) {
            log.error("获取近100期大乐透开奖信息失败：{}", e.getMessage(), e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "获取近100期大乐透开奖信息失败：" + e.getMessage());
        }
    }
}