import { ref, computed } from 'vue'

export function useModal(isShow: boolean, delay: number) {
    // 显示隐藏
    const visible = ref(isShow);
    // 是否过渡动画中
    const animation = ref(true);
    // 动画类名
    const transitionClass = ref('');
    // 是否阻止鼠标事件
    const pointerEvents = ref(false);

    // 动画样式
    const transitionStyles = computed(() => ({
        transitionDuration: delay + 'ms',
        pointerEvents: pointerEvents.value ? 'none' : 'auto',
    }))

    // 动画切换
    const transition = (isShow: boolean, callback?: () => void) => {
        if (isShow) visible.value = true;
        window.setTimeout(() => {
            transitionClass.value = isShow ? 'is-show' : 'is-hide';
            // 阻止鼠标事件，防止动画过程中触发事件
            pointerEvents.value = true;
            window.setTimeout(() => {
                if (isShow) animation.value = false;
                pointerEvents.value = false;
                visible.value = isShow;
                callback && callback();
            }, delay);
        }, 20);
    }

    // 初始化
    if (isShow) {
        transition(true);
    }

    return {
        visible,
        animation,
        transitionClass,
        transitionStyles,
        transition,
    }
}