<script setup>
import { getFullUrl } from '~/utils/helper';
import request from '~/utils/request';

const props = defineProps({
  url: String
})

const loading = ref(false)
const isLimit = ref(false)

function getFileType(str) {
  if (str) {
    str = str.toLocaleLowerCase()
    const ext = str.split('.').at(-1)
    if (['pdf'].includes(ext)) {
      return 'pdf'
    } else if (['mp4'].includes(ext)) {
      return 'video'
    } else if (['ppt', 'pptx', 'xls', 'xlsx', 'doc', 'docx'].includes(ext)) {
      getIsLimit()
      return 'office'
    } else if (['mp3'].includes(ext)) {
      return 'audio'
    } else if (['png', 'jpg', 'jpeg'].includes(ext)) {
      return 'image'
    }
    return 'other'
  }
  return 'other'
}

const type = getFileType(props.url)
console.log('file preview :>> ', type);


function getIsLimit(url) {
  loading.value = true
  request({
    url: '',
    data: {
      path_url: url
    }
  }).then(res => {
    if (res.code === '1') {
      isLimit.value = res.data.support_preview == 1
    }
    loading.value = false
  })
}
</script>

<template>
  <template v-if="type === 'office' && !loading">
    <iframe v-if="isLimit" :src="`https://view.officeapps.live.com/op/view.aspx?src=${getFullUrl(url)}`" width='100%'
      height='100%' frameborder='0'></iframe>
    <el-result v-else icon="error" title="错误信息" sub-title="文件过大，暂不支持在线预览，请下载">
    </el-result>
  </template>
  <template v-else-if="type === 'pdf'">
    <object type="application/pdf" :data="getFullUrl(url)" class="w-full h-full"></object>
  </template>
  <template v-else-if="type === 'video'">
    <video class="w-full h-full" :src="getFullUrl(url)" controls></video>
  </template>
  <template v-else-if="type === 'audio'">
    <audio class="w-full h-100px" :src="getFullUrl(url)" controls></audio>
  </template>
  <template v-else-if="type === 'image'">
    <div class="w-full h-full bg-light-300 flex_center">
      <!-- <img class="w-full object-contain" :src="getFullUrl(url)" /> -->
      <el-image class="w-full h-full" :src="getFullUrl(url)" :preview-src-list="[getFullUrl(url)]" fit="contain" />
    </div>
  </template>
  <el-result v-else-if="type === 'other'" icon="error" title="错误信息" sub-title="文件格式不支持">
  </el-result>
</template>
