import {injectLocal, provideLocal} from "@vueuse/core";
import {useConditionPickType} from "@/components/mx-condition/modules/useConditionPickType";
import {useConditionCollegeFeatures} from "@/components/mx-condition/modules/useConditionCollegeFeatures";
import {useConditionCollegeType} from "@/components/mx-condition/modules/useConditionCollegeType";
import {useConditionCollegeNatureTypeCN} from "@/components/mx-condition/modules/useConditionCollegeNatureTypeCN";
import {useConditionCollegeLocation} from "@/components/mx-condition/modules/useConditionCollegeLocation";

const key = Symbol('VOLUNTARY_SEARCH')

export const useProvideVoluntarySearch = () => {

    const queryDefault = {
        majors: [],
        pickType: '',
        minScore: '',
        maxScore: '',
        sinoforeign: '',
        collect: '',
        specialProjectNation: '',
        specialProjectLocal: '',
        specialProjects: '',
        // props of university
        name: '',
        location: [],
        natureTypeCN: [],
        type: [],
        features: []
    }
    const queryParams = ref({})
    const formatQueryParams = () => {
        const vProps = ['majors', 'pickType', 'minScore', 'maxScore', 'sinoforeign', 'collect',
            'specialProjectNation', 'specialProjectLocal', 'specialProjects']
        const uProps = ['name', 'location', 'natureTypeCN', 'type', 'features']
        const input = toValue(queryParams)
        const output = {}
        vProps.forEach(p => output[p] = input[p])
        output.university = {}
        uProps.forEach(p => output.university[p] = input[p].toString())
        return output
    }

    const filter = ref({})
    const {dispatchCache} = useCacheStore()

    const {onSearch, conditions, reset: resetCore} = useProvideSearchModel([
        useConditionPickType(),
        // 因为填报里的数据是后触发的，所以需要配置isImmediate=true
        useConditionCollegeFeatures(computed(() => filter.value['features'])),
        useConditionCollegeType(computed(() => filter.value['types'])),
        useConditionCollegeNatureTypeCN(computed(() => filter.value['natureTypes'])),
        useConditionCollegeLocation(computed(() => filter.value['locations']))
    ], queryParams)

    const reset = () => {
        resetCore()
        queryParams.value = {
            ...queryDefault
        }
    }

    onMounted(async () => {
        const res = await dispatchCache(filters)
        filter.value = {...res.data} // 创建副本，防止不能正确触发searchModelService
    })

    const options = {
        queryParams,
        formatQueryParams,
        conditions,
        onSearch,
        reset
    }

    provideLocal(key, options)
    return options
}

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