import Taro from '@tarojs/taro';
import { GameType, StorageKey } from '../constants';
import { Room, TurtleSoupQuestion, ActionResult, TurtleSoupGameData } from '../interfaces';
import * as api from './api';

/**
 * 处理海龟汤游戏逻辑
 */
export class TurtleSoupGameService {
  /**
   * 获取海龟汤问题列表
   * @param params 参数
   */
  static async getQuestions(params?: { category?: string; difficulty?: number; isPremium?: boolean }): Promise<TurtleSoupQuestion[]> {
    return api.getTurtleSoupQuestions(params);
  }

  /**
   * 随机获取一个海龟汤问题
   * @param params 参数
   */
  static async getRandomQuestion(params?: { category?: string; difficulty?: number; isPremium?: boolean }): Promise<TurtleSoupQuestion> {
    const questions = await this.getQuestions(params);
    const randomIndex = Math.floor(Math.random() * questions.length);
    return questions[randomIndex];
  }

  /**
   * 开始海龟汤游戏
   * @param roomId 房间ID
   * @param questionId 问题ID，如果不传则随机选择
   */
  static async startGame(roomId: string, questionId?: string): Promise<ActionResult> {
    let question: TurtleSoupQuestion;
    
    if (questionId) {
      const questions = await this.getQuestions();
      question = questions.find(q => q.questionId === questionId) || await this.getRandomQuestion();
    } else {
      question = await this.getRandomQuestion();
    }

    return api.startGame(roomId, { 
      gameType: GameType.TURTLE_SOUP,
      questionId: question.questionId,
      gameData: {
        currentQuestion: question,
        playerAnswers: {},
        revealedClues: [],
        gameState: 'playing',
        startTime: new Date()
      } as TurtleSoupGameData
    });
  }

  /**
   * 提交问题答案
   * @param roomId 房间ID
   * @param answer 答案
   */
  static async submitAnswer(roomId: string, answer: string): Promise<ActionResult> {
    return api.gameAction(roomId, { 
      action: 'submitAnswer', 
      data: { answer } 
    });
  }

  /**
   * 揭示线索
   * @param roomId 房间ID
   * @param clueId 线索ID
   */
  static async revealClue(roomId: string, clueId: string): Promise<ActionResult> {
    return api.gameAction(roomId, { 
      action: 'revealClue', 
      data: { clueId } 
    });
  }

  /**
   * 结束游戏
   * @param roomId 房间ID
   */
  static async endGame(roomId: string): Promise<ActionResult> {
    return api.endGame(roomId);
  }

  /**
   * 获取玩家视图数据
   * @param room 房间信息
   */
  static getPlayerViewData(room: Room): any {
    const gameData = room.gameData as TurtleSoupGameData;
    
    // 玩家只能看到汤面和已揭示的线索
    return {
      question: {
        title: gameData.currentQuestion.title,
        category: gameData.currentQuestion.category,
        difficultyLevel: gameData.currentQuestion.difficultyLevel,
      },
      revealedClues: gameData.revealedClues.map(clueId => {
        const clue = gameData.currentQuestion.keyClues.find(c => c.type + c.value === clueId);
        return clue || null;
      }).filter(Boolean),
      gameState: gameData.gameState,
      playerAnswers: Object.keys(gameData.playerAnswers).length,
      startTime: gameData.startTime,
      endTime: gameData.endTime,
    };
  }

  /**
   * 获取主持人视图数据
   * @param room 房间信息
   */
  static getHostViewData(room: Room): any {
    const gameData = room.gameData as TurtleSoupGameData;
    
    // 主持人可以看到完整信息
    return {
      question: gameData.currentQuestion,
      revealedClues: gameData.revealedClues,
      playerAnswers: gameData.playerAnswers,
      gameState: gameData.gameState,
      startTime: gameData.startTime,
      endTime: gameData.endTime,
      availableClues: gameData.currentQuestion.keyClues.filter(
        clue => !gameData.revealedClues.includes(clue.type + clue.value)
      ),
    };
  }
}

/**
 * 创建游戏服务
 * @param gameType 游戏类型
 */
export const createGameService = (gameType: GameType) => {
  switch (gameType) {
    case GameType.TURTLE_SOUP:
      return TurtleSoupGameService;
    default:
      throw new Error(`不支持的游戏类型: ${gameType}`);
  }
};

/**
 * 获取当前房间信息
 */
export const getCurrentRoom = (): Room | null => {
  try {
    const roomInfo = Taro.getStorageSync(StorageKey.ROOM_INFO);
    return roomInfo ? JSON.parse(roomInfo) : null;
  } catch (error) {
    console.error('获取当前房间信息失败：', error);
    return null;
  }
};

/**
 * 保存当前房间信息
 * @param room 房间信息
 */
export const saveCurrentRoom = (room: Room): void => {
  try {
    Taro.setStorageSync(StorageKey.ROOM_INFO, JSON.stringify(room));
  } catch (error) {
    console.error('保存当前房间信息失败：', error);
  }
};

/**
 * 清除当前房间信息
 */
export const clearCurrentRoom = (): void => {
  try {
    Taro.removeStorageSync(StorageKey.ROOM_INFO);
  } catch (error) {
    console.error('清除当前房间信息失败：', error);
  }
}; 