<template>
  <div class="h-full">
    <template v-if="type === 'office'">
      <iframe :src="`https://view.officeapps.live.com/op/view.aspx?src=${getFullUrl(url)}`" class="w-full h-full" frameborder='0'></iframe>
    </template>
    <template v-else-if="type === 'pdf'">
      <object type="application/pdf" :data="getFullUrl(url)" style="width: 100%; height: 100%;"></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-full" :src="getFullUrl(url)"></audio>
    </template>
    <template v-else-if="type === 'image'">
      <div class="bg-light-300 w-full h-full">
        <img class="object-contain w-full h-full" :src="getFullUrl(url)" />
      </div>
    </template>
    <el-result v-else-if="type === 'other'" icon="error" title="错误信息" sub-title="文件格式不支持">
    </el-result>
  </div>
</template>

<script setup>
const type = ref("");
const player = ref("");
const props = defineProps({
  url: ""
})

function getFullUrl(url) {
  if (!url) return '';
  return url.startsWith('http') ? url : window.GLOBAL_CONFIG.api + '/' + url
}

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

watch(
  () => props.url,
  (newValue, oldValue) => {
    if (newValue != "") {
      type.value = getFileType(newValue);
    } else {
      type.value = "other"
    }
  },
  { immediate: true }
);
</script>