import { ModalEnum } from '@/common/constants/modalNameEnum';
import { inject, Ref, ref, SetupContext, watchEffect } from 'vue';


export function closeModal(modelName: ModalEnum, context?: SetupContext) {
    // 控制弹窗 flag
    const visible = ref<boolean>(false);
    const show = inject(modelName, ref<boolean>(false))
    watchEffect(() => {
        visible.value = show.value
    })
    /**
     * 取消弹窗
     */
    function cancel() {
        visible.value = false;
        show.value = false
    }
    // 组件关闭弹窗需要刷新列表数据
    function refresh() {
        context?.emit('refresh')
        cancel()

    }
    return { visible, cancel, refresh }
}
// 批量处理引入关闭弹窗逻辑
export function batchCloseMal(arr: ModalEnum[], context?: SetupContext) {
    // 控制每个关闭弹窗的flag
    type VisibleItem = Ref<boolean>
    interface CacheFunction {
        cancel: Function;
        refresh: Function;
    }
    // 缓存控制关闭弹窗的逻辑函数
    const cache = new Map<ModalEnum, CacheFunction>()
    // 控制弹窗flag 列表：此列表与 arr 的索引对应上
    const visibleList = ref<VisibleItem[]>([])
    arr.forEach(el => {
        const { visible, cancel, refresh } = closeModal(el, context)
        visibleList.value.push(visible)
        if (!cache.has(el)) {
            cache.set(el, { cancel, refresh })
        }
    })
    // 关闭弹窗
    function cancel(modalName: ModalEnum) {
        if (cache.has(modalName)) {
            cache.get(modalName)?.cancel()
        } else {
            console.warn('未找到关闭弹窗名：${modalName}')
        }
    }
    // 刷新页面
    function refresh(modalName: ModalEnum) {
        if (cache.has(modalName)) {
            cache.get(modalName)?.refresh()
        } else {
            console.warn('未找到关闭弹窗名：${modalName}')
        }
    }
    return { visibleList, cancel, refresh }
}

export { ModalEnum };
