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

export function useQuestionBank() {
  const questions = ref([])
  // 搜索模式下的全量数据缓存（用于前端本地分页）
  const allQuestionsCache = ref([])
  const loading = ref(false)
  const isSearchMode = ref(false)   // 是否处于搜索/筛选状态
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0
  })

  const searchForm = reactive({
    keyword: '',
    type: '',
    difficulty: '',
    status: '',
    documentId: ''
  })

  const questionTypeOptions = [
    { value: '', label: '全部类型' },
    { value: 'single_choice', label: '单选题' },
    { value: 'multiple_choice', label: '多选题' },
    { value: 'true_false', label: '判断题' },
    { value: 'fill_blank', label: '填空题' },
    { value: 'subjective', label: '简答题' }
  ]

  const difficultyOptions = [
    { value: '', label: '全部难度' },
    { value: 1, label: '简单' },
    { value: 2, label: '中等' },
    { value: 3, label: '困难' }
  ]

  const statusOptions = [
    { value: '', label: '全部状态' },
    { value: 'pending', label: '待审核' },
    { value: 'approved', label: '已通过' },
    { value: 'rejected', label: '已驳回' }
  ]

  const fileOptions = ref([
    { value: '', label: '全部文件' }
  ])

  const loadFileList = async () => {
    try {
      const res = await fileAPI.getFiles({ current: 1, size: 200 })
      const wrapper = res?.data || res
      let list = []
      if (wrapper?.code === 200 && wrapper?.data?.records) {
        list = wrapper.data.records.filter(f => f.auditStatus !== 0)
      } else if (Array.isArray(wrapper)) {
        list = wrapper
      } else if (wrapper?.data) {
        const inner = wrapper.data
        list = Array.isArray(inner) ? inner : (inner?.list || inner?.records || inner?.data?.list || [])
      }

      if (list.length > 0) {
        fileOptions.value = [
          { value: '', label: '全部文件' },
          ...list.map(f => ({
            value: String(f.id),
            label: f.title || f.fileName || f.filename || ('文件-' + f.id)
          }))
        ]
      }
    } catch (err) {
      console.warn('[useQuestionBank] 加载文件列表失败:', err)
    }
  }

  const enrichQuestion = (q) => {
  let source = q
  if (q.data && (q.data.id || q.data.stem || q.data.content || q.data.options || q.data.answer)) {
    source = q.data
  }
  const content = source.content || source
  const rawOptions = source.options || content?.options || content?.choices ||
    content?.items || (content?.body?.options) || (content?.body?.choices) ||
    (content?.data?.options) || (content?.data?.choices) || []
  const rawAnswer = source.answer ?? content?.answer ?? content?.correct_answer ?? source.correctAnswer ?? null

  let options = []
  if (Array.isArray(rawOptions) && rawOptions.length > 0) {
    options = rawOptions.map((opt, i) => {
      if (typeof opt === 'string') return { key: String.fromCharCode(65 + i), text: opt, isCorrect: false }
      return { key: opt.key || opt.label || String.fromCharCode(65 + i), text: opt.text || opt.content || opt.value || '', isCorrect: !!opt.isCorrect || opt.is_correct || opt.correct || opt.is_right || false }
    })

    if (rawAnswer !== null && options.length > 0) {
      let answerKeys = []
      if (Array.isArray(rawAnswer)) {
        answerKeys = rawAnswer.map(a => String(a).toUpperCase().trim())
      } else {
        answerKeys = String(rawAnswer).toUpperCase().split(/[,，]/).map(s => s.trim())
      }
      options.forEach(opt => {
        opt.isCorrect = answerKeys.includes(opt.key)
      })
    }
  }

  return {
    id: q.questionId || q.question_id || q.id,
    type: q.questionType || q.type,
    stem: (content?.stem || q.stem || q.title || '无题干'),
    difficulty: q.difficulty ?? undefined,
    score: q.score,
    status: q.status || 'pending',
    createdAt: q.createdAt || q.created_at || q.generationTime || '-',
    answer: rawAnswer,
    options,
    content,
    sourceTrace: q.sourceTrace,
    documentId: q.documentId || '',
    documentName: q.documentName || ''
  }
}

const sortByPending = (arr) => {
  arr.sort((a, b) => {
    const aPending = (a.status || 'pending') === 'pending' ? 0 : 1
    const bPending = (b.status || 'pending') === 'pending' ? 0 : 1
    return aPending - bPending
  })
}

/** 判断当前是否处于搜索/筛选模式 */
function checkSearchMode() {
  return !!(
    (searchForm.keyword && searchForm.keyword.trim()) ||
    (searchForm.type) ||
    (searchForm.difficulty !== '' && searchForm.difficulty != null) ||
    (searchForm.status)
  )
}

