import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { addTest } from '@/api/learn/test.js'
import { getPaperBatches } from '@/api/dz/papers.js'

/**
 * 批次和年份相关的公共逻辑
 * @param {Ref} batchId - 批次ID的ref
 * @param {Ref} batchList - 批次列表的ref
 * @returns {Object} 返回年份和批次相关的状态和方法
 */
export function useBatchYear(batchId, batchList) {
    // 年份相关
    const selectedYear = ref(null)
    
    // 从batchList中提取唯一的年份列表
    const yearList = computed(() => {
        const years = new Set()
        if (batchList.value && Array.isArray(batchList.value)) {
            batchList.value.forEach(b => {
                if (b && b.year) {
                    years.add(b.year)
                }
            })
        }
        return Array.from(years).sort((a, b) => b - a) // 降序排列
    })

    // 根据选中的年份过滤批次列表
    const filteredBatchList = computed(() => {
        if (!batchList.value || !Array.isArray(batchList.value)) {
            return []
        }
        if (!selectedYear.value) {
            return batchList.value
        }
        return batchList.value.filter(b => b && b.year === selectedYear.value)
    })

    // 监听年份列表变化，默认选择第一个年份
    watch(yearList, (years) => {
        if (years.length > 0 && !selectedYear.value) {
            selectedYear.value = years[0]
        }
    }, { immediate: true })

    // 监听年份变化，清空批次选择，然后选择第一个批次
    watch(selectedYear, async () => {
        batchId.value = null
        // 等待 filteredBatchList 更新后，选择第一个批次
        await nextTick()
        if (filteredBatchList.value.length > 0) {
            batchId.value = filteredBatchList.value[0].batchId
        }
    })

    // 监听过滤后的批次列表变化，默认选择第一个批次
    watch(filteredBatchList, (batches) => {
        if (batches.length > 0 && !batchId.value) {
            batchId.value = batches[0].batchId
        }
    }, { immediate: true })

    // 新增批次相关
    const batchDialogVisible = ref(false)
    const batchFormRef = ref(null)
    const batchSaving = ref(false)
    const batchForm = ref({
        year: null,
        name: ''
    })
    const batchRules = {
        year: [
            { required: true, message: '请输入年份', trigger: 'blur' }
        ],
        name: [
            { required: true, message: '请输入批次名称', trigger: 'blur' }
        ]
    }

    // 打开新增批次弹窗
    const handleAddBatch = () => {
        batchForm.value = {
            year: selectedYear.value || new Date().getFullYear(),
            name: ''
        }
        batchDialogVisible.value = true
    }

    // 保存批次
    const handleSaveBatch = async () => {
        if (!batchFormRef.value) return
        
        await batchFormRef.value.validate(async (valid) => {
            if (valid) {
                try {
                    batchSaving.value = true
                    await addTest({
                        year: batchForm.value.year,
                        name: batchForm.value.name
                    })
                    ElMessage.success('保存成功')
                    batchDialogVisible.value = false
                    
                    // 刷新批次列表
                    const res = await getPaperBatches()
                    batchList.value = res.data
                    
                    // 如果保存的年份是当前选中的年份，自动选中新创建的批次
                    if (batchForm.value.year === selectedYear.value) {
                        const newBatch = res.data.find(b => b.year === batchForm.value.year && b.name === batchForm.value.name)
                        if (newBatch) {
                            batchId.value = newBatch.batchId
                        }
                    } else {
                        // 如果保存的年份不是当前选中的年份，自动选中该年份
                        selectedYear.value = batchForm.value.year
                    }
                } catch (error) {
                    console.error('保存批次失败:', error)
                    ElMessage.error('保存失败')
                } finally {
                    batchSaving.value = false
                }
            }
        })
    }

    /**
     * 格式化批次名称（用于下拉框显示）
     * @param {Object} batch - 批次对象
     * @returns {String} 格式化后的批次名称
     */
    const formatBatchName = (batch) => {
        if (!batch || !batch.name) return '-'
        if (batch.year) {
            return `${batch.name}（${batch.year}）`
        }
        return batch.name
    }

    return {
        selectedYear,
        yearList,
        filteredBatchList,
        batchDialogVisible,
        batchFormRef,
        batchSaving,
        batchForm,
        batchRules,
        handleAddBatch,
        handleSaveBatch,
        formatBatchName
    }
}

