import {ref, computed} from 'vue';
import {injectLocal, provideLocal} from "@vueuse/core";
import {useCacheStore} from "@/hooks/useCacheStore";
import {cacheActions} from "@/hooks/defineCacheActions";

const key = Symbol('VOLUNTARY_MAJOR_HIGHLIGHT')

export const useProvideVoluntaryMajorHighlight = (readonly) => {
    const {dispatchCache} = useCacheStore()
    const checkedList = ref([])
    const formedMajors = ref({})
    const majorTree = ref([])

    const resetHighlight = () => {
        checkedList.value = []
        formedMajors.value = {}
    }

    const majorTreeChildren = computed(() => {
        // extend majorTree with children property. use name as key, and children as value.
        // put it here to avoid re-compute and re-build big-data instead of in InjectionMixin.
        const categoryMap = {}
        majorTree.value.forEach(category => {
            category.children.forEach(group => {
                categoryMap[group.name] = group.children.map(item => item.name)
            })
        })
        return categoryMap
    })

    const updateCheckedList = (conditionMajors) => {
        checkedList.value = conditionMajors
    }
    const snapshotSearchingMajorWhenApply = (major) => {
        // keep currentSearching if major selected, remove if not.
        if (major.selected) {
            if (isSearchingMajorFired(major)) {
                // make a copy of currentSearching, and keep it.
                return formedMajors.value[major.id] = [...checkedList.value]
            }
        }
        // remove it if exists.
        delete formedMajors.value[major.id]
    }
    const isSearchingMajorFired = (major) => {
        // 编辑模式下，列表的高亮即是表单的高亮（详情列表）
        if (readonly) return isFormedMajorFired(major)
        return checkedList.value.includes(major.marjorName) ||
            checkedList.value.some(item => majorTreeChildren.value[item]?.includes(major.marjorName))
    }
    const isFormedMajorFired = (major) => {
        return formedMajors.value[major.id]?.includes(major.marjorName) ||
            formedMajors.value[major.id]?.some(item => majorTreeChildren.value[item]?.includes(major.marjorName))
    }
    const ensureMajorFullTree = async (batch) => {
        const params = {level: 3, batch}
        majorTree.value = dispatchCache(cacheActions.getMajorTree, params)
    }
    const resolveFormedMajorsFromSavedData = (data) => {
        const formed = {}
        const highlighted = data.detail?.batch?.highlightMajorIds || []
        data.detail?.batch?.wishes?.forEach(group => {
            group.marjors.forEach(major => {
                // Do not use ===, id is not concerned with type of string or number
                if (highlighted.some(id => id == major.id)) {
                    formed[major.id] = [major.name]
                }
            })
        })
        formedMajors.value = formed
        return formed
    }

    const options = {
        checkedList, formedMajors, majorTree, majorTreeChildren,
        updateCheckedList,
        snapshotSearchingMajorWhenApply,
        isSearchingMajorFired,
        isFormedMajorFired,
        ensureMajorFullTree,
        resolveFormedMajorsFromSavedData,
        resetHighlight
    }
    provideLocal(key, options)
    return options
}

export const useInjectVoluntaryMajorHighlight = () => {
    return injectLocal(key)
}