<script setup lang="ts">
import { computed } from 'vue'
import { getOnlinePreviewUrl } from '@/utils/util'

interface PreviewFileItem {
  url?: string
  name?: string
}

const props = defineProps<{
  item?: PreviewFileItem
  url?: string
  name?: string
}>()

const previewItem = computed<PreviewFileItem>(() => {
  return {
    url: props.item?.url || props.url || '',
    name: props.item?.name || props.name || '',
  }
})

const fileUrl = computed(() => previewItem.value.url || '')
const fileName = computed(() => previewItem.value.name || '')

const fileExtension = computed(() => {
  const cleanUrl = fileUrl.value.split('?')[0].split('#')[0].toLowerCase()
  const matches = cleanUrl.match(/\.([a-z0-9]+)$/)
  return matches?.[1] || ''
})

const previewType = computed(() => {
  if (['pdf', 'txt'].includes(fileExtension.value)) return 'embed'
  if (fileExtension.value === 'mp4') return 'video'
  if (fileExtension.value === 'mp3') return 'audio'
  if (['png', 'jpg', 'jpeg', 'gif', 'webp'].includes(fileExtension.value)) return 'image'
  if (['rar', 'zip'].includes(fileExtension.value)) return 'archive'
  return 'iframe'
})

const archiveIcon = computed(() => {
  if (fileExtension.value === 'rar') return '/center_resource/rar.png'
  if (fileExtension.value === 'zip') return '/center_resource/zip.png'
  return ''
})
</script>

<template>
  <el-card>
    <div class="preview-container">
      <iframe v-if="previewType === 'iframe'" :src="getOnlinePreviewUrl(fileUrl)" allowfullscreen>
        {{ fileName }}
      </iframe>

      <embed v-else-if="previewType === 'embed'" :src="fileUrl" />

      <video v-else-if="previewType === 'video'" controls>
        <source :src="fileUrl" />
      </video>

      <audio v-else-if="previewType === 'audio'" :src="fileUrl" controls />

      <img v-else-if="previewType === 'image'" :src="fileUrl" :alt="fileName" />

      <div v-else class="archive-container">
        <a :href="fileUrl" class="archive-link">
          <img v-if="archiveIcon" :src="archiveIcon" class="archive-icon" />
          {{ fileName || fileUrl }}
        </a>
        <div class="archive-tip">* 该文件格式暂不支持预览,可点击上方文件名下载</div>
      </div>
    </div>
  </el-card>
</template>

<style lang="scss" scoped>
.preview-container {
  width: 100%;
  height: 600px;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: stretch;
  min-height: 0;

  iframe,
  embed,
  video,
  img {
    flex: 1;
    width: 100%;
    height: 100%;
    display: block;
    border: 0;
  }

  img {
    display: block;
    object-fit: contain;
  }
}

.archive-container {
  width: 100%;
  border: 1px solid #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.archive-link {
  color: #aa1941;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.archive-icon {
  width: 100px;
  height: 100px;
  margin: auto;
}

.archive-tip {
  font-size: 14px;
  margin-top: 10px;
}
</style>
