<template>
    <div class="iframe-view">
        <!-- 可选的头部区域 -->
        <div v-if="showHeader && finalUrl" class="iframe-header">
            <span class="iframe-title">{{ title }}</span>
            <el-button 
                text 
                @click="refresh"
                :icon="RefreshCw"
            >
                刷新
            </el-button>
        </div>
        
        <iframe
            v-if="finalUrl"
            ref="iframeRef"
            :src="finalUrl"
            :key="iframeKey"
            class="iframe-content"
            :class="{ 'with-header': showHeader }"
            frameborder="0"
            allow="camera; microphone; fullscreen; display-capture; autoplay"
            allowfullscreen
            @load="handleLoad"
            @error="handleError"
        />
        <div v-else class="iframe-error">
            <AlertTriangle :size="48" class="error-icon" />
            <p>无效的 iframe 地址</p>
        </div>
        <div v-if="loading" class="iframe-loading">
            <Loader :size="32" class="is-loading" />
            <span>加载中...</span>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { Loader, AlertTriangle, RefreshCw } from 'lucide-vue-next'

interface Props {
    url?: string           // 直接传入的 URL（优先级高于 route.meta）
    title?: string         // 标题
    showHeader?: boolean   // 是否显示头部（带刷新按钮）
    timeout?: number       // 加载超时时间（毫秒），默认 10000
}

const props = withDefaults(defineProps<Props>(), {
    url: '',
    title: '',
    showHeader: false,
    timeout: 10000
})

const emit = defineEmits<{
    load: []
    error: [error: string]
}>()

const route = useRoute()
const loading = ref(true)
const iframeRef = ref<HTMLIFrameElement>()
const iframeKey = ref(0)
let loadTimeout: number | null = null

// 最终的 iframe URL（props.url 优先，否则从 route.meta 获取）
const finalUrl = computed(() => {
    return props.url || (route.meta.iframeUrl as string) || ''
})

function handleLoad() {
    clearLoadTimeout()
    loading.value = false
    console.log('[IframeView] iframe 加载完成')
    emit('load')
}

function handleError(e: Event) {
    clearLoadTimeout()
    loading.value = false
    console.error('[IframeView] iframe 加载错误:', e)
    emit('error', 'iframe 加载失败')
}

function clearLoadTimeout() {
    if (loadTimeout) {
        clearTimeout(loadTimeout)
        loadTimeout = null
    }
}

function startLoadTimeout() {
    clearLoadTimeout()
    // 设置超时，如果超时后仍在加载，则隐藏加载状态
    // 因为某些情况下 iframe 的 load 事件可能不会触发
    loadTimeout = window.setTimeout(() => {
        if (loading.value) {
            console.warn('[IframeView] iframe 加载超时，隐藏加载状态')
            loading.value = false
        }
    }, props.timeout)
}

// 刷新 iframe
function refresh() {
    if (iframeRef.value) {
        loading.value = true
        iframeKey.value++ // 通过改变 key 强制重新渲染 iframe
        startLoadTimeout()
    }
}

// 监听 URL 变化，重新加载
watch(finalUrl, (newUrl) => {
    if (newUrl) {
        loading.value = true
        iframeKey.value++ // 强制重新渲染
        startLoadTimeout()
        console.log('[IframeView] URL 变化，重新加载:', newUrl)
    }
})

// 暴露方法供外部调用
defineExpose({
    refresh
})

onMounted(() => {
    console.log('[IframeView] 加载 iframe:', finalUrl.value)
    if (finalUrl.value) {
        startLoadTimeout()
    }
})

onUnmounted(() => {
    clearLoadTimeout()
})
</script>

<style lang="scss" scoped>
.iframe-view {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.iframe-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    background: var(--el-bg-color);
    border-bottom: 1px solid var(--el-border-color-light);
    flex-shrink: 0;
    
    .iframe-title {
        font-size: 16px;
        font-weight: 500;
        color: var(--el-text-color-primary);
    }
}

.iframe-content {
    width: 100%;
    height: 100%;
    border: none;
    flex: 1;
    
    &.with-header {
        height: calc(100% - 49px);
    }
}

.iframe-error {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: var(--el-text-color-secondary);
    
    .error-icon {
        font-size: 48px;
        margin-bottom: 16px;
        color: var(--el-color-warning);
    }
}

.iframe-loading {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: var(--el-bg-color);
    gap: 12px;
    
    .is-loading {
        animation: rotating 1.5s linear infinite;
        color: var(--el-color-primary);
    }
}

@keyframes rotating {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}
</style>
