import {computed, ref, watch, watchEffect} from 'vue'
import mxConst from "@/common/mxConst";
import {getExamMajors, getExamTypes} from "@/api/login";
import {useInjectFormData} from "@/pagesOther/pages/login/components/hooks/useFormDataInjection";

// useExamTypeService 主要阐述了examType,examMajor的联动关系
// 服务本身并没有区分业务场景，只是引用了组件的props.disabled来控制修改权限
export const useExamTypeService = function (props) {

    const [model] = useInjectFormData()
    const examTypeOptions = ref([])
    const examMajorOptions = ref([])
    const isModelCultural = computed(() => model.value.examType == mxConst.keyCulturalExamType)
    console.log(model.value, 111)
    // 这个watch主要是消除切换省份时getExamMajors会多触发一次
    // 如: 当前isModelCultural=true, 此时切换省份会触发getExamMajors查询
    watch(() => model.value.location, () => {
        if (props.disabled) return
        model.value.examType = ''
        model.value.examMajor = ''
    })

    watchEffect(async () => {
        // if (props.disabled) return
        // 必须提供有效的省份值，才能触发数据加载，
        // 所以useExamTypeService的核心也在于外部提供的proRefOrGetter
        const {location} = model.value
        console.log(1111, location)
        if (!location) return

        const res = await getExamTypes({location})
        console.log(res, model.value.examType)
        examTypeOptions.value = res.data.exam_type
        console.log(examTypeOptions.value.map(item => item.dictValue), model.value.examType)
        if (!examTypeOptions.value.map(item => item.dictValue).includes(model.value.examType)) {
            // 清空无效值
            console.log('清空无效值')
            model.value.examType = ''
            model.value.examMajor = ''
        }
    })

    watchEffect(async () => {
        if (props.disabled) return
        // 同上
        const {location, examType} = model.value
        if (!location || !examType) return
        // 只有职高对口升学才有考生专业的概念
        if (!isModelCultural.value) return model.value.examMajor = ''

        const res = await getExamMajors({location, examType})
        examMajorOptions.value = res.data
        if (examMajorOptions.value.every(op => op.code != model.value.examMajor)) {
            // 清空无效值
            model.value.examMajor = ''
        }
    })

    return {
        isModelCultural,
        examTypeOptions,
        examMajorOptions
    }
}