import {createEventHook, injectLocal, provideLocal} from "@vueuse/core";
import {getPaperKnowledges} from "@/api/dz/papers.js";
import {getKnowledgeTree, getKnowledgeTreeBatch} from "@/api/learn/knowledgeTree.js";
import {useInjectGlobalLoading} from "@/views/hooks/useGlobalLoading.js";
import {ElMessage} from "element-plus";

const key = Symbol('PaperKnowledgeCondition')
export const useProvidePaperKnowledgeCondition = function () {
    const knowledges = ref([])
    const knowledgeNode = ref(null) // 单选节点
    const knowledgeCheckNodes = ref([]) // 多选的节点
    const knowledgeIds = computed(() => knowledgeCheckNodes.value.map(k => k.id))
    const knowledgeId = computed(() => knowledgeNode.value?.id || '')
    const knowledgeRemoveEvent = createEventHook()
    const {loading} = useInjectGlobalLoading()
    const removeKnowledge = async (k) => {
        const nodes = knowledgeCheckNodes.value
        const idx = nodes.indexOf(k)
        if (idx > -1) {
            nodes.splice(idx, 1)
            await knowledgeRemoveEvent.trigger(k)
        }
    }

    // 一键清空所有知识点
    const clearAllKnowledge = () => {
        knowledgeCheckNodes.value = []
        knowledgeNode.value = null
    }

    // 批量添加知识点
    const batchAddKnowledge = async (knowledgeIdsStr) => {
        if (!knowledgeIdsStr || !knowledgeIdsStr.trim()) {
            ElMessage.warning('请输入知识点ID')
            return
        }

        // 解析知识点ID字符串，支持逗号、空格、换行等分隔符
        const ids = knowledgeIdsStr
            .split(/[,，\s\n]+/)
            .map(id => id.trim())
            .filter(id => id && !isNaN(Number(id)))
            .map(id => Number(id))

        if (ids.length === 0) {
            ElMessage.warning('请输入有效的知识点ID')
            return
        }

        loading.value = true
        try {
            // 获取已存在的知识点ID集合，避免重复添加
            const existingIds = new Set(knowledgeCheckNodes.value.map(k => k.id))
            
            // 过滤掉已存在的ID
            const newIds = ids.filter(id => !existingIds.has(id))
            
            if (newIds.length === 0) {
                ElMessage.warning('所有知识点已存在')
                return
            }

            // 批量查询知识点详情
            const res = await getKnowledgeTreeBatch(newIds)
            
            if (!res.data || res.data.length === 0) {
                ElMessage.warning('没有找到新的知识点，可能ID无效')
                return
            }

            // 过滤掉非叶子节点（有子节点的节点）
            const newKnowledgeNodes = res.data.filter(node => {
                return !node.children || node.children.length === 0
            })

            if (newKnowledgeNodes.length === 0) {
                ElMessage.warning('没有找到叶子节点知识点')
                return
            }

            // 追加到现有列表
            knowledgeCheckNodes.value = [...knowledgeCheckNodes.value, ...newKnowledgeNodes]
            ElMessage.success(`成功添加 ${newKnowledgeNodes.length} 个知识点`)
        } catch (error) {
            console.error('批量添加知识点失败:', error)
            ElMessage.error('批量添加知识点失败')
        } finally {
            loading.value = false
        }
    }

    const loadKnowledge = async function(payload) {
        loading.value = true
        try {
            const res = await getPaperKnowledges(payload)
            knowledges.value = res.data
        } finally {
            loading.value = false
        }
    }

    const payload = {
        knowledges, knowledgeNode, knowledgeId, knowledgeCheckNodes, knowledgeIds,
        removeKnowledge, loadKnowledge, clearAllKnowledge, batchAddKnowledge,
        onKnowledgeRemove: knowledgeRemoveEvent.on
    }
    provideLocal(key, payload)
    return payload
}
export const useInjectPaperKnowledgeCondition = function () {
    return injectLocal(key)
}