import { ref, reactive, computed } from 'vue'
import { message } from 'ant-design-vue'
import { examAPI } from '../../../api/exam.js'
import { fileAPI } from '../../../api/file.js'
import { questionAPI } from '../../../api/question.js'

export function useGenerateState() {
  const selectedDoc = ref(null)
  const selectedDocData = ref(null)
  const selectedCollectionName = ref('')
  const difficulty = ref(2)
  const generatedQuestions = ref([])
  const isGenerating = ref(false)
  
  const questionTypeOptions = [
    { value: 'single_choice', label: '单选题' },
    { value: 'multiple_choice', label: '多选题' },
    { value: 'true_false', label: '判断题' },
    { value: 'fill_blank', label: '填空题' },
    { value: 'subjective', label: '简答题' }
  ]
  
  const questionTypeCounts = reactive({
    single_choice: 0,
    multiple_choice: 0,
    true_false: 0,
    fill_blank: 0,
    subjective: 0
  })
  
  // 题目总数：与出题任务 resultCount 统一，默认 null 表示"暂未生成"
  const apiTotalCount = ref(null)

  const totalQuestionCount = computed(() => {
    // 优先使用实际加载的题目列表长度（最准确），其次用任务resultCount
    if (generatedQuestions.value.length > 0) return generatedQuestions.value.length
    if (apiTotalCount.value !== null && apiTotalCount.value > 0) return apiTotalCount.value
    return '-'
  })

  // 重置为未生成状态（开始新任务时调用）
  const resetApiTotalCount = () => { apiTotalCount.value = null }

  const examTypeStats = computed(() => [
    { value: totalQuestionCount.value, label: '题目总数' },
    { value: generatedQuestions.value.length || '-', label: '已生成' },
    { value: difficulty.value === 1 ? '简单' : difficulty.value === 2 ? '中等' : '困难', label: '难度等级' }
  ])
  
  const onDocSelected = (doc) => {
    selectedDocData.value = doc
  }
  
  const onCollectionChange = (name) => {
    selectedCollectionName.value = name
  }
  
  const toggleQuestionType = (type) => {
    if (questionTypeCounts[type] > 0) {
      questionTypeCounts[type] = 0
    } else {
      questionTypeCounts[type] = 1
    }
  }
  
  const handleGenerateQuestions = async () => {
    if (!selectedDoc.value) {
      message.warning('请先选择制度文件')
      return
    }

    if (totalQuestionCount.value === 0) {
      message.warning('请至少配置一道题目')
      return
    }

    isGenerating.value = true
    generatedQuestions.value = []

    const generationStartTime = new Date()
    console.log('🚀 [useGenerateState] 开始生成题目...')
    console.log('   - 生成开始时间:', generationStartTime.toISOString())

    try {
      const activeTypes = {}
      Object.entries(questionTypeCounts).forEach(([key, val]) => {
        if (val > 0) activeTypes[key] = val
      })

      const doc = selectedDocData.value
      let fileId = doc?.id || doc?.fileId
      // 向量库的文件：真正的 file_id 可能嵌套在 sourceData 中
      if (!fileId && doc?.sourceData) {
        fileId = doc.sourceData.metadata?.file_id || doc.sourceData.file_id || doc.sourceData.id
      }

      console.log('   - selectedDocData 完整对象:', JSON.stringify(doc, null, 2))
      console.log('   - 文件ID:', fileId)
      console.log('   - 题型配置:', JSON.stringify(activeTypes, null, 2))
      console.log('   - 题目总数:', totalQuestionCount.value)
      console.log('   - 难度等级:', difficulty.value)

      const params = {
        question_count: totalQuestionCount.value,
        question_types: activeTypes,
        difficulty: difficulty.value,
        request_id: `gen_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
      }

      if (fileId) {
        params.file_id = Number(fileId)
      } else if (doc?.pdfUrl || doc?.filePath || doc?.path) {
        params.file_path = doc.pdfUrl || doc.filePath || doc.path
        params.collection = selectedCollectionName.value || 'public_kb'
      } else {
        console.error('❌ [useGenerateState] 无法获取文件ID或文件路径!', JSON.stringify(doc))
        throw new Error('无法获取文件信息，请重新选择文件后重试')
      }

      console.log('📤 [useGenerateState] 完整请求参数:', JSON.stringify(params, null, 2))

      const result = await examAPI.generateQuestions(params)

      console.log('✅ [useGenerateState] 生成任务返回:', result)

      // ============================================================
      // FIX 1: 检查初始响应中是否已直接包含题目（同步模式）
      // 后端可能直接返回题目，无需轮询
      // ============================================================
      let initialQuestions = null

      // 格式1: result.data.questions (RAG服务原始格式：{success, data: {questions: [...]}})
      if (result?.data?.questions && Array.isArray(result.data.questions) && result.data.questions.length > 0) {
        initialQuestions = result.data.questions
        console.log('📦 [useGenerateState] 在 result.data.questions 中发现题目:', initialQuestions.length)
      }
      // 格式2: result.questions (Java后端解包后的格式)
      else if (result?.questions && Array.isArray(result.questions) && result.questions.length > 0) {
        initialQuestions = result.questions
        console.log('📦 [useGenerateState] 在 result.questions 中发现题目:', initialQuestions.length)
      }
      // 格式3: result.data 本身就是一个数组（直接返回题目列表）
      else if (result?.data && Array.isArray(result.data) && result.data.length > 0) {
        initialQuestions = result.data
        console.log('📦 [useGenerateState] 在 result.data（数组）中发现题目:', initialQuestions.length)
      }
      // 格式4: result 本身就是一个数组
      else if (Array.isArray(result) && result.length > 0) {
        initialQuestions = result
        console.log('📦 [useGenerateState] result 本身就是题目数组:', initialQuestions.length)
      }

      // 同步模式：后端直接返回了题目
      if (initialQuestions) {
        console.log('✅ [useGenerateState] 同步模式：接口直接返回题目，无需轮询')
        generatedQuestions.value = transformQuestionData(initialQuestions)
        apiTotalCount.value = generatedQuestions.value.length
        message.success(`成功生成 ${generatedQuestions.value.length} 道题目`)
        console.log(`\n📋 题目详情:`)
        generatedQuestions.value.forEach((q, i) => {
          console.log(`   题${i+1}: ${q.typeLabel} | ${q.stem?.substring(0, 50)}...`)
        })
        isGenerating.value = false
        return
      }

      // ============================================================
      // 异步模式：后端返回 request_id，需要轮询等待
      // ============================================================
      if (!result || (!result.requestId && !result.request_id && !result.message)) {
        console.warn('⚠️ [useGenerateState] 未找到 request_id 或题目，尝试从 pending 接口获取...')
      }

      const requestId = result?.requestId || result?.request_id || 'unknown'
      message.loading({ content: '题目正在异步生成中，请耐心等待...', key: 'generating', duration: 0 })

      console.log(`⏳ [useGenerateState] RequestId: ${requestId}，开始轮询等待...`)

      console.log(`🔍 [useGenerateState] 获取到的 fileId: ${fileId} (类型: ${typeof fileId})`)
      if (!fileId) {
        console.warn('⚠️ [useGenerateState] fileId 为空，将无法监控文件状态！')
      }

      console.log(`📋 [useGenerateState] 生成流程说明:`)
      console.log(`   - 生成接口: POST /api/exam/generate`)
      console.log(`   - 状态检测: 轮询 GET /api/file/{id}`)

      const maxPollAttempts = 60
      const initialPollIntervalMs = 4000
      const maxPollIntervalMs = 10000
      let currentPollIntervalMs = initialPollIntervalMs
      let pollCount = 0
      let found = false
      let lastFileStatus = null
      let consecutiveNoChangeCount = 0
      let pollNoFileStatusCount = 0
      let loggedFullResponse = false

      console.log(`⚙️ [useGenerateState] 轮询配置:`)
      console.log(`   - 最大次数: ${maxPollAttempts} (约${(maxPollAttempts * 7 / 60).toFixed(0)}分钟)`)
      console.log(`   - 初始间隔: ${initialPollIntervalMs/1000}秒`)
      console.log(`   - 最大间隔: ${maxPollIntervalMs/1000}秒`)

      while (pollCount < maxPollAttempts && !found) {
        pollCount++

        console.log(`\n${'='.repeat(50)}`)
        console.log(`🔄 [${pollCount}/${maxPollAttempts}] 第${pollCount}次轮询 | 间隔: ${(currentPollIntervalMs/1000).toFixed(1)}s`)

        try {
          let fileStatusChanged = false
          if (fileId) {
            try {
              const fileRes = await fileAPI.getFileDetail(fileId)

              // 首次轮询时打印完整响应用于诊断
              if (!loggedFullResponse && pollCount === 1) {
                console.log('📋 [诊断] GET /api/file/', fileId, '原始响应:', JSON.stringify(fileRes?.data))
                loggedFullResponse = true
              }

              let fileInfo = null
              if (fileRes?.data?.data) {
                fileInfo = fileRes.data.data
              } else if (fileRes?.data) {
                fileInfo = fileRes.data
              }

              if (fileInfo) {
                const examStatus = fileInfo.examStatus || fileInfo.exam_status || ''
                const processMsg = fileInfo.processMessage || fileInfo.process_message || ''

                const prevStatus = lastFileStatus?.examStatus
                lastFileStatus = { examStatus, processMessage: processMsg }
                pollNoFileStatusCount = 0

                console.log(`📁 文件状态: ${examStatus || '未设置'}${prevStatus && prevStatus !== examStatus ? ` ✨ (从 ${prevStatus} 变化)` : ''}`)

                if (examStatus === 'FAILED') {
                  message.destroy('generating')
                  message.error({ content: `RAG服务生成失败: ${processMsg || '未知错误'}`, duration: 0 })
                  isGenerating.value = false
                  return
                } else if (examStatus === 'GENERATED' || examStatus === 'COMPLETED') {
                  console.log(`✅ 文件状态已变为 ${examStatus}`)
                  fileStatusChanged = true
                } else if (examStatus === 'GENERATING') {
                  console.log('⏳ RAG服务正在生成中...')
                  fileStatusChanged = true
                }
              } else {
                pollNoFileStatusCount++
                if (pollNoFileStatusCount <= 3) {
                  console.warn(`⚠️ 第${pollNoFileStatusCount}次无法解析文件状态`)
                }
              }
            } catch (fileErr) {
              console.warn(`⚠️ 获取文件状态失败:`, fileErr.message)
            }
          }

          // 每5次轮询尝试直接查询 pending 题目（即使文件状态未更新）
          if (!fileStatusChanged && pollCount % 5 === 0) {
            try {
              console.log(`🔍 [${pollCount}] 尝试直接查询 pending 题目...`)
              const checkRes = await questionAPI.getPendingQuestions()
              const checkQuestions = checkRes?.data?.data || checkRes?.data?.list || checkRes?.data || []
              if (Array.isArray(checkQuestions) && checkQuestions.length > 0) {
                console.log(`🎉 [${pollCount}] 在 pending 中发现 ${checkQuestions.length} 条题目！直接使用`)

                const currentFileId = selectedDocData.value?.id
                let matchCount = 0
                if (currentFileId) {
                  const strFileId = String(currentFileId)
                  const matchedQs = checkQuestions.filter(q => String(q.documentId || q.document_id || '') === strFileId)
                  matchCount = matchedQs.length
                  if (matchCount > 0) {
                    found = true
                    generatedQuestions.value = transformQuestionData(matchedQs)
                    apiTotalCount.value = generatedQuestions.value.length
                    message.destroy('generating')
                    message.success(`成功生成 ${generatedQuestions.value.length} 道题目`)
                    break
                  }
                }

                console.log(`🔍 pending 中题目数: ${checkQuestions.length}, 匹配当前文件: ${matchCount}`)
              }
            } catch (checkErr) {
              console.warn(`⚠️ 查询 pending 题目失败:`, checkErr.message)
            }
          }

          if (fileStatusChanged && (lastFileStatus?.examStatus === 'GENERATED' || lastFileStatus?.examStatus === 'COMPLETED')) {
            found = true
            console.log(`🎉 文件状态已变为 GENERATED，开始获取待审批题目...`)

            // FIX 3: 先从初始 result 中尝试获取题目（如果之前漏掉了）
            let pendingQuestions = null

            if (result?.data?.questions && Array.isArray(result.data.questions)) {
              pendingQuestions = result.data.questions
              console.log('📦 从 result.data.questions 获取题目:', pendingQuestions.length)
            } else if (result?.questions && Array.isArray(result.questions)) {
              pendingQuestions = result.questions
              console.log('📦 从 result.questions 获取题目:', pendingQuestions.length)
            }

            // 如果 result 中没有，再从 pending 接口获取
            if (!pendingQuestions) {
              const pendingRes = await questionAPI.getPendingQuestions()
              console.log(`📤 [useGenerateState] 调用接口: GET /api/question/pending`)
              console.log(`   - 接口返回:`, pendingRes)

              pendingQuestions = pendingRes?.data?.data || pendingRes?.data?.list || pendingRes?.data || pendingRes || []
              if (!Array.isArray(pendingQuestions)) {
                pendingQuestions = []
              }
            }

            const currentFileId = selectedDocData.value?.id
            const currentFileName = selectedDocData.value?.title || selectedDocData.value?.rawFileName || '未知文件'

            console.log(`\n📁 [useGenerateState] 待审批题目信息:`)
            console.log(`   - 当前文件ID: ${currentFileId} (类型: ${typeof currentFileId})`)
            console.log(`   - 当前文件名: ${currentFileName}`)
            console.log(`   - 原始题目数: ${pendingQuestions.length}`)
            console.log(`   - 请求生成数量: ${totalQuestionCount.value}`)
            console.log(`   - 生成开始时间: ${generationStartTime.toISOString()}`)

            let filteredQuestions = []
            let filterMethod = 'none'

            if (currentFileId) {
              const strFileId = String(currentFileId)
              filteredQuestions = pendingQuestions.filter(q => {
                const qDocId = q.documentId || q.document_id || ''
                return String(qDocId) === strFileId
              })

              console.log(`   - 方法1 (documentId=${strFileId}) 过滤结果: ${filteredQuestions.length} 条`)

              if (filteredQuestions.length > 0) {
                filterMethod = 'documentId'
              } else {
                console.warn(`   ⚠️ documentId过滤失败`)
                pendingQuestions.slice(0, 5).forEach((q, i) => {
                  console.warn(`     题${i+1}: documentId=${q.documentId || q.document_id || '空'}, documentName=${q.documentName || q.document_name || '空'}, createdAt=${q.createdAt || q.created_at || '无'}`)
                })
              }
            }

            if (filterMethod === 'none' && filteredQuestions.length === 0) {
              const timeFiltered = pendingQuestions.filter(q => {
                const createdAt = q.createdAt || q.created_at
                if (!createdAt) return false
                return new Date(createdAt) >= generationStartTime
              })

              console.log(`   - 方法2 (时间戳) 过滤结果: ${timeFiltered.length} 条`)

              if (timeFiltered.length > 0) {
                filteredQuestions = timeFiltered
                filterMethod = 'timestamp'
              } else {
                console.warn(`   ⚠️ 时间戳过滤也失败，取全部题目`)
                filteredQuestions = pendingQuestions
                filterMethod = 'all_pending'
              }
            }

            if (filteredQuestions.length > totalQuestionCount.value && filterMethod !== 'documentId') {
              console.log(`   ℹ️ 截取: ${filteredQuestions.length} → ${totalQuestionCount.value}`)
              filteredQuestions = filteredQuestions.slice(0, totalQuestionCount.value)
            }

            console.log(`\n✅ 最终过滤结果: 方法=${filterMethod}, 题目数=${filteredQuestions.length}`)

            generatedQuestions.value = transformQuestionData(filteredQuestions)
            apiTotalCount.value = generatedQuestions.value.length

            console.log(`\n✅ [useGenerateState] 数据转换完成:`)
            console.log(`   - 输入: ${filteredQuestions.length} 条`)
            console.log(`   - 输出: ${generatedQuestions.value.length} 条标准化数据`)
            generatedQuestions.value.forEach((q, i) => {
              console.log(`   题${i+1}: ${q.typeLabel} | ${q.stem?.substring(0, 50)}...`)
            })

            message.destroy('generating')
            message.success(`成功生成 ${generatedQuestions.value.length} 道题目（来自：${currentFileName}）`)
            break
          }

          if (!fileStatusChanged && (!lastFileStatus?.examStatus || lastFileStatus?.examStatus === 'UNGENERATED')) {
            consecutiveNoChangeCount++
            if (consecutiveNoChangeCount <= 3) {
              console.log(`💡 等待后端启动异步任务... (${consecutiveNoChangeCount}/3)`)
            } else if (consecutiveNoChangeCount === 10) {
              console.log(`ℹ️ 已等待较长时间，后端可能处理较慢`)
            }
          } else {
            consecutiveNoChangeCount = 0
          }

        } catch (e) {
          console.error(`❌ [${pollCount}] 轮询异常:`, e.message)
        }

        if (!found && pollCount < maxPollAttempts) {
          console.log(`⏳ 等待 ${(currentPollIntervalMs/1000).toFixed(1)}秒...`)
          await new Promise(resolve => setTimeout(resolve, currentPollIntervalMs))

          if (pollCount % 4 === 0 && currentPollIntervalMs < maxPollIntervalMs) {
            currentPollIntervalMs = Math.min(currentPollIntervalMs * 1.5, maxPollIntervalMs)
            console.log(`📈 调整间隔: ${(currentPollIntervalMs/1000).toFixed(1)}秒`)
          }
        }
      }

      if (!found) {
        message.destroy('generating')
        const totalWaitTimeSec = (maxPollAttempts * 3.5 / 60).toFixed(1)
        console.warn(`\n⚠️ 轮询完成 (${pollCount}/${maxPollAttempts}次), 等待约${totalWaitTimeSec}分钟`)
        console.warn(`📁 最终文件状态: ${lastFileStatus?.examStatus || '未知'}`)

        // 兜底：轮询结束后始终尝试从 pending 接口获取题目
        let fallbackQuestions = null
        try {
          console.log('🔍 [兜底] 轮询结束，尝试从 pending 接口获取题目...')
          const fallbackRes = await questionAPI.getPendingQuestions()
          const fallbackAll = fallbackRes?.data?.data || fallbackRes?.data?.list || fallbackRes?.data || []
          if (Array.isArray(fallbackAll) && fallbackAll.length > 0) {
            const strFileId = String(selectedDocData.value?.id || '')
            if (strFileId) {
              fallbackQuestions = fallbackAll.filter(q => String(q.documentId || q.document_id || '') === strFileId)
            }
            if (!fallbackQuestions || fallbackQuestions.length === 0) {
              fallbackQuestions = fallbackAll.filter(q => {
                const createdAt = q.createdAt || q.created_at
                return createdAt && new Date(createdAt) >= generationStartTime
              })
            }
            if (!fallbackQuestions || fallbackQuestions.length === 0) {
              fallbackQuestions = fallbackAll
            }
          }
        } catch (fbErr) {
          console.warn('⚠️ [兜底] 获取题目失败:', fbErr.message)
        }

        // 再尝试从初始 result 中取题目
        if (!fallbackQuestions || fallbackQuestions.length === 0) {
          const lateQuestions = result?.data?.questions || result?.questions || []
          if (Array.isArray(lateQuestions) && lateQuestions.length > 0) {
            console.log('📦 轮询结束后在 result 中发现题目，直接使用')
            fallbackQuestions = lateQuestions
          }
        }

        if (fallbackQuestions && fallbackQuestions.length > 0) {
          console.log(`✅ [兜底] 成功获取 ${fallbackQuestions.length} 道题目`)
          generatedQuestions.value = transformQuestionData(fallbackQuestions)
          apiTotalCount.value = generatedQuestions.value.length
          message.success(`成功生成 ${generatedQuestions.value.length} 道题目`)
        } else if (lastFileStatus?.examStatus === 'GENERATING') {
          message.warning({ content: '生成任务仍在进行中，请稍后手动刷新查看结果', duration: 10 })
        } else if (!lastFileStatus?.examStatus || lastFileStatus?.examStatus === 'UNGENERATED') {
          message.info({
            content: '暂未检测到新题目，可能原因：\n1. 后端异步任务尚未开始\n2. 生成时间较长\n建议稍后刷新页面查看',
            duration: 8
          })
        } else {
          message.info({ content: '请稍后刷新页面查看最新生成的题目', duration: 6 })
        }
      }

    } catch (error) {
      console.error('❌ 生成题目失败:', error)
      message.destroy('generating')
      message.error(error.message || '生成题目时发生错误')
    } finally {
      isGenerating.value = false
    }
  }

  const formatQuestionType = (type) => {
    const typeMap = {
      'single_choice': '单选题',
      'multiple_choice': '多选题',
      'true_false': '判断题',
      'fill_blank': '填空题',
      'subjective': '简答题',
      'single': '单选题',
      'multiple': '多选题',
      'judgment': '判断题',
      'essay': '简答题'
    }
    return typeMap[type] || type || '未分类'
  }

  const transformQuestionData = (rawQuestions) => {
    if (!Array.isArray(rawQuestions)) return []

    return rawQuestions.map((q, qIdx) => {
      let contentObj = {}

      try {
        if (typeof q.content === 'string' && q.content.trim().startsWith('{')) {
          contentObj = JSON.parse(q.content || '{}')
        } else if (typeof q.content === 'object' && q.content !== null) {
          contentObj = q.content
        }
      } catch (e) {
        console.warn(`[useGenerateState] 题目${qIdx} content解析失败:`, e.message)
      }

      const rawStem = contentObj.stem ||
                     (contentObj.data && contentObj.data.stem) ||
                     q.stem ||
                     q.question_stem ||
                     q.questionContent ||
                     q.question_content ||
                     (typeof q.content === 'string' ? q.content : '')

      let rawOptions = contentObj.options ||
                       (contentObj.data && contentObj.data.options) ||
                       q.options || []

      if (rawOptions.length === 0 && contentObj.data && Array.isArray(contentObj.data)) {
        rawOptions = contentObj.data
      }

      let options = []
      if (Array.isArray(rawOptions) && rawOptions.length > 0) {
        if (rawOptions[0] && typeof rawOptions[0] === 'object' && rawOptions[0].key) {
          options = rawOptions.map(opt => ({
            key: String(opt.key),
            text: opt.content || opt.text || '',
            isCorrect: false
          }))
        } else {
          const optionKeys = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
          options = rawOptions.map((opt, idx) => ({
            key: optionKeys[idx] || String.fromCharCode(65 + idx),
            text: typeof opt === 'object' ? (opt.content || opt.text || '') : String(opt),
            isCorrect: false
          }))
        }
      }

      // 将 answer 映射到选项的 isCorrect 字段（选择题）
      const rawType = q.questionType || q.question_type || q.type || ''
      const typeStr = String(rawType).toLowerCase()
      const rawAnswer = q.answer !== undefined ? q.answer : (contentObj.answer || '')
      if ((typeStr === 'single_choice' || typeStr === 'multiple_choice') && rawAnswer && options.length > 0) {
        const answerKeys = String(rawAnswer).toUpperCase().split(/[,，]/).map(s => s.trim())
        options.forEach(opt => {
          if (answerKeys.includes(opt.key)) {
            opt.isCorrect = true
          }
        })
      }

      return {
        id: q.questionId || q.question_id || q.id || `gen_q_${qIdx}`,
        questionId: q.questionId || q.question_id || q.id || `gen_q_${qIdx}`,
        type: String(rawType).toLowerCase(),
        typeLabel: formatQuestionType(rawType),
        difficulty: q.difficulty || 2,
        score: Number(q.score) || Number(q.questionScore) || 5,
        stem: rawStem,
        options: options,
        answer: rawAnswer,
        status: q.status || 'pending',
        documentId: q.documentId || q.document_id || '',
        documentName: q.documentName || q.document_name || '',
        createdAt: q.createdAt || q.created_at
      }
    })
  }

  return {
    selectedDoc,
    selectedDocData,
    selectedCollectionName,
    difficulty,
    generatedQuestions,
    isGenerating,
    questionTypeOptions,
    questionTypeCounts,
    totalQuestionCount,
    apiTotalCount,
    resetApiTotalCount,
    examTypeStats,
    onDocSelected,
    onCollectionChange,
    toggleQuestionType,
    handleGenerateQuestions,
    transformQuestionData
  }
}
