import {ref} from 'vue';
import {toast} from "@/uni_modules/uv-ui-tools/libs/function";
import {useCacheStore} from "@/hooks/useCacheStore";
import {getAIRenderRules} from "@/api/webApi/ie-voluntary";

export const useAIRenderRules = function (paramFactory) {
    const renderRuleLoading = ref(false)
    const renderRules = ref([])
    const {dispatchCache, removeCache} = useCacheStore()

    const reloadRenderRules = async () => {
        const params = paramFactory()
        if (!params) return console.error('please implement `paramFactory`')
        renderRuleLoading.value = true
        try {
            const res = await dispatchCache(getAIRenderRules, params)
            renderRules.value = res.data
        } finally {
            renderRuleLoading.value = false
        }
    }

    const validateRenderRule = async () => {
        if (!renderRules.value.length) {
            if (!renderRuleLoading.value) {
                const params = paramFactory()
                if (params) removeCache(getAIRenderRules, params)
                await reloadRenderRules()
            }
            const err = `请稍候，正在获取志愿规则信息...`
            toast(err)
            return Promise.reject(err)
        }
    }

    return {
        renderRuleLoading,
        renderRules,
        reloadRenderRules,
        validateRenderRule
    }
}