<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="80%"
    :show-close="true"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    class="video-preview-dialog"
    @close="handleClose"
  >
    <div class="video-container">
      <video
        ref="videoRef"
        :src="currentVideoUrl"
        class="video-player"
        controls
        autoplay
        controlslist="nodownload"
      ></video>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" type="danger" plain>关闭预览</el-button>
      </div>
    </template>
  </el-dialog>
</template>

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

// 当前视频URL
const currentVideoUrl = ref('')

// 弹窗标题
const dialogTitle = ref('视频预览')

// 弹窗显示状态
const dialogVisible = ref(false)

// DOM 引用
const videoRef = ref(null)

// 显示弹窗
const show = (options) => {
  if (!options || !options.url) {
    console.error('视频URL不能为空')
    return
  }
  
  currentVideoUrl.value = options.url
  dialogTitle.value = options.title || '视频预览'
  dialogVisible.value = true
}

// 关闭弹窗
const close = () => {
  dialogVisible.value = false
  // 延迟清空视频URL，避免视频元素销毁时的问题
  setTimeout(() => {
    if (!dialogVisible.value) {
      currentVideoUrl.value = ''
      dialogTitle.value = '视频预览'
    }
  }, 100)
}

// 键盘事件处理
const handleKeydown = (event) => {
  if (event.key === 'Escape' && dialogVisible.value) {
    close()
  }
}

// 监听弹窗关闭
const handleClose = () => {
  close()
}

// 监听弹窗显示状态，添加/移除键盘监听
watch(dialogVisible, (visible) => {
  if (visible) {
    document.addEventListener('keydown', handleKeydown)
  } else {
    document.removeEventListener('keydown', handleKeydown)
  }
})

// 组件卸载时清理
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})

// 对外暴露方法
defineExpose({
  show,
  close
})
</script>

<style scoped>
.video-preview-dialog :deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

.video-preview-dialog :deep(.el-dialog__body) {
  padding: 0;
  max-height: 70vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-container {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #000;
}

.video-player {
  width: 100%;
  max-height: 70vh;
  object-fit: contain;
  outline: none;
  display: block;
}

.video-preview-dialog :deep(.el-dialog__footer) {
  padding: 16px 20px;
  border-top: 1px solid #e4e7ed;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>