import {ref, watch} from 'vue';
import {injectLocal, provideLocal, toValue} from "@vueuse/core";
import {useUserStore} from "@/hooks/useUserStore";
import {useCacheStore} from "@/hooks/useCacheStore";
import {cacheActions} from "@/hooks/defineCacheActions";
import {toast} from "@/uni_modules/uv-ui-tools/libs/function";
import {empty} from "@/uni_modules/uv-ui-tools/libs/function/test";

const key = Symbol('VOLUNTARY_DATA')
/*本来voluntary data在批次/计划/专业线都是通用的，理论上它应该是全局性的
* 但由于它和年份和当前用户相关，如果造成全局，year参数的影响性对开发者容易乎略
* 所以这里定义为依赖注入，缩小影响范围*/
export const useProvideVoluntaryData = function (yearRef) {
    const {currentUser, isLogin} = useUserStore()
    const {dispatchCache} = useCacheStore()

    const voluntaryData = ref({})

    const loadData = async () => {
        let payload = undefined
        if (yearRef) {
            const year = toValue(yearRef)
            if (!year) return
            payload = {year}
        }
        voluntaryData.value = await dispatchCache(cacheActions.getVoluntaryData, payload)
    }

    const validate = async (score, silence) => {
        if (empty(voluntaryData.value)) {
            return Promise.reject('VoluntaryData not be loaded.')
        }
        if (!score) {
            if (!silence) toast('请输入分数')
            return Promise.reject(false)
        }
        if (!/^[1-9]\d*$/.test(score)) {
            if (!silence) toast('分数必须为正整数')
            return Promise.reject(false)
        }
        if (score > voluntaryData.value.maxScore) {
            if (!silence) toast(`分数不能超过${voluntaryData.value.maxScore}`)
            return Promise.reject(false)
        }
        return true
    }

    const dependents = yearRef ? [currentUser, yearRef] : [currentUser]
    watch(dependents, () => isLogin.value && loadData(), {immediate: true})

    const options = {
        voluntaryData,
        validate
    }

    provideLocal(key, options)
    return options
}

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