package com.xy.xyaicpzs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xy.xyaicpzs.common.requset.PredictRecordQueryRequest;
import com.xy.xyaicpzs.common.response.PageResponse;
import com.xy.xyaicpzs.domain.entity.LotteryDraws;
import com.xy.xyaicpzs.domain.entity.PredictRecord;
import com.xy.xyaicpzs.domain.vo.UserPredictStatVO;
import com.xy.xyaicpzs.mapper.LotteryDrawsMapper;
import com.xy.xyaicpzs.mapper.PredictRecordMapper;
import com.xy.xyaicpzs.service.DataAnalysisService;
import com.xy.xyaicpzs.util.SsqPrizeCalculator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 数据分析服务实现类
 */
@Slf4j
@Service
public class DataAnalysisServiceImpl implements DataAnalysisService {
    
    @Autowired
    private PredictRecordMapper predictRecordMapper;
    
    @Autowired
    private LotteryDrawsMapper lotteryDrawsMapper;
    
    @Override
    public UserPredictStatVO getUserPredictStat(Long userId) {
        UserPredictStatVO statVO = new UserPredictStatVO();
        
        // 查询用户的所有预测记录
        QueryWrapper<PredictRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId)
                   .eq("type", "ssq");
        List<PredictRecord> predictRecords = predictRecordMapper.selectList(queryWrapper);
        
        if (predictRecords == null || predictRecords.isEmpty()) {
            statVO.setUserId(userId);
            statVO.setPredictCount(0L);
            statVO.setHitCount(0L);
            statVO.setPendingCount(0L);
            statVO.setDrawnCount(0L);
            statVO.setHitRate(java.math.BigDecimal.ZERO);
            return statVO;
        }
        
        // 统计数据
        long totalPredicts = predictRecords.size();
        long hitCount = 0L;
        long pendingCount = 0L;
        long drawnCount = 0L;
        
        for (PredictRecord record : predictRecords) {
            if ("待开奖".equals(record.getPredictStatus())) {
                pendingCount++;
            } else if ("已中奖".equals(record.getPredictStatus())) {
                hitCount++;
                drawnCount++;
            } else if ("未中奖".equals(record.getPredictStatus())) {
                drawnCount++;
            }
        }
        
        // 计算命中率
        java.math.BigDecimal hitRate = drawnCount > 0 ? 
            java.math.BigDecimal.valueOf(hitCount).divide(java.math.BigDecimal.valueOf(drawnCount), 4, java.math.RoundingMode.HALF_UP) : 
            java.math.BigDecimal.ZERO;
        
        statVO.setUserId(userId);
        statVO.setPredictCount(totalPredicts);
        statVO.setHitCount(hitCount);
        statVO.setPendingCount(pendingCount);
        statVO.setDrawnCount(drawnCount);
        statVO.setHitRate(hitRate);
        
        return statVO;
    }
    
    @Override
    public int processPendingPredictions() {
        log.info("开始处理双色球待开奖预测记录");
        
        // 查询所有待开奖的预测记录
        QueryWrapper<PredictRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("predictStatus", "待开奖")
                   .eq("type", "ssq");
        List<PredictRecord> pendingRecords = predictRecordMapper.selectList(queryWrapper);
        
        log.info("找到{}条待开奖的双色球预测记录", pendingRecords.size());
        
        int processedCount = 0;
        
        for (PredictRecord record : pendingRecords) {
            try {
                // 查询对应期号的开奖结果
                LotteryDraws draws = lotteryDrawsMapper.selectById(record.getDrawId());
                
                if (draws != null) {
                    log.debug("处理预测记录ID：{}，期号：{}，奖池：{}亿元，特别规定期间：{}", 
                             record.getId(), record.getDrawId(), draws.getPrizePool(), 
                             draws.getIsSpecialPeriod());
                    
                    // 构建预测号码数组 [红球6个, 蓝球1个]
                    Integer[] predictNumbers = {
                        record.getRedBall1(),
                        record.getRedBall2(),
                        record.getRedBall3(),
                        record.getRedBall4(),
                        record.getRedBall5(),
                        record.getRedBall6(),
                        record.getBlueBall()
                    };
                    
                    // 构建开奖号码数组 [红球6个, 蓝球1个]
                    Integer[] drawNumbers = {
                        draws.getRedBall1(),
                        draws.getRedBall2(),
                        draws.getRedBall3(),
                        draws.getRedBall4(),
                        draws.getRedBall5(),
                        draws.getRedBall6(),
                        draws.getBlueBall()
                    };
                    
                    // 获取奖池金额和特别规定状态
                    Double prizePool = draws.getPrizePool() != null ? draws.getPrizePool() : 0.0;
                    boolean isSpecialPeriod = draws.getIsSpecialPeriod() != null && draws.getIsSpecialPeriod() == 1;
                    
                    // 使用SsqPrizeCalculator计算中奖结果
                    SsqPrizeCalculator.PrizeResult prizeResult = SsqPrizeCalculator.calculatePrize(
                        predictNumbers, drawNumbers, prizePool, isSpecialPeriod);
                    
                    // 更新预测记录
                    if(prizeResult.getPrizeLevel().equals("未中奖")){
                        record.setPredictStatus("未中奖");
                    }else{
                        record.setPredictStatus("已中奖");
                    }
                    
                    record.setPredictResult(prizeResult.getPrizeLevel());
                    record.setBonus(prizeResult.getBonus());
                    predictRecordMapper.updateById(record);
                    
                    log.debug("预测记录ID：{} 处理完成，中奖等级：{}，奖金：{}元（奖池：{}亿元，特别规定：{}）", 
                             record.getId(), prizeResult.getPrizeLevel(), prizeResult.getBonus(), 
                             prizePool, isSpecialPeriod);
                    
                    processedCount++;
                } else {
                    log.debug("未找到期号{}的开奖记录", record.getDrawId());
                }
            } catch (Exception e) {
                log.error("处理预测记录ID：{} 时发生错误：{}", record.getId(), e.getMessage(), e);
            }
        }
        
        log.info("双色球待开奖预测记录处理完成，共处理{}条记录", processedCount);
        return processedCount;
    }
    
    @Override
    public PageResponse<PredictRecord> queryPredictRecords(PredictRecordQueryRequest request) {
        // 构建查询条件
        QueryWrapper<PredictRecord> queryWrapper = new QueryWrapper<>();
        
        // 添加用户ID筛选条件
        if (request.getUserId() != null) {
            queryWrapper.eq("userId", request.getUserId());
        }
        
        // 添加预测状态筛选条件
        if (StringUtils.hasText(request.getPredictStatus())) {
            queryWrapper.eq("predictStatus", request.getPredictStatus());
        }
        
        // 添加类型筛选条件，只查询双色球类型
        queryWrapper.eq("type", "ssq");
        
        // 按预测时间降序排序
        queryWrapper.orderByDesc("predictTime");
        
        // 执行分页查询
        Page<PredictRecord> page = new Page<>(request.getCurrent(), request.getPageSize());
        Page<PredictRecord> resultPage = predictRecordMapper.selectPage(page, queryWrapper);
        
        // 构建分页响应对象
        return PageResponse.of(
                resultPage.getRecords(), 
                resultPage.getTotal(), 
                (int) resultPage.getCurrent(), 
                (int) resultPage.getSize()
        );
    }
    
    @Override
    public long getTotalPredictCount() {
        // 获取全部预测记录数量（只统计双色球类型）
        QueryWrapper<PredictRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", "ssq");
        return predictRecordMapper.selectCount(queryWrapper);
    }
} 