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

const key = Symbol('PaperFullCondition')

export const useProvidePaperFullCondition = function () {
    const batchId = ref('')
    const batchList = ref([])

    const subjects = ref([])
    const subjectId = ref('')
    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 removeKnowledge = async (k) => {
        const nodes = knowledgeCheckNodes.value
        const idx = nodes.indexOf(k)
        if (idx > -1) {
            nodes.splice(idx, 1)
            await knowledgeRemoveEvent.trigger(k)
        }
    }

    const paperArgs = computed(() => ({
        batchId: toValue(batchId),
        batchName: batchList.value.find(b => b.batchId == batchId.value)?.name,
        subjectId: toValue(subjectId),
        subjectName: subjects.value.find(s => s.subjectId == subjectId.value)?.subjectName
    }))
    const payload = {
        batchId, batchList, subjectId, subjects,
        knowledges, knowledgeId, knowledgeNode, knowledgeCheckNodes, knowledgeIds,
        removeKnowledge, onKnowledgeRemove: knowledgeRemoveEvent.on,
        paperArgs
    }
    provideLocal(key, payload)

    onMounted(async () => {
        const res = await getPaperSubjects()
        subjects.value = res.data
        // 给一个默认值
        if (res.data.length) subjectId.value = res.data[0].subjectId
    })
    onMounted(async () => {
        const res = await getPaperBatches()
        batchList.value = res.data
    })
    watch(subjectId, async (subjectId) => {
        // 先清空以前的知识点
        knowledges.value = []
        knowledgeNode.value = null // 单选的情况
        knowledgeCheckNodes.value = [] // 多选的情况

        // 获取知识点数据
        const res = await getPaperKnowledges({subjectId})
        knowledges.value = res.data
    })
    return payload
}

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