<template>
  <div class="media-preview">
    <!-- 图片预览 -->
    <div v-if="type === 'image'" class="image-preview">
      <img
        :src="url"
        :alt="'图片预览'"
        @load="handleLoad"
        @error="handleError"
      />
      <div v-if="dimensions" class="image-info">
        {{ dimensions }}
      </div>
    </div>

    <!-- 视频预览 -->
    <div v-else-if="type === 'video'" class="video-preview">
      <video :src="url" controls>
        您的浏览器不支持视频播放
      </video>
    </div>

    <!-- 音频预览 -->
    <div v-else-if="type === 'audio'" class="audio-preview">
      <audio :src="url" controls>
        您的浏览器不支持音频播放
      </audio>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

// Props
interface Props {
  url: string
  type: 'image' | 'video' | 'audio'
}

const props = defineProps<Props>()

// Emits
interface Emits {
  (e: 'load', dimensions: string): void
  (e: 'error'): void
}

const emit = defineEmits<Emits>()

// 图片尺寸信息
const dimensions = ref('')

// 图片加载完成
const handleLoad = (event: Event) => {
  const img = event.target as HTMLImageElement
  if (img.naturalWidth && img.naturalHeight) {
    dimensions.value = `${img.naturalWidth} × ${img.naturalHeight}`
    emit('load', dimensions.value)
  }
}

// 图片加载错误
const handleError = () => {
  dimensions.value = ''
  emit('error')
}
</script>

<style scoped>
.media-preview {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.image-preview img {
  max-width: 100%;
  max-height: calc(100% - 20px);
  object-fit: contain;
}

.image-info {
  margin-top: 8px;
  font-size: 12px;
  color: var(--color-text-3);
}

.video-preview,
.audio-preview {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

video,
audio {
  max-width: 100%;
  max-height: 100%;
}
</style>
