import ApiService from '../services/apiService';
import type { PrizeConfig } from '../database/database';
import EventService, { EVENT_TYPES, type PrizeDrawnEventData } from './eventService';
import type { LotteryRecord } from '../types';

export interface DrawResult {
  success: boolean;
  prize?: {
    id: string;
    name: string;
    level: number;
  };
  message: string;
  remaining?: number;
}

export interface LotteryStats {
  totalDraws: number;
  prizeDistribution: Record<number, number>;
  remainingPrizes: PrizeConfig[];
}

class LotteryService {
  private api: ApiService;
  private static instance: LotteryService;

  private constructor() {
    this.api = ApiService.getInstance();
  }

  public static getInstance(): LotteryService {
    if (!LotteryService.instance) {
      LotteryService.instance = new LotteryService();
    }
    return LotteryService.instance;
  }

  // 验证学号格式
  public validateStudentId(studentId: string): boolean {
    // 12位数字学号验证
    const regex = /^\d{12}$/;
    return regex.test(studentId);
  }

  // 检查学生是否可以抽奖
  public async canStudentDraw(studentId: string): Promise<{ canDraw: boolean; message: string }> {
    console.log('=== canStudentDraw 验证开始 ===');
    console.log('输入学号:', studentId);
    console.log('学号长度:', studentId.length);
    console.log('学号类型:', typeof studentId);
    
    // 验证学号格式
    const isValidFormat = this.validateStudentId(studentId);
    console.log('学号格式验证结果:', isValidFormat);
    
    if (!isValidFormat) {
      console.log('学号格式验证失败，返回格式错误提示');
      return { canDraw: false, message: '学号格式不正确，请输入12位数字学号' };
    }

    const systemConfig = await this.api.getSystemConfig();
    console.log('系统配置:', systemConfig);
    
    if (!systemConfig) {
      console.log('系统配置获取失败');
      return { canDraw: false, message: '系统配置错误，请联系管理员' };
    }

    const student = await this.api.getStudent(studentId);
    console.log('学生信息:', student);
    console.log('最大抽奖次数:', systemConfig.max_draw_times);
    
    if (student && student.draw_count >= systemConfig.max_draw_times) {
      console.log('抽奖次数验证失败，当前次数:', student.draw_count, '最大次数:', systemConfig.max_draw_times);
      return { canDraw: false, message: `已达到抽奖上限！每人最多只能抽奖${systemConfig.max_draw_times}次` };
    }

    console.log('所有验证通过，可以开始抽奖');
    return { canDraw: true, message: '验证通过，可以开始抽奖' };
  }

  // 执行抽奖
  public async drawLottery(studentId: string): Promise<DrawResult> {
    // 验证是否可以抽奖
    const validation = await this.canStudentDraw(studentId);
    if (!validation.canDraw) {
      return {
        success: false,
        message: validation.message
      };
    }

    try {
      // 获取所有奖项，只考虑启用且有剩余数量的奖项
      const prizes = await this.api.getAllPrizes();
      const availablePrizes = prizes.filter(p => p.is_active && p.remaining_quantity > 0);
      
      if (availablePrizes.length === 0) {
        return {
          success: false,
          message: '暂无可抽取的奖品'
        };
      }

      // 执行加权随机抽奖
      const selectedPrize = this.weightedRandomDraw(availablePrizes);
      
      if (!selectedPrize) {
        return {
          success: false,
          message: '抽奖失败，请重试'
        };
      }

      // 更新数据库 - 确保原子性操作，防止重复计数
      const newRemainingQuantity = selectedPrize.remaining_quantity - 1;
      
      // 使用 await 确保所有数据库操作按顺序执行
      // 先更新奖品数量
      await this.api.updatePrizeQuantity(selectedPrize.id, newRemainingQuantity);
      
      // 创建抽奖记录
      await this.api.createLotteryRecord(
        studentId,
        selectedPrize.id,
        selectedPrize.prize_name,
        selectedPrize.prize_level
      );
      
      // 最后更新学生抽奖次数（只在成功抽奖后更新）
      await this.api.createOrUpdateStudent(studentId);

      // 触发奖品抽中事件，用于全站无感刷新
      const eventService = EventService.getInstance();
      const eventData: PrizeDrawnEventData = {
        studentId,
        prizeId: selectedPrize.id,
        prizeName: selectedPrize.prize_name,
        prizeLevel: selectedPrize.prize_level,
        remainingQuantity: newRemainingQuantity,
        timestamp: Date.now()
      };
      eventService.emit(EVENT_TYPES.PRIZE_DRAWN, eventData);
      eventService.emit(EVENT_TYPES.PRIZES_UPDATED, {
        updatedPrizes: [{
          id: selectedPrize.id,
          remainingQuantity: newRemainingQuantity,
          totalQuantity: selectedPrize.total_quantity
        }],
        timestamp: Date.now()
      });

      console.log('=== 构建抽奖返回结果 ===');
      console.log('selectedPrize:', selectedPrize);
      
      const result = {
        success: true,
        prize: {
          id: selectedPrize.id,
          name: selectedPrize.prize_name,
          level: selectedPrize.prize_level
        },
        message: '恭喜中奖！',
        remaining: newRemainingQuantity,
        studentId: studentId,
        timestamp: Date.now(),
        formattedStudentId: this.formatStudentId(studentId)
      };
      
      console.log('返回结果:', JSON.stringify(result, null, 2));
      return result;

    } catch (error) {
      console.error('Draw lottery error:', error);
      return {
        success: false,
        message: '抽奖过程中发生错误，请重试'
      };
    }
  }



