import {createEventHook, injectLocal, provideLocal} from "@vueuse/core";
import {getPaperKnowledges} from "@/api/dz/papers.js";
import {useInjectGlobalLoading} from "@/views/hooks/useGlobalLoading.js";

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 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, onKnowledgeRemove: knowledgeRemoveEvent.on
    }
    provideLocal(key, payload)
    return payload
}
export const useInjectPaperKnowledgeCondition = function () {
    return injectLocal(key)
}