<!-- components/LoadingDialog.vue -->
<template>
    <teleport to="body">
        <div v-if="visible" class="loading-overlay">
            <div class="loading-dialog">
                <div class="loading-content">
                    <span class="loading-spinner"></span>
                    <p>{{ message }}</p>
                </div>
            </div>
        </div>
    </teleport>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
    modelValue: Boolean,
    message: {
        type: String,
        default: '加载中...'
    },
    timeout: {
        type: Number,
        default: 10000 // 10 秒超时
    }
})

const emit = defineEmits(['update:modelValue', 'timeout'])

const visible = ref(props.modelValue)

// 监听 v-model 控制显隐
watch(() => props.modelValue, (val) => {
    visible.value = val
    if (val) {
        startTimeout()
    }
})

let timer = null

// 启动超时定时器
function startTimeout() {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
        visible.value = false
        emit('update:modelValue', false)
        emit('timeout') // 触发超时事件
    }, props.timeout)
}

// 关闭时清除定时器
function close() {
    if (timer) {
        clearTimeout(timer)
        timer = null
    }
    visible.value = false
    emit('update:modelValue', false)
}

// 暴露给父组件使用
defineExpose({
    close
})
</script>

<style scoped>
.loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 2000;
}

.loading-dialog {
    background: white;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    min-width: 200px;
}

.loading-spinner {
    display: inline-block;
    width: 24px;
    height: 24px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #3498db;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

.loading-content p {
    margin-top: 10px;
    color: #333;
    font-size: 14px;
}
</style>