// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command
const roomCollection = db.collection('rooms')
const riddleCollection = db.collection('turtle_soup_riddles')

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  
  if (!openid) {
    return {
      code: 401,
      message: '未能获取到用户OpenID',
    }
  }
  
  const { action, roomId, riddleId, question, clue, answer } = event
  
  try {
    // 获取随机题目
    if (action === 'getRandomRiddle') {
      // 获取所有题目的总数
      const countResult = await riddleCollection.count()
      const total = countResult.total
      
      if (total === 0) {
        return {
          code: 404,
          message: '没有可用的题目',
        }
      }
      
      // 随机选择一个题目
      const random = Math.floor(Math.random() * total)
      const riddleResult = await riddleCollection.skip(random).limit(1).get()
      
      if (riddleResult.data.length === 0) {
        return {
          code: 404,
          message: '获取题目失败',
        }
      }
      
      const riddle = riddleResult.data[0]
      
      return {
        code: 200,
        message: '获取题目成功',
        data: {
          riddleId: riddle._id,
          title: riddle.title,
          description: riddle.description,
          answer: riddle.answer,
          difficulty: riddle.difficulty,
          tips: riddle.tips
        }
      }
    }
    
    // 根据ID获取题目
    else if (action === 'getRiddleById') {
      if (!riddleId) {
        return {
          code: 400,
          message: '缺少必要参数：riddleId',
        }
      }
      
      const riddleResult = await riddleCollection.doc(riddleId).get()
      const riddle = riddleResult.data
      
      return {
        code: 200,
        message: '获取题目成功',
        data: {
          riddleId: riddle._id,
          title: riddle.title,
          description: riddle.description,
          answer: riddle.answer,
          difficulty: riddle.difficulty,
          tips: riddle.tips
        }
      }
    }
    
    // 初始化房间的游戏数据
    else if (action === 'initGameData') {
      if (!roomId || !riddleId) {
        return {
          code: 400,
          message: '缺少必要参数：roomId或riddleId',
        }
      }
      
      // 获取房间信息
      const roomResult = await roomCollection.doc(roomId).get()
      const room = roomResult.data
      
      // 检查是否是房主
      if (room.hostId !== openid) {
        return {
          code: 403,
          message: '只有房主可以初始化游戏数据',
        }
      }
      
      // 获取题目信息
      const riddleResult = await riddleCollection.doc(riddleId).get()
      const riddle = riddleResult.data
      
      // 初始化游戏数据
      const gameData = {
        riddleId: riddle._id,
        title: riddle.title,
        description: riddle.description,
        answer: riddle.answer,
        questions: [],
        clues: [],
        solved: false,
        startedAt: db.serverDate(),
        hostRevealedAnswer: false
      }
      
      // 更新房间游戏数据
      await roomCollection.doc(roomId).update({
        data: {
          gameData,
          updatedAt: db.serverDate()
        }
      })
      
      return {
        code: 200,
        message: '游戏数据初始化成功',
        data: {
          roomId,
          gameData: {
            ...gameData,
            answer: undefined // 不向客户端返回答案
          }
        }
      }
    }
    
    // 提交问题（玩家向主持人提问）
    else if (action === 'submitQuestion') {
      if (!roomId || !question) {
        return {
          code: 400,
          message: '缺少必要参数：roomId或question',
        }
      }
      
      // 获取房间信息
      const roomResult = await roomCollection.doc(roomId).get()
      const room = roomResult.data
      
      // 检查房间状态
      if (room.status !== 'playing') {
        return {
          code: 400,
          message: '游戏尚未开始或已结束',
        }
      }
      
      // 检查是否是玩家（非房主）
      if (room.hostId === openid) {
        return {
          code: 403,
          message: '房主不能提交问题',
        }
      }
      
      // 检查用户是否在房间中
      const playerExists = room.players.some(p => p.userId === openid && p.status === 'active')
      if (!playerExists) {
        return {
          code: 403,
          message: '您不是该房间的成员',
        }
      }
      
      // 获取用户信息
      const playerInfo = room.players.find(p => p.userId === openid)
      
      // 添加问题到游戏数据
      const newQuestion = {
        id: Date.now().toString(),
        content: question,
        askedBy: {
          userId: openid,
          nickName: playerInfo.nickName,
          avatarUrl: playerInfo.avatarUrl
        },
        askedAt: db.serverDate(),
        status: 'pending', // pending, answered, rejected
        answer: '',
        answeredAt: null
      }
      
      const updatedGameData = room.gameData || {}
      updatedGameData.questions = [...(updatedGameData.questions || []), newQuestion]
      
      // 更新房间游戏数据
      await roomCollection.doc(roomId).update({
        data: {
          'gameData.questions': _.push(newQuestion),
          updatedAt: db.serverDate()
        }
      })
      
      return {
        code: 200,
        message: '问题提交成功',
        data: {
          roomId,
          questionId: newQuestion.id
        }
      }
    }
    
    // 回答问题（主持人回答玩家的问题）
    else if (action === 'answerQuestion') {
      if (!roomId || !event.questionId || !event.answer || !event.status) {
        return {
          code: 400,
          message: '缺少必要参数：roomId、questionId、answer或status',
        }
      }
      
      // 获取房间信息
      const roomResult = await roomCollection.doc(roomId).get()
      const room = roomResult.data
      
      // 检查是否是房主
      if (room.hostId !== openid) {
        return {
          code: 403,
          message: '只有房主可以回答问题',
        }
      }
      
      // 查找问题在数组中的索引
      const questions = room.gameData?.questions || []
      const questionIndex = questions.findIndex(q => q.id === event.questionId)
      
      if (questionIndex === -1) {
        return {
          code: 404,
          message: '问题不存在',
        }
      }
      
      // 更新问题状态和回答
      await roomCollection.doc(roomId).update({
        data: {
          [`gameData.questions.${questionIndex}.status`]: event.status,
          [`gameData.questions.${questionIndex}.answer`]: event.answer,
          [`gameData.questions.${questionIndex}.answeredAt`]: db.serverDate(),
          updatedAt: db.serverDate()
        }
      })
      
      return {
        code: 200,
        message: '回答问题成功',
        data: {
          roomId,
          questionId: event.questionId,
          status: event.status
        }
      }
    }
    
    // 提交线索（主持人提供线索）
    else if (action === 'submitClue') {
      if (!roomId || !clue) {
        return {
          code: 400,
          message: '缺少必要参数：roomId或clue',
        }
      }
      
      // 获取房间信息
      const roomResult = await roomCollection.doc(roomId).get()
      const room = roomResult.data
      
      // 检查是否是房主
      if (room.hostId !== openid) {
        return {
          code: 403,
          message: '只有房主可以提交线索',
        }
      }
      
      // 添加线索到游戏数据
      const newClue = {
        id: Date.now().toString(),
        content: clue,
        providedAt: db.serverDate()
      }
      
      // 更新房间游戏数据
      await roomCollection.doc(roomId).update({
        data: {
          'gameData.clues': _.push(newClue),
          updatedAt: db.serverDate()
        }
      })
      
      return {
        code: 200,
        message: '线索提交成功',
        data: {
          roomId,
          clueId: newClue.id
        }
      }
    }
    
    // 提交答案（玩家尝试解答）
    else if (action === 'submitAnswer') {
      if (!roomId || !answer) {
        return {
          code: 400,
          message: '缺少必要参数：roomId或answer',
        }
      }
      
      // 获取房间信息
      const roomResult = await roomCollection.doc(roomId).get()
      const room = roomResult.data
      
      // 检查房间状态
      if (room.status !== 'playing') {
        return {
          code: 400,
          message: '游戏尚未开始或已结束',
        }
      }
      
      // 检查是否是玩家（非房主）
      if (room.hostId === openid) {
        return {
          code: 403,
          message: '房主不能提交答案',
        }
      }
      
      // 检查用户是否在房间中
      const playerExists = room.players.some(p => p.userId === openid && p.status === 'active')
      if (!playerExists) {
        return {
          code: 403,
          message: '您不是该房间的成员',
        }
      }
      
      // 获取用户信息
      const playerInfo = room.players.find(p => p.userId === openid)
      
      // 检查答案是否正确
      const isCorrect = room.gameData.answer.toLowerCase().includes(answer.toLowerCase())
      
      // 添加答案尝试到游戏数据
      const answerAttempt = {
        id: Date.now().toString(),
        content: answer,
        submittedBy: {
          userId: openid,
          nickName: playerInfo.nickName,
          avatarUrl: playerInfo.avatarUrl
        },
        submittedAt: db.serverDate(),
        isCorrect
      }
      
      // 更新房间游戏数据
      const updateData = {
        'gameData.answerAttempts': _.push(answerAttempt),
        updatedAt: db.serverDate()
      }
      
      // 如果答案正确，则更新游戏状态
      if (isCorrect) {
        updateData['gameData.solved'] = true
        updateData['gameData.solvedBy'] = {
          userId: openid,
          nickName: playerInfo.nickName,
          avatarUrl: playerInfo.avatarUrl
        }
        updateData['gameData.solvedAt'] = db.serverDate()
      }
      
      await roomCollection.doc(roomId).update({
        data: updateData
      })
      
      return {
        code: 200,
        message: isCorrect ? '恭喜你，回答正确！' : '答案不正确，请继续尝试',
        data: {
          roomId,
          isCorrect,
          answerId: answerAttempt.id
        }
      }
    }
    
    // 揭晓答案（主持人揭晓答案）
    else if (action === 'revealAnswer') {
      if (!roomId) {
        return {
          code: 400,
          message: '缺少必要参数：roomId',
        }
      }
      
      // 获取房间信息
      const roomResult = await roomCollection.doc(roomId).get()
      const room = roomResult.data
      
      // 检查是否是房主
      if (room.hostId !== openid) {
        return {
          code: 403,
          message: '只有房主可以揭晓答案',
        }
      }
      
      // 更新游戏数据
      await roomCollection.doc(roomId).update({
        data: {
          'gameData.hostRevealedAnswer': true,
          'gameData.revealedAt': db.serverDate(),
          updatedAt: db.serverDate()
        }
      })
      
      return {
        code: 200,
        message: '答案已揭晓',
        data: {
          roomId,
          answer: room.gameData.answer
        }
      }
    }
    
    else {
      return {
        code: 400,
        message: '无效的action参数',
      }
    }
  } catch (error) {
    console.error('海龟汤游戏操作失败:', error)
    return {
      code: 500,
      message: '操作失败: ' + error.message,
    }
  }
} 