import {getPaperBatches} from "@/api/dz/papers.js";
import {createEventHook, injectLocal, provideLocal} from "@vueuse/core";

const key = Symbol('PaperBatchCondition')

export const useProvidePaperBatchCondition = function (type, autoSelectFirst = false) {
    // 批次
    const buildType = type
    const batchId = ref('')
    const batchList = ref([])
    const batchEvent = createEventHook()
    let isInitialized = false

    onMounted(async () => {
        const res = await getPaperBatches()
        batchList.value = res.data
        
        // 如果启用自动选择且列表不为空，且是首次初始化，默认选中最新的第一个
        if (autoSelectFirst && batchList.value.length > 0 && !isInitialized && !batchId.value) {
            isInitialized = true
            // 按创建时间降序排序，选择最新的第一个
            const sorted = [...batchList.value].sort((a, b) => {
                const timeA = a.createTime || a.create_time || 0
                const timeB = b.createTime || b.create_time || 0
                return timeB - timeA
            })
            batchId.value = sorted[0].batchId
        }
    })
    watch(batchId, async (batchId) => {
        if (batchId) {
            const payload = {buildType, batchId}
            await batchEvent.trigger(payload)
        }
    })

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

    /**
     * 获取批次显示名称（batchName(year)）
     * @param {Object} row - 表格行数据
     * @returns {String} 批次显示名称
     */
    const getBatchDisplayName = (row) => {
        if (!row || !row.batchName) return '-'
        // 从 batchList 中查找对应的批次，获取年份
        const batch = batchList.value.find(b => b.batchId === row.batchId || b.name === row.batchName)
        if (batch && batch.year) {
            return `${row.batchName}（${batch.year}）`
        }
        return row.batchName
    }

    const payload = {buildType, batchId, batchList, formatBatchName, getBatchDisplayName, onBatchReady: batchEvent.on}
    provideLocal(key, payload)
    return payload
}

export const useInjectPaperBatchCondition = function () {
    return injectLocal(key)
}