import _ from 'lodash';
import {VoluntaryData} from "@/types/vhs";
import {getVoluntaryData} from "@/api/modules/vhs";
import {useUserStore} from "@/store/userStore";
import {VHS_VOLUNTARY_DATA} from "@/types/injectionSymbols";

export const useProvideVoluntaryData = (yearRef: Ref<string> | null = null) => {
    // 如果页面有年份要求就必须传年份ref参数；
    // 如果不传，表示只关心最新年份的配置；

    const voluntaryData = ref<VoluntaryData>({} as VoluntaryData)
    const userStore = useUserStore()

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

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

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

    const options = {
        voluntaryData,
        validate
    }

    provide(VHS_VOLUNTARY_DATA, options)
    return options
}

export const useInjectVoluntaryData = () => {
    return inject(VHS_VOLUNTARY_DATA)
}