import { ref, computed, onUnmounted } from 'vue'
import { fileAPI } from '../../../api/file.js'
import { message } from 'ant-design-vue'

const POLL_CONFIG = {
  active: 3000,       // 单文件活跃任务: 3秒
  idle: 10000,        // 列表刷新: 10秒
  hidden: 30000,      // 页面隐藏: 30秒
  maxInterval: 30000,
  singleFileActive: 2000  // 单文件高频轮询: 2秒（更实时）
}

export function useUploadTasks() {
  const tasks = ref([])
  const statusFilter = ref('all')
  const searchQuery = ref('')
  const currentPage = ref(1)
  const pageSize = ref(10)

  let pollTimer = null
  let singleFilePollTimers = new Map()  // 单文件轮询定时器Map

  function parseVectorStatus(task) {
    const rawStatus = task.processStepStatus || ''
    const processMessage = task.processStepMessage || ''

    switch (rawStatus) {
      case 'UPLOADED':
        return { phase: 'vectorize', status: 'pending', label: '等待处理', color: 'pending', animating: false, rawStatus }
      case 'VECTORIZING':
        return { phase: 'vectorize', status: 'processing', label: '向量化中...', color: 'info', animating: true, rawStatus }
      case 'VECTORIZED':
        return { phase: 'vectorize', status: 'success', label: '向量化完成', color: 'success', animating: false, rawStatus }
      case 'EXAM_GENERATED':
      case 'COMPLETED':
        return { phase: 'vectorize', status: 'success', label: '全部完成', color: 'success', animating: false, rawStatus }
      case 'VECTORIZE_FAILED':
        return { phase: 'vectorize', status: 'error', label: '向量化失败', message: processMessage, color: 'error', animating: false, rawStatus }
      case 'EXAM_GENERATE_FAILED':
        return { phase: 'vectorize', status: 'success', label: '向量化完成', color: 'success', animating: false, rawStatus }
      default:
        return { phase: 'vectorize', status: 'unknown', label: '未知', color: 'pending', animating: false, rawStatus }
    }
  }

  function parseExamStatus(task) {
    const examStatus = task.examStatus || ''
    const processMessage = task.processMessage || ''
    const processStepStatus = task.processStepStatus || ''

    if (['UPLOADED', 'VECTORIZING', 'VECTORIZE_FAILED'].includes(processStepStatus)) {
      return { phase: 'exam', status: 'pending', label: '等待中', color: 'pending', animating: false, rawStatus: examStatus }
    }

    if (examStatus === 'GENERATING' || examStatus === 'EXAM_GENERATING') {
      return { phase: 'exam', status: 'processing', label: '出题中...', color: 'info', animating: true, rawStatus: examStatus }
    }

    if (['GENERATED', 'EXAM_GENERATED', 'COMPLETED'].includes(examStatus)) {
      const match = processMessage.match(/共(\d+)道题/)
      const count = match ? match[1] : ''
      return { phase: 'exam', status: 'success', label: count ? `生成${count}道题` : '出题完成', color: 'success', animating: false, rawStatus: examStatus }
    }

    if (examStatus === 'FAILED' || examStatus === 'EXAM_GENERATE_FAILED') {
      return { phase: 'exam', status: 'error', label: '出题失败', message: processMessage || '生成失败', color: 'error', animating: false, rawStatus: examStatus }
    }

    if (examStatus === 'UNGENERATED' || !examStatus) {
      return { phase: 'exam', status: 'pending', label: '等待中', color: 'pending', animating: false, rawStatus: examStatus }
    }

    return { phase: 'exam', status: 'unknown', label: '未知', color: 'pending', animating: false, rawStatus: examStatus }
  }

  function normalizeTask(raw) {
    return {
      id: raw.id,
      fileName: raw.fileName || raw.file_name || '',
      filePath: raw.filePath || raw.file_path || '',
      fileSize: raw.fileSize || raw.file_size || 0,
      fileType: raw.fileType || raw.file_type || '',
      extension: raw.extension || '',
      deptId: raw.deptId || raw.dept_id || '',
      deptName: raw.deptName || raw.dept_name || '',
      uploadUserId: raw.uploadUserId || raw.upload_user_id || '',
      uploadUserName: raw.uploadUserName || raw.upload_user_name || '',
      createTime: raw.createTime || raw.create_time || '',
      updateTime: raw.updateTime || raw.update_time || '',
      processStepStatus: raw.processStepStatus || raw.process_step_status || '',
      processStepMessage: raw.processStepMessage || raw.process_step_message || '',
      examStatus: raw.examStatus || raw.exam_status || '',
      processMessage: raw.processMessage || raw.process_message || '',
      auditStatus: raw.auditStatus || raw.audit_status || '',
      fileCategory: raw.fileCategory || raw.file_category || '',
      isPublic: raw.isPublic ?? raw.is_public ?? false
    }
  }

  function addTask(fileData) {
    const normalized = normalizeTask(fileData)
    const existingIdx = tasks.value.findIndex(t => t.id === normalized.id)
    if (existingIdx !== -1) {
      tasks.value[existingIdx] = { ...tasks.value[existingIdx], ...normalized }
    } else {
      tasks.value.unshift(normalized)
    }
  }

  /**
   * 判断任务是否需要高频单文件轮询
   * 条件：处于活跃处理阶段（UPLOADED/VECTORIZING/EXAM_GENERATING）
   */
  function needsSingleFilePolling(task) {
    const activeStatuses = ['UPLOADED', 'VECTORIZING', 'EXAM_GENERATING']
    return activeStatuses.includes(task.processStepStatus)
  }

  /**
   * 核心新功能：查询单个文件详情
   * 使用 GET /api/file/{id} 接口
   */
  async function fetchSingleTaskDetail(taskId) {
    const now = new Date().toLocaleTimeString('zh-CN', { hour12: false })
    
    try {
      console.log(`%c[TASK-DETAIL] ${now} | 查询文件 #${taskId} 详情...`, 
        'background: #8b5cf6; color: white; padding: 2px 6px; border-radius: 3px; font-weight: bold;')
      
      const res = await fileAPI.getFileDetail(taskId)
      const data = res?.data?.data || res?.data
      
      if (data) {
        addTask(data)
        
        const task = tasks.value.find(t => t.id === taskId)
        if (task) {
          const vs = parseVectorStatus(task)
          const es = parseExamStatus(task)
          
          const vectorIcon = vs.status === 'processing' ? '🔄' : vs.status === 'success' ? '✅' : vs.status === 'error' ? '❌' : '⏳'
          const examIcon = es.status === 'processing' ? '🔄' : es.status === 'success' ? '✅' : es.status === 'error' ? '❌' : '➖'
          
          console.log(
            `%c[TASK-DETAIL#${taskId}] %c${task.fileName}\n` +
            `  向量化: ${vectorIcon} ${vs.label} (${task.processStepStatus || '空'})\n` +
            `  出题:   ${examIcon} ${es.label} (${task.examStatus || '空'})\n` +
            `  消息:   ${task.processStepMessage || task.processMessage || '无'}`,
            'color: #8b5cf6; font-weight: bold;',
            'color: #333;'
          )
          
          // 如果任务已完成或失败，停止单文件轮询
          const terminalStatuses = ['COMPLETED', 'EXAM_GENERATED', 'VECTORIZE_FAILED', 'EXAM_GENERATE_FAILED']
          if (terminalStatuses.includes(task.processStepStatus)) {
            stopSingleFilePolling(taskId)
            console.log(`%c[TASK-DETAIL] ✅ 文件 #${taskId} 已完成，停止单文件轮询`, 
              'background: #10b981; color: white; padding: 2px 6px; border-radius: 3px;')
          }
          
          return task
        }
      }
    } catch (err) {
      console.error(`[TASK-DETAIL] 查询文件 #${taskId} 失败:`, err)
    }
    
    return null
  }

  /**
   * 启动单个文件的高频轮询
   */
  function startSingleFilePolling(taskId) {
    // 如果已经在轮询，不重复启动
    if (singleFilePollTimers.has(taskId)) {
      return
    }
    
    console.log(`%c[TASK-DETAIL] 🚀 启动文件 #${taskId} 高频轮询 (${POLL_CONFIG.singleFileActive}ms)`, 
      'color: #8b5cf6; font-weight: bold;')
    
    // 立即执行一次
    fetchSingleTaskDetail(taskId)
    
    // 设置定时器
    const timer = setInterval(() => {
      fetchSingleTaskDetail(taskId)
    }, POLL_CONFIG.singleFileActive)
    
    singleFilePollTimers.set(taskId, timer)
  }

  /**
   * 停止单个文件的轮询
   */
  function stopSingleFilePolling(taskId) {
    const timer = singleFilePollTimers.get(taskId)
    if (timer) {
      clearInterval(timer)
      singleFilePollTimers.delete(taskId)
      console.log(`[TASK-DETAIL] ⏹️ 停止文件 #${taskId} 轮询`)
    }
  }

  /**
   * 停止单文件轮询（内部使用）
   */
  function _stopSingleFilePollingInternal(taskId) {
    const timer = singleFilePollTimers.get(taskId)
    if (timer) {
      clearInterval(timer)
      singleFilePollTimers.delete(taskId)
    }
  }

  async function fetchTasks() {
    const now = new Date().toLocaleTimeString('zh-CN', { hour12: false })
    try {
      const res = await fileAPI.getFiles({ pageNum: 1, pageSize: 100 })

      const list = res?.data?.data?.list || res?.data?.list || res?.data?.records || []

      if (Array.isArray(list)) {
        list.forEach(item => addTask(item))

        console.log(`%c[TASK] ${now} | 共${tasks.value.length}个任务`, 'background: #667eea; color: white; padding: 2px 6px; border-radius: 3px; font-weight: bold;')

        tasks.value.forEach((task, idx) => {
          const vs = parseVectorStatus(task)
          const es = parseExamStatus(task)

          const vectorIcon = vs.status === 'processing' ? '🔄' : vs.status === 'success' ? '✅' : vs.status === 'error' ? '❌' : '⏳'
          const examIcon = es.status === 'processing' ? '🔄' : es.status === 'success' ? '✅' : es.status === 'error' ? '❌' : '➖'

          console.log(
            `%c[TASK#${idx + 1}] %c${task.fileName}\n` +
            `  向量化: ${vectorIcon} ${vs.label} (${task.processStepStatus || '空'})\n` +
            `  出题:   ${examIcon} ${es.label} (${task.examStatus || '空'})`,
            'color: #667eea; font-weight: bold;',
            'color: #333;'
          )

          // 自动为活跃任务启动单文件轮询
          if (needsSingleFilePolling(task) && !singleFilePollTimers.has(task.id)) {
            startSingleFilePolling(task.id)
          }
        })
      }
    } catch (err) {
      message.error('获取任务列表失败')
    }
  }

  function refreshTasks() {
    return fetchTasks()
  }

  const stats = computed(() => {
    const total = tasks.value.length
    let processing = 0
    let success = 0
    let failed = 0

    tasks.value.forEach(task => {
      const vs = parseVectorStatus(task)
      const es = parseExamStatus(task)

      if (vs.status === 'processing' || es.status === 'processing') {
        processing++
      } else if (vs.status === 'error' || es.status === 'error') {
        failed++
      } else if (vs.status === 'success' && (es.status === 'success' || es.status === 'pending')) {
        success++
      }
    })

    return { total, processing, success, failed }
  })

  const filteredTasks = computed(() => {
    let result = [...tasks.value]

    if (statusFilter.value !== 'all') {
      result = result.filter(task => {
        const vs = parseVectorStatus(task)
        const es = parseExamStatus(task)

        switch (statusFilter.value) {
          case 'processing':
            return vs.status === 'processing' || es.status === 'processing'
          case 'success':
            return vs.status === 'success' && (es.status === 'success' || es.status === 'pending')
          case 'failed':
            return vs.status === 'error' || es.status === 'error'
          case 'pending':
            return vs.status === 'pending' && es.status === 'pending'
          default:
            return true
        }
      })
    }

    if (searchQuery.value.trim()) {
      const query = searchQuery.value.trim().toLowerCase()
      result = result.filter(task =>
        (task.fileName || '').toLowerCase().includes(query) ||
        (task.deptName || '').toLowerCase().includes(query) ||
        (task.uploadUserName || '').toLowerCase().includes(query)
      )
    }

    return result
  })

  const paginatedTasks = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return filteredTasks.value.slice(start, end)
  })

  const totalFilteredPages = computed(() => {
    return Math.ceil(filteredTasks.value.length / pageSize.value.value) || 1
  })

  function shouldPoll() {
    return tasks.value.some(task => {
      const vs = parseVectorStatus(task)
      const es = parseExamStatus(task)
      return vs.animating || es.animating || needsSingleFilePolling(task)
    })
  }

  async function pollOnce() {
    await fetchTasks()
  }

  let currentInterval = POLL_CONFIG.idle
  let visibilityHandler = null

  function updatePollingStrategy() {
    const hasActiveTasks = shouldPoll()
    const isHidden = document.hidden
    const hasSingleFilePolling = singleFilePollTimers.size > 0

    let newInterval

    if (tasks.value.length === 0 && !hasSingleFilePolling) {
      newInterval = 0
    } else if (isHidden) {
      newInterval = POLL_CONFIG.hidden
    } else if (hasActiveTasks || hasSingleFilePolling) {
      newInterval = POLL_CONFIG.active
    } else {
      newInterval = POLL_CONFIG.idle
    }

    if (newInterval !== currentInterval) {
      const oldInterval = currentInterval
      currentInterval = newInterval

      const modeText = newInterval === 3000 ? '⚡高频' : newInterval === 2000 ? '⚡⚡超高频' : newInterval === 10000 ? '🔄中频' : newInterval === 30000 ? '💤低频' : '⏹️停止'
      console.log(`%c[TASK] 列表轮询: ${oldInterval}ms → ${newInterval}ms (${modeText}) | 单文件轮询: ${hasSingleFilePolling}个活跃`, 
        'color: #f59e0b; font-weight: bold;')

      stopPolling()

      if (newInterval > 0) {
        pollTimer = setInterval(pollOnce, newInterval)
      }
    }
  }

  function setupVisibilityListener() {
    if (visibilityHandler) return

    visibilityHandler = () => {
      updatePollingStrategy()
      
      // 页面隐藏时暂停单文件轮询，显示时恢复
      if (document.hidden) {
        singleFilePollTimers.forEach((timer, taskId) => {
          clearInterval(timer)
        })
        console.log(`[TASK-DETAIL] 💤 页面隐藏，暂停 ${singleFilePollTimers.size} 个单文件轮询`)
      } else {
        // 恢复单文件轮询
        tasks.value.forEach(task => {
          if (needsSingleFilePolling(task) && !singleFilePollTimers.has(task.id)) {
            startSingleFilePolling(task.id)
          }
        })
        console.log(`[TASK-DETAIL] 👁️ 页面可见，恢复单文件轮询`)
      }
    }

    document.addEventListener('visibilitychange', visibilityHandler)
  }

  function teardownVisibilityListener() {
    if (visibilityHandler) {
      document.removeEventListener('visibilitychange', visibilityHandler)
      visibilityHandler = null
    }
  }

  function startPolling() {
    stopPolling()

    updatePollingStrategy()
    setupVisibilityListener()

    console.log(`%c[TASK] ✅ 智能轮询已启动 (${currentInterval}ms)`, 'background: #10b981; color: white; padding: 2px 6px; border-radius: 3px; font-weight: bold;')
  }

  function stopPolling() {
    if (pollTimer) {
      clearInterval(pollTimer)
      pollTimer = null
    }

    teardownVisibilityListener()
    currentInterval = 0
    
    // 同时停止所有单文件轮询
    singleFilePollTimers.forEach((timer, taskId) => {
      clearInterval(timer)
    })
    singleFilePollTimers.clear()
  }

  onUnmounted(() => {
    stopPolling()
  })

  if (tasks.value.length > 0) {
    startPolling()
  }

  return {
    tasks,
    statusFilter,
    searchQuery,
    currentPage,
    pageSize,
    stats,
    filteredTasks,
    paginatedTasks,
    totalFilteredPages,
    parseVectorStatus,
    parseExamStatus,
    normalizeTask,
    addTask,
    fetchTasks,
    refreshTasks,
    shouldPoll,
    startPolling,
    stopPolling,
    // 新增导出
    fetchSingleTaskDetail,
    startSingleFilePolling,
    stopSingleFilePolling
  }
}
