import {computed} from 'vue';
import {useCacheStore} from "@/hooks/useCacheStore";
import {toast} from "@/uni_modules/uv-ui-tools/libs/function";
import {concernedUniversities, concernUniversity, removeConcernedUniversity} from "@/api/webApi/career-other";
import {universityDetail} from "@/api/webApi/collegemajor";
import {createEventHook, toValue} from "@vueuse/core";

export const useCollegeCollectionService = function (collegeRef) {
    const changeEvent = createEventHook()

    const {removeCache} = useCacheStore()
    const collected = computed(() => toValue(collegeRef).collected)
    let loading = false

    const handleToggle = async () => {
        if (loading) return toast('请稍候')
        try {
            loading = true
            const entity = toValue(collegeRef)
            const op = collected.value ? removeConcernedUniversity : concernUniversity
            await op({universityId: entity.id})
            entity.collected = !collected.value
            await changeEvent.trigger(entity.collected)

            // 需要清除当前院校的详情缓存才能更新收藏状态
            const payload = {code: entity.code}
            removeCache(universityDetail, payload)
            // 需要清除收藏列表的缓存才能更新收藏状态
            removeCache(concernedUniversities) // 不清楚目标，只能全清
        } finally {
            loading = false
        }
    }

    return {
        collected,
        onChange: changeEvent.on,
        handleToggle
    }
}