import { ref, 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'

let taskIdCounter = 0

const tasks = ref([])

const activeTasks = computed(() => tasks.value.filter(t => t.status === 'generating' || t.status === 'pending'))
const completedTasks = computed(() => tasks.value.filter(t => t.status === 'completed' || t.status === 'failed'))
const hasActiveTasks = computed(() => activeTasks.value.length > 0)
const taskCount = computed(() => tasks.value.length)

export function useTaskManager() {
  const addTask = (fileData, difficulty = 2, questionTypeCounts = {}, totalCount = 0) => {
    const taskId = `task_${++taskIdCounter}`
    const task = {
      id: taskId,
      fileId: fileData.id || '',
      fileName: fileData.title || fileData.rawFileName || fileData.fileName || '未知文件',
      filePath: fileData.pdfUrl || fileData.filePath || fileData.path || '',
      collection: fileData.collectionName || '',
      difficulty,
      questionTypeCounts: { ...questionTypeCounts },
      totalCount,
      status: 'pending',
      examStatus: '',
      processMessage: '等待中...',
      processStepMessage: '',
      createdAt: new Date().toLocaleTimeString(),
      updatedAt: new Date().toLocaleTimeString(),
      pollingStopped: false
    }
    tasks.value.unshift(task)
    return taskId
  }

  const removeTask = (taskId) => {
    const idx = tasks.value.findIndex(t => t.id === taskId)
    if (idx !== -1) {
      tasks.value[idx].pollingStopped = true
      tasks.value.splice(idx, 1)
    }
  }

  const clearCompleted = () => {
    tasks.value = tasks.value.filter(t => t.status === 'pending' || t.status === 'generating')
  }

  const clearAll = () => {
    tasks.value.forEach(t => { t.pollingStopped = true })
    tasks.value = []
  }

  const startGeneration = async (fileData, difficulty, questionTypeCounts, totalCount) => {
    const taskId = addTask(fileData, difficulty, questionTypeCounts, totalCount)
    const task = tasks.value.find(t => t.id === taskId)
    if (!task) return

    updateTask(taskId, { status: 'generating', processMessage: '正在调用生成接口...' })

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

      // 优先使用 file_id（从多个可能的数据源获取）
      let fileId = task.fileId || fileData.id || fileData.fileId
      // 向量库的文件：真正的 file_id 可能嵌套在 sourceData 中
      if (!fileId && fileData.sourceData) {
        fileId = fileData.sourceData.metadata?.file_id || fileData.sourceData.file_id || fileData.sourceData.id
      }

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

      if (fileId) {
        params.file_id = Number(fileId)
        console.log(`[useTaskManager] 使用 file_id=${params.file_id} 调用生成接口`)
      } else if (task.filePath) {
        // 没有 file_id 时退回到 file_path + collection
        params.file_path = task.filePath
        params.collection = fileData.collectionName || 'public_kb'
        console.log('[useTaskManager] 使用 file_path + collection 调用生成接口')
      } else {
        updateTask(taskId, { status: 'failed', examStatus: 'FAILED', processMessage: '无法获取文件ID或文件路径' })
        return
      }

      updateTask(taskId, { processMessage: `请求生成 ${totalCount} 道题目...` })

      console.log('[useTaskManager] 生成请求参数:', JSON.stringify(params))

      const result = await examAPI.generateQuestions(params)

      let initialQuestions = null
      if (result?.data?.questions && Array.isArray(result.data.questions) && result.data.questions.length > 0) {
        initialQuestions = result.data.questions
      } else if (result?.questions && Array.isArray(result.questions) && result.questions.length > 0) {
        initialQuestions = result.questions
      } else if (result?.data && Array.isArray(result.data) && result.data.length > 0) {
        initialQuestions = result.data
      } else if (Array.isArray(result) && result.length > 0) {
        initialQuestions = result
      }

      if (initialQuestions) {
        updateTask(taskId, {
          status: 'completed',
          examStatus: 'COMPLETED',
          processMessage: `生成完成：共 ${initialQuestions.length} 题`,
          resultCount: initialQuestions.length
        })
        message.success(`${task.fileName}：生成 ${initialQuestions.length} 题成功`)
        return
      }

      updateTask(taskId, { processMessage: '任务已提交，正在等待处理结果...' })

      await pollFileStatus(taskId, task.fileId)
    } catch (err) {
      console.error(`[Task ${taskId}] 生成失败:`, err)
      updateTask(taskId, { status: 'failed', examStatus: 'FAILED', processMessage: `失败：${err.message || '未知错误'}` })
      message.error(`${task.fileName} 生成失败: ${err.message || '未知错误'}`)
    }
  }

  const pollFileStatus = async (taskId, fileId) => {
    const maxAttempts = 60
    let pollCount = 0
    let interval = 4000

    while (pollCount < maxAttempts) {
      const task = tasks.value.find(t => t.id === taskId)
      if (!task || task.pollingStopped) return

      pollCount++
      await new Promise(resolve => setTimeout(resolve, interval))

      if (pollCount % 4 === 0 && interval < 10000) {
        interval = Math.min(interval * 1.5, 10000)
      }

      const taskNow = tasks.value.find(t => t.id === taskId)
      if (!taskNow || taskNow.pollingStopped) return

      if (!fileId) {
        try {
          const checkRes = await questionAPI.getPendingQuestions()
          const checkQuestions = checkRes?.data?.data || checkRes?.data?.list || checkRes?.data || []
          if (Array.isArray(checkQuestions) && checkQuestions.length > 0) {
            updateTask(taskId, {
              status: 'completed',
              examStatus: 'COMPLETED',
              processMessage: `已生成 ${checkQuestions.length} 题（通过待审批列表获取）`,
            })
            message.success(`${taskNow.fileName}：已生成 ${checkQuestions.length} 题`)
            return
          }
        } catch (e) {
          // ignore
        }
        updateTask(taskId, { processMessage: `等待中 (${pollCount}s)...` })
        continue
      }

      try {
        const fileRes = await fileAPI.getFileDetail(fileId)
        const fileInfo = fileRes?.data?.data || fileRes?.data || null

        if (!fileInfo) {
          updateTask(taskId, { processMessage: `等待中 (${pollCount})...` })
          continue
        }

        const examStatus = fileInfo.examStatus || fileInfo.exam_status || ''
        const processMsg = fileInfo.processMessage || fileInfo.process_message || ''
        const processStepMsg = fileInfo.processStepMessage || fileInfo.process_step_message || ''

        // processStepMessage 展示生成过程中的步骤状态
        // processMessage 展示生成完成后的详细结果
        if (processStepMsg) {
          updateTask(taskId, { examStatus, processStepMessage: processStepMsg })
        }
        if (examStatus === 'GENERATED' || examStatus === 'COMPLETED' || examStatus === 'FAILED') {
          // 完成或失败时，展示完整的结果信息
          updateTask(taskId, { examStatus, processMessage: processMsg || processStepMsg || '处理完成' })
        } else {
          // 生成过程中，展示步骤状态
          updateTask(taskId, { examStatus, processMessage: processStepMsg || processMsg || `正在处理 (${pollCount})...` })
        }

        if (examStatus === 'FAILED') {
          updateTask(taskId, { status: 'failed', examStatus: 'FAILED', processMessage: processMsg || '生成失败' })
          message.error(`${taskNow.fileName} 生成失败: ${processMsg || 'RAG服务错误'}`)
          return
        }

        if (examStatus === 'GENERATED' || examStatus === 'COMPLETED') {
          let pendingQuestions = null
          try {
            const pendingRes = await questionAPI.getPendingQuestions()
            const allPending = pendingRes?.data?.data || pendingRes?.data?.list || pendingRes?.data || []
            if (Array.isArray(allPending) && allPending.length > 0) {
              const strFileId = String(fileId)
              pendingQuestions = allPending.filter(q => String(q.documentId || q.document_id || '') === strFileId)
              if (pendingQuestions.length === 0) {
                pendingQuestions = allPending.filter(q => {
                  const t = q.createdAt || q.created_at
                  return t && new Date(t) > new Date(Date.now() - 60000)
                })
              }
              if (pendingQuestions.length === 0) {
                pendingQuestions = allPending
              }
            }
          } catch (e) {
            // ignore
          }

          const count = pendingQuestions?.length || 0
          updateTask(taskId, {
            status: 'completed',
            examStatus: examStatus,
            // 使用接口返回的 processMessage（含题型统计、AI分析等完整结果）
            processMessage: processMsg || `生成完成：共 ${count} 题`,
            resultCount: count
          })
          if (count > 0) {
            message.success(`${taskNow.fileName}：成功生成 ${count} 题`)
          } else {
            message.info(`${taskNow.fileName}：任务完成，请刷新查看`)
          }
          return
        }
      } catch (err) {
        console.warn(`[Task ${taskId}] 轮询第${pollCount}次失败:`, err.message?.substring(0, 60))
        updateTask(taskId, { processMessage: `轮询等待 (${pollCount})...` })
      }
    }

    const finalTask = tasks.value.find(t => t.id === taskId)
    if (finalTask && finalTask.status === 'generating') {
      try {
        const checkRes = await questionAPI.getPendingQuestions()
        const checkQuestions = checkRes?.data?.data || checkRes?.data?.list || checkRes?.data || []
        if (Array.isArray(checkQuestions) && checkQuestions.length > 0) {
          let matched = checkQuestions
          if (fileId) {
            const strFileId = String(fileId)
            matched = checkQuestions.filter(q => String(q.documentId || q.document_id || '') === strFileId)
          }
          if (matched.length > 0) {
            updateTask(taskId, { status: 'completed', examStatus: 'COMPLETED', processMessage: `生成 ${matched.length} 题`, resultCount: matched.length })
            message.success(`${finalTask.fileName}：${matched.length} 题已可查看`)
            return
          }
        }
      } catch (e) { /* ignore */ }

      updateTask(taskId, { status: 'completed', examStatus: 'TIMEOUT', processMessage: '处理超时，请手动刷新查看' })
      message.info(`${finalTask.fileName}：处理时间较长，请手动刷新`)
    }
  }

  const updateTask = (taskId, updates) => {
    const idx = tasks.value.findIndex(t => t.id === taskId)
    if (idx !== -1) {
      tasks.value[idx] = { ...tasks.value[idx], ...updates, updatedAt: new Date().toLocaleTimeString() }
    }
  }

  return {
    tasks,
    activeTasks,
    completedTasks,
    hasActiveTasks,
    taskCount,
    addTask,
    removeTask,
    clearCompleted,
    clearAll,
    startGeneration,
    updateTask
  }
}