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

export function usePaperManagement() {
  const drafts = ref([])
  const publishedPapers = ref([])
  const loading = ref(false)
  const activeTab = ref('drafts')
  
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0
  })

  const publishDialogVisible = ref(false)
  const publishingPaperId = ref(null)
  const publishForm = reactive({
    deptIds: [],
    userIds: [],
    excludeUserIds: [],
    publishTime: null,
    deadline: null
  })
  const publishing = ref(false)

  const previewData = ref(null)
  const previewLoading = ref(false)
  const assignmentData = ref(null)

  const loadDrafts = async () => {
    loading.value = true
    try {
      const response = await examAPI.getAdminPapers()
      if (Array.isArray(response)) {
        drafts.value = response.filter(p => !p.published || p.status === 'draft')
        publishedPapers.value = response.filter(p => p.published || p.status === 'published')
      } else if (response && response.list) {
        drafts.value = (response.list || []).filter(p => !p.published || p.status === 'draft')
        publishedPapers.value = (response.list || []).filter(p => p.published || p.status === 'published')
        pagination.total = response.total || 0
      }
    } catch (error) {
      console.error('加载试卷列表失败:', error)
    } finally {
      loading.value = false
    }
  }

  const loadPublishedPapers = async () => {
    loading.value = true
    try {
      const response = await examAPI.getAdminPapers()
      if (Array.isArray(response)) {
        publishedPapers.value = response.filter(p => p.published || p.status === 'published')
      } else if (response && response.list) {
        publishedPapers.value = (response.list || []).filter(p => p.published || p.status === 'published')
        pagination.total = response.total || 0
      }
    } catch (error) {
      console.error('加载已发布试卷失败:', error)
    } finally {
      loading.value = false
    }
  }

  const deleteDraft = async (id) => {
    try {
      await examAPI.deleteAdminPaper(id)
      message.success('删除成功')
      loadDrafts()
    } catch (error) {
      console.error('删除草稿失败:', error)
      message.error('删除失败: ' + (error.message || '未知错误'))
    }
  }

  const openPublishDialog = (paperId) => {
    publishingPaperId.value = paperId
    publishForm.deptIds = []
    publishForm.userIds = []
    publishForm.excludeUserIds = []
    publishForm.publishTime = null
    publishForm.deadline = null
    publishDialogVisible.value = true
  }

  const closePublishDialog = () => {
    publishDialogVisible.value = false
    publishingPaperId.value = null
  }

  const confirmPublish = async () => {
    if (!publishingPaperId.value) return
    if (publishForm.deptIds.length === 0 && publishForm.userIds.length === 0) {
      message.warning('请至少选择一个目标部门或用户')
      return
    }

    publishing.value = true
    try {
      await examAPI.publishPaper(publishingPaperId.value, {
        deptIds: publishForm.deptIds,
        userIds: publishForm.userIds,
        excludeUserIds: publishForm.excludeUserIds,
        publishTime: publishForm.publishTime,
        deadline: publishForm.deadline
      })
      message.success('试卷发布成功')
      closePublishDialog()
      loadDrafts()
      loadPublishedPapers()
    } catch (error) {
      console.error('发布试卷失败:', error)
      message.error('发布失败: ' + (error.message || '未知错误'))
    } finally {
      publishing.value = false
    }
  }

  const revokePublishedPaper = async (paperId) => {
    try {
      await examAPI.revokePaper(paperId)
      message.success('已撤回试卷')
      loadDrafts()
      loadPublishedPapers()
    } catch (error) {
      console.error('撤回试卷失败:', error)
      message.error('撤回失败: ' + (error.message || '未知错误'))
    }
  }

  const viewPaperDetail = async (paper) => {
    previewLoading.value = true
    previewData.value = null
    assignmentData.value = null

    try {
      const [detailRes, assignmentRes] = await Promise.allSettled([
        examAPI.getAdminPaperDetail(paper.id || paper.paperId),
        examAPI.getPaperAssignment(paper.id || paper.paperId).catch(() => null)
      ])

      if (detailRes.status === 'fulfilled') {
        previewData.value = detailRes.value
      }
      if (assignmentRes.status === 'fulfilled' && assignmentRes.value) {
        assignmentData.value = assignmentRes.value
      }
    } catch (error) {
      console.error('获取试卷详情失败:', error)
      message.error('获取试卷详情失败')
    } finally {
      previewLoading.value = false
    }
  }

  const previewPaperWithDetails = async (params) => {
    previewLoading.value = true
    previewData.value = null
    try {
      const result = await examAPI.previewPaperWithDetails(params)
      previewData.value = result
      return result
    } catch (error) {
      console.error('预览试卷详情失败:', error)
      message.error('预览失败: ' + (error.message || '未知错误'))
      throw error
    } finally {
      previewLoading.value = false
    }
  }

  const clearPreview = () => {
    previewData.value = null
    assignmentData.value = null
  }

  return {
    drafts,
    publishedPapers,
    loading,
    activeTab,
    pagination,
    publishDialogVisible,
    publishingPaperId,
    publishForm,
    publishing,
    previewData,
    previewLoading,
    assignmentData,
    loadDrafts,
    loadPublishedPapers,
    deleteDraft,
    openPublishDialog,
    closePublishDialog,
    confirmPublish,
    revokePublishedPaper,
    viewPaperDetail,
    previewPaperWithDetails,
    clearPreview
  }
}
