import {ref, computed, watch} from 'vue'; import {injectLocal, provideLocal, toValue} from "@vueuse/core"; import {array, empty} from "@/uni_modules/uv-ui-tools/libs/function/test"; import {useUserStore} from "@/hooks/useUserStore"; import {zytbBatches} from "@/api/webApi/volunteer"; import {useCacheStore} from "@/hooks/useCacheStore"; const key = Symbol('VOLUNTARY_FORM') export const useProvideVoluntaryForm = function () { const {currentUser} = useUserStore() const {dispatchCache} = useCacheStore() const model = ref({ firstSubject: '', lastSubject: [], score: '', rank: {}, seatInput: '' }) const batch = ref({}) const batchList = ref([]) const courses = computed(() => { return getCourses(toValue(model)) }) const mode = computed(() => { return courses.value.toString() }) const simpleMode = computed(() => { if (courses.value.length === 1) return courses.value.toString() return courses.value.map(i => i.substring(0, 1)).join('') }) const getCourses = (modelVal) => { const results = [] const {firstSubject, lastSubject} = modelVal if (!empty(firstSubject)) results.push(firstSubject) if (!empty(lastSubject) && array(lastSubject)) results.push(...lastSubject) return results } const getMode = (modelVal) => { return getCourses(modelVal).toString() } const reloadScoreAndMode = async () => { const {mode, score, seatInput} = toValue(currentUser) const modeParams = mode?.split(',') || [] model.value.score = score || '' model.value.firstSubject = modeParams[0] model.value.lastSubject = modeParams.slice(1) || [] model.value.seatInput = (seatInput || 0) * 1 // This value may be changed by setRankByScore feature if (!score) model.value.seatInput = '' } const loadBatchList = async () => { const m = toValue(mode) const {score} = toValue(model) const res = await dispatchCache(zytbBatches, {mode: m, score}) batchList.value = res.rows } const getBatchList = async (modelVal) => { const m = getMode(modelVal) const {score} = modelVal const res = await dispatchCache(zytbBatches, {mode: m, score}) return res.rows } watch(currentUser, () => reloadScoreAndMode(), {immediate: true}) const options = { model, batch, batchList, mode, simpleMode, loadBatchList, getBatchList } provideLocal(key, options) return options } export const useInjectVoluntaryForm = function () { return injectLocal(key) }