import {createEventHook, injectLocal, provideLocal} from "@vueuse/core";
import {useProvidePaperBatchCondition} from "@/views/dz/papers/hooks/usePaperBatchCondition.js";
import {getPaperExamTypes, getPaperSubjects} from "@/api/dz/papers.js";

const key = Symbol('PaperFullCondition')
export const useProvidePaperFullCondition = function (type) {
    const {buildType, batchId, batchList, formatBatchName, getBatchDisplayName, onBatchReady} = useProvidePaperBatchCondition(type)

    const examType = ref('')
    const examTypes = ref([])

    const subjectId = ref('')
    const subjectList = ref([])
    const groupedSubjects = computed(() => {
        const groups = []
        subjectList.value.forEach(s => {
            const match = groups.find(g => g.label ==  s.groupName)
            if (!match) {
                groups.push({
                    label: s.groupName,
                    items: [s]
                })
            } else {
                match.items.push(s)
            }
        })
        return groups
    })

    const conditionArgs = computed(() => ({
        buildType: toValue(buildType),
        batchId: toValue(batchId),
        examType: toValue(examType),
        subjectId: toValue(subjectId)
    }))
    const conditionData = computed(() => ({
        batchList: toValue(batchList),
        examTypes: toValue(examTypes),
        subjectList: toValue(subjectList)
    }))
    const readyEvent = createEventHook()

    watch(batchId, async (batchId) => {
        examType.value = ''
        examTypes.value = []

        const res = await getPaperExamTypes({buildType, batchId})
        examTypes.value = res.data
    })
    watch([batchId, examType], async ([batchId, examType]) => {
        subjectId.value = ''
        subjectList.value = []

        if(!batchId || !examType) return
        const res = await getPaperSubjects({buildType, batchId, examType})
        subjectList.value = res.data
    })
    watch([batchId, examType, subjectId], async ([batchId, examType, subjectId]) => {
        if (!subjectId) return
        const payload = {buildType, batchId, examType, subjectId}
        await readyEvent.trigger(payload)
    })

    const payload = {buildType, batchId, batchList, formatBatchName, getBatchDisplayName, onBatchReady,
        examType, examTypes,
        subjectId, subjectList, groupedSubjects,
        conditionArgs, conditionData,
        onConditionReady: readyEvent.on}
    provideLocal(key, payload)
    return payload

}

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