// 数据库服务 - 直接调用服务器API
// 移除所有本地存储，统一使用服务器数据库

import type { LotteryRecord } from '../types';

// 数据库接口定义
export interface SystemConfig {
  id: string;
  admin_password: string;
  login_password: string;
  max_draw_times: number;
  background_config: string;
  hide_positions: string;
  created_at: string;
  updated_at: string;
}

export interface PrizeConfig {
  id: string;
  prize_name: string;
  prize_level: number;
  total_quantity: number;
  remaining_quantity: number;
  probability: number;
  is_active: boolean;
  created_at: string;
}

export interface Student {
  student_id: string;
  draw_count: number;
  first_draw_at?: string;
  last_draw_at?: string;
}



class DatabaseService {
  private static instance: DatabaseService;
  private baseUrl: string = 'http://localhost:3010/api';

  private constructor() {
    // 直接使用服务器API，无需初始化本地数据库
  }

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

  // HTTP请求辅助方法
  private async request(endpoint: string, options: RequestInit = {}): Promise<any> {
    const url = `${this.baseUrl}${endpoint}`;
    const response = await fetch(url, {
      headers: {
        'Content-Type': 'application/json',
        ...options.headers,
      },
      ...options,
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return response.json();
  }

  private generateId(): string {
    return Math.random().toString(36).substr(2, 9) + Date.now().toString(36);
  }

  // 系统配置相关方法
  public async getSystemConfig(): Promise<SystemConfig | null> {
    try {
      return await this.request('/system/config');
    } catch (error) {
      console.error('获取系统配置失败:', error);
      return null;
    }
  }

  public async updateSystemConfig(config: Partial<SystemConfig>): Promise<boolean> {
    try {
      await this.request('/system/config', {
        method: 'PUT',
        body: JSON.stringify(config),
      });
      return true;
    } catch (error) {
      console.error('更新系统配置失败:', error);
      return false;
    }
  }

  public async changeAdminPassword(newPassword: string): Promise<boolean> {
    try {
      await this.request('/system/admin-password', {
        method: 'PUT',
        body: JSON.stringify({ password: newPassword }),
      });
      return true;
    } catch (error) {
      console.error('修改管理员密码失败:', error);
      return false;
    }
  }

  public async verifyAdminPassword(password: string): Promise<boolean> {
    try {
      const result = await this.request('/system/verify-admin', {
        method: 'POST',
        body: JSON.stringify({ password }),
      });
      return result.valid;
    } catch (error) {
      console.error('验证管理员密码失败:', error);
      return false;
    }
  }

  // 更新管理员密码
  public async updateAdminPassword(newPassword: string): Promise<boolean> {
    try {
      return await this.changeAdminPassword(newPassword);
    } catch (error) {
      console.error('Update admin password failed:', error);
      return false;
    }
  }

  // 验证当前管理员密码
  public async validateCurrentAdminPassword(password: string): Promise<boolean> {
    try {
      return await this.verifyAdminPassword(password);
    } catch (error) {
      console.error('Validate admin password failed:', error);
      return false;
    }
  }

  // 重置管理员密码为默认值
  public async resetAdminPasswordToDefault(): Promise<boolean> {
    try {
      console.log('重置管理员密码为默认值: 123456');
      return await this.changeAdminPassword('123456');
    } catch (error) {
      console.error('Reset admin password failed:', error);
      return false;
    }
  }

  // 更新首页登录密码
  public async updateLoginPassword(newPassword: string): Promise<boolean> {
    try {
      console.log('更新首页登录密码');
      return await this.updateSystemConfig({ login_password: newPassword });
    } catch (error) {
      console.error('Update login password failed:', error);
      return false;
    }
  }

  // 验证首页登录密码
  public async validateLoginPassword(password: string): Promise<boolean> {
    try {
      const config = await this.getSystemConfig();
      return config ? config.login_password === password : false;
    } catch (error) {
      console.error('Validate login password failed:', error);
      return false;
    }
  }

  // 重置首页登录密码为默认值
  public async resetLoginPasswordToDefault(): Promise<boolean> {
    try {
      console.log('重置首页登录密码为默认值: 123456');
      return await this.updateSystemConfig({ login_password: '123456' });
    } catch (error) {
      console.error('Reset login password failed:', error);
      return false;
    }
  }

  // 奖项配置相关操作
  public async getAllPrizes(): Promise<PrizeConfig[]> {
    try {
      return await this.request('/prizes');
    } catch (error) {
      console.error('获取奖项列表失败:', error);
      return [];
    }
  }

  // 添加奖项
  public async addPrize(prize: Omit<PrizeConfig, 'id' | 'remaining_quantity' | 'created_at'>): Promise<boolean> {
    try {
      await this.request('/prizes', {
        method: 'POST',
        body: JSON.stringify(prize),
      });
      return true;
    } catch (error) {
      console.error('添加奖项失败:', error);
      return false;
    }
  }

  // 更新奖项
  public async updatePrize(id: string, prize: Partial<Omit<PrizeConfig, 'id' | 'created_at'>>): Promise<boolean> {
    try {
      await this.request(`/prizes/${id}`, {
        method: 'PUT',
        body: JSON.stringify(prize),
      });
      return true;
    } catch (error) {
      console.error('更新奖项失败:', error);
      return false;
    }
  }

  // 删除奖项
  public async deletePrize(id: string): Promise<boolean> {
    try {
      await this.request(`/prizes/${id}`, {
        method: 'DELETE',
      });
      return true;
    } catch (error) {
      console.error('删除奖项失败:', error);
      return false;
    }
  }

  // 获取所有抽奖记录
  public async getAllDrawRecords(): Promise<LotteryRecord[]> {
    try {
      return await this.request('/records');
    } catch (error) {
      console.error('获取抽奖记录失败:', error);
      return [];
    }
  }

  public async updatePrizeQuantity(prizeId: string, remainingQuantity: number): Promise<boolean> {
    try {
      await this.request(`/prizes/${prizeId}/quantity`, {
        method: 'PUT',
        body: JSON.stringify({ remaining_quantity: remainingQuantity }),
      });
      return true;
    } catch (error) {
      console.error('Update prize quantity failed:', error);
      return false;
    }
  }

  // 学生相关操作
  public async getStudent(studentId: string): Promise<Student | null> {
    try {
      return await this.request(`/students/${studentId}`);
    } catch (error) {
      console.error('Get student failed:', error);
      return null;
    }
  }

  public async createOrUpdateStudent(studentId: string): Promise<Student> {
    try {
      return await this.request('/students', {
        method: 'POST',
        body: JSON.stringify({ student_id: studentId }),
      });
    } catch (error) {
      console.error('Create or update student failed:', error);
      throw error;
    }
  }

  // 抽奖记录相关操作
  public async createLotteryRecord(studentId: string, prizeId: string, prizeName: string, prizeLevel: number): Promise<LotteryRecord> {
    try {
      const record = {
        student_id: studentId,
        prize_id: prizeId,
        prize_name: prizeName,
        prize_level: prizeLevel
      };
      return await this.request('/records', {
        method: 'POST',
        body: JSON.stringify(record),
      });
    } catch (error) {
      console.error('Create lottery record failed:', error);
      throw error;
    }
  }

  public async createDrawRecord(record: Omit<LotteryRecord, 'id' | 'draw_time' | 'is_synced' | 'cache_data'>): Promise<LotteryRecord> {
    try {
      return await this.request('/records', {
        method: 'POST',
        body: JSON.stringify(record),
      });
    } catch (error) {
      console.error('创建抽奖记录失败:', error);
      throw error;
    }
  }

  public async getLotteryRecords(limit?: number): Promise<LotteryRecord[]> {
    try {
      const params = limit ? `?limit=${limit}` : '';
      return await this.request(`/records${params}`);
    } catch (error) {
      console.error('Get lottery records failed:', error);
      return [];
    }
  }

  public async getStudentRecords(studentId: string): Promise<LotteryRecord[]> {
    try {
      return await this.request(`/students/${studentId}/records`);
    } catch (error) {
      console.error('Get student records failed:', error);
      return [];
    }
  }

  // 清空所有抽奖记录
  public async clearAllLotteryRecords(): Promise<boolean> {
    try {
      await this.request('/records', {
        method: 'DELETE',
      });
      return true;
    } catch (error) {
      console.error('Clear lottery records failed:', error);
      return false;
    }
  }

  public async clearAllDrawRecords(): Promise<boolean> {
    try {
      return await this.clearAllLotteryRecords();
    } catch (error) {
      console.error('清空抽奖记录失败:', error);
      return false;
    }
  }

  // 一键重置系统：清空记录、重置奖项数量和重新计算概率
  public async resetSystemCompletely(): Promise<boolean> {
    try {
      await this.request('/system/reset', {
        method: 'POST',
      });
      return true;
    } catch (error) {
      console.error('一键重置系统失败:', error);
      return false;
    }
  }

  public async resetSystem(): Promise<boolean> {
    try {
      return await this.resetSystemCompletely();
    } catch (error) {
      console.error('系统重置失败:', error);
      return false;
    }
  }

  // 强制重置数据库
  public async forceResetDatabase(): Promise<boolean> {
    try {
      console.log('DatabaseService: 开始强制重置数据库...');
      return await this.resetSystemCompletely();
    } catch (error) {
      console.error('强制重置数据库失败:', error);
      return false;
    }
  }

  // 模拟抽奖（用于测试）
  public async simulateLottery(studentId: string, prizeId: string): Promise<LotteryRecord | null> {
    try {
      return await this.request('/lottery/simulate', {
        method: 'POST',
        body: JSON.stringify({ studentId, prizeId }),
      });
    } catch (error) {
      console.error('模拟抽奖失败:', error);
      return null;
    }
  }
  
  // 抽奖逻辑现在由服务器处理
  // 客户端不再需要本地抽奖逻辑

  // 保存数据库（用于数据持久化）
  public async saveDatabase(): Promise<boolean> {
    try {
      await this.request('/system/save', {
        method: 'POST',
      });
      return true;
    } catch (error) {
      console.error('保存数据库失败:', error);
      return false;
    }
  }

  // 获取数据库统计信息
  public async getDatabaseStats(): Promise<any> {
    try {
      return await this.request('/system/stats');
    } catch (error) {
      console.error('获取数据库统计信息失败:', error);
      return null;
    }
  }

  // 关闭数据库连接
  public close(): void {
    // 服务器端数据库连接由服务器管理，客户端无需关闭
    console.log('使用服务器数据库，无需关闭连接');
  }
}

export default DatabaseService;