import {computed, ref, watch} from 'vue';
import {injectLocal, provideLocal, toValue} from "@vueuse/core";
import {empty} from "@/uni_modules/uv-ui-tools/libs/function/test";
import {getVoluntaryHeaders} from "@/api/webApi/volunteer";
import {useInjectVoluntaryForm} from "@/pagesOther/pages/voluntary/hooks/useVoluntaryFormInjection";
import {useCacheStore} from "@/hooks/useCacheStore";
import {useInjectVoluntaryStep} from "@/pagesOther/pages/voluntary/hooks/useVoluntaryStepInjection";

const key = Symbol('VOLUNTARY_HEADER')

export const useProvideVoluntaryHeader = () => {
    const cols = ref([])
    const isMock = ref(undefined) // unset status
    const {dispatchCache} = useCacheStore()

    const historyYears = computed(() => {
        if (empty(cols.value)) return []
        return cols.value
            .filter(col => col.includes('&'))
            .map(col => col.split('&')[0])
    })
    const headerPlanYear = computed(() => {
        if (empty(cols.value)) return ''
        const suffix = '招生计划'
        const col = cols.value.find(col => col.endsWith(suffix))
        return col?.replace(suffix, '') || ''
    })

    const ensureHistoryYears = async (payload) => {
        const res = await dispatchCache(getVoluntaryHeaders, payload)
        cols.value = res.data
        isMock.value = res.isMock
    }

    const ensureHistoryYearsFromPageData = async (prevData) => {
        const {mode, detail: {year, isMock}} = prevData
        const headerPayload = {mode, year, isMock: isMock || false}
        await ensureHistoryYears(headerPayload)
    }

    const options = {cols, isMock, headerPlanYear, historyYears, ensureHistoryYears, ensureHistoryYearsFromPageData}
    provideLocal(key, options)
    return options
}

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