/** 前端本地分页：从全量缓存中截取当前页数据 */
function applyLocalPagination() {
  if (!isSearchMode.value || allQuestionsCache.value.length === 0) return
  const start = (pagination.current - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  questions.value = allQuestionsCache.value.slice(start, end)
  pagination.total = allQuestionsCache.value.length
}

/** 搜索模式下切换页码（前端本地分页，不请求后端） */
const changeLocalPage = (page, size) => {
  if (!isSearchMode.value) {
    // 非搜索模式：走正常后端分页
    pagination.current = page
    if (size) pagination.pageSize = size
    loadQuestions()
    return
  }
  // 搜索模式：前端本地分页
  if (size) pagination.pageSize = size
  pagination.current = page
  applyLocalPagination()
}

const loadQuestions = async () => {
  loading.value = true

  // 判断是否搜索模式
  isSearchMode.value = checkSearchMode()

  const requestParams = {
    pageNum: 1,
    // 搜索模式加载全量数据用于前端分页
    pageSize: isSearchMode.value ? Math.max(pagination.pageSize * 20, 500) : pagination.pageSize,
    sortBy: 'status',
    sortOrder: 'asc'
  }
  if (searchForm.type) {
    requestParams.questionType = searchForm.type
  }
  if (searchForm.difficulty !== '' && searchForm.difficulty != null) {
    requestParams.difficulty = searchForm.difficulty
  }
  if (searchForm.status) {
    requestParams.status = searchForm.status
  }
  if (searchForm.documentId) {
    requestParams.documentId = searchForm.documentId
  }
  try {
    const res = await questionAPI.pageQuestions(requestParams)

    const raw = res?.data || res
    let list = []
    if (Array.isArray(raw)) {
      list = raw.map(enrichQuestion)
    } else {
      const rawData = raw?.data || raw
      const rawList = rawData?.list || rawData?.records || rawData?.questions || (Array.isArray(rawData) ? rawData : null)
      list = Array.isArray(rawList) ? rawList.map(enrichQuestion) : []
    }

    // documentId 过滤（始终在后端结果上二次过滤）
    if (searchForm.documentId) {
      list = list.filter(q => !q.documentId || String(q.documentId) === String(searchForm.documentId))
    }

    // 搜索关键词过滤（只保留匹配的题目）
    if (searchForm.keyword && searchForm.keyword.trim()) {
      const kw = searchForm.keyword.trim().toLowerCase()
      list = list.filter(q => matchKeyword(q, kw))
    }

    // 排序：pending 优先
    sortByPending(list)

    if (list.length > 0) {
      if (isSearchMode.value) {
        // ★ 搜索模式：缓存全量数据，前端本地分页
        allQuestionsCache.value = list
        applyLocalPagination()
      } else {
        // 正常模式：直接使用后端返回的分页数据
        questions.value = list
        pagination.total = Array.isArray(raw)
          ? list.length
          : (raw?.data?.total || raw?.data?.count || raw?.total || raw?.count || list.length)
      }
    } else {
      questions.value = []
      allQuestionsCache.value = []
      pagination.total = 0
    }
    } catch (error) {
    console.error('加载题目列表失败:', error)
    message.error('加载题目时发生错误: ' + (error.message || '未知错误'))
    questions.value = []
    allQuestionsCache.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

/** 判断题目是否匹配关键词（仅搜索题干 stem 字段） */
function matchKeyword(question, kw) {
  if (!kw) return false
  // 1. 检查 excludeStems 纯文本字段
  if (question.excludeStems && question.excludeStems.toLowerCase().includes(kw)) return true
  // 2. 仅检查 content JSON 中的 stem（题干）字段，不匹配选项/答案/解析
  if (question.content) {
    const c = typeof question.content === 'string'
      ? (function() { try { return JSON.parse(question.content) } catch(e) { return null } })()
      : question.content
    // 提取 stem 题干文本
    const stem = c?.stem || c?.title || c?.question || ''
    if (stem && String(stem).toLowerCase().includes(kw)) return true
  }
  // 3. 检查已 enrich 的 stem 字段（enrichQuestion 提取过一次）
  if (question.stem && String(question.stem).toLowerCase().includes(kw)) return true
  return false
}

  const handleSearch = () => {
    pagination.current = 1
    loadQuestions()
  }

  const handleReset = () => {
    searchForm.keyword = ''
    searchForm.type = ''
    searchForm.difficulty = ''
    searchForm.status = ''
    searchForm.documentId = ''
    handleSearch()
  }

  const handleTableChange = (pag) => {
    pagination.current = pag.current
    pagination.pageSize = pag.pageSize
    loadQuestions()
  }

  const handleDeleteQuestion = async (id) => {
    try {
      const res = await questionAPI.deleteQuestion(id)
      const response = res.data || res
      if (response.success !== false) {
        message.success('删除成功')
        loadQuestions()
      } else {
        message.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除题目失败:', error)
      message.error('删除题目时发生错误')
    }
  }

  return {
    questions,
    loading,
    pagination,
    isSearchMode,
    searchForm,
    questionTypeOptions,
    difficultyOptions,
    statusOptions,
    fileOptions,
    loadFileList,
    loadQuestions,
    handleSearch,
    handleReset,
    handleTableChange,
    handleDeleteQuestion,
    changeLocalPage
  }
}