  // 加权随机抽奖算法
  private weightedRandomDraw(prizes: PrizeConfig[]): PrizeConfig | null {
    // 只考虑启用且有剩余数量的奖项
    const enabledPrizes = prizes.filter(p => p.is_active && p.remaining_quantity > 0);
    
    if (enabledPrizes.length === 0) {
      return null;
    }
    
    // 计算启用奖项的总权重
    const totalWeight = enabledPrizes.reduce((sum, prize) => sum + prize.probability, 0);
    
    if (totalWeight === 0) {
      return null;
    }

    // 生成随机数
    const random = Math.random() * totalWeight;
    
    // 根据权重选择奖品
    let currentWeight = 0;
    for (const prize of enabledPrizes) {
      currentWeight += prize.probability;
      if (random <= currentWeight) {
        return prize;
      }
    }

    // 兜底返回最后一个启用的奖品
    return enabledPrizes[enabledPrizes.length - 1];
  }

  // 获取抽奖统计信息
  public async getLotteryStats(): Promise<LotteryStats> {
    const records = await this.api.getLotteryRecords(1000);
    const prizes = await this.api.getAllPrizes();
    
    const prizeDistribution: Record<number, number> = {};
    
    records.forEach(record => {
      prizeDistribution[record.prize_level] = (prizeDistribution[record.prize_level] || 0) + 1;
    });

    return {
      totalDraws: records.length,
      prizeDistribution,
      remainingPrizes: prizes.filter(p => p.remaining_quantity > 0)
    };
  }

  // 获取学生抽奖记录
  public async getStudentHistory(studentId: string): Promise<LotteryRecord[]> {
    return this.api.getStudentRecords(studentId);
  }

  // 验证首页登录密码
  public async validateLoginPassword(password: string): Promise<boolean> {
    const config = await this.api.getSystemConfig();
    return config ? config.login_password === password : false;
  }

  // 验证后台管理密码
  public async validateAdminPassword(password: string): Promise<boolean> {
    const config = await this.api.getSystemConfig();
    return config ? config.admin_password === password : false;
  }

  // 获取隐藏位置配置
  public async getHidePositions(): Promise<number[]> {
    const config = await this.api.getSystemConfig();
    if (!config || !config.hide_positions) {
      return [3, 4, 5, 6]; // 默认隐藏位置
    }
    
    try {
      return config.hide_positions.split(',').map(pos => parseInt(pos.trim()));
    } catch {
      return [3, 4, 5, 6];
    }
  }

  // 格式化学号显示
  public formatStudentId(studentId: string): string {
    // 不隐藏任何数字，每四位用空格分隔
    return studentId.replace(/(\d{4})(?=\d)/g, '$1 ');
  }
  
  // 清理方法，防止内存泄漏
  public cleanup(): void {
    // 清理API服务
    this.api.cleanup();
    console.log('🧹 LotteryService 已清理');
  }
}

export default LotteryService;