<template>
  <div>
    <div v-if="loading" class="page">
      <p>Loading...</p>
    </div>
    <section v-else class="page">
      <!-- 图片 -->
      <img v-if="isImageType" :src="mediaUrl" alt="media" class="media-item" />

      <!-- 视频 -->
      <video v-if="isVideoType" controls :src="mediaUrl" class="media-item">
        Your browser does not support the video tag.
      </video>

      <!-- 音频 -->
      <audio v-if="isAudioType" controls :src="mediaUrl" class="media-item">
        Your browser does not support the audio element.
      </audio>

      <!-- PDF -->
      <iframe v-if="isPdfType" :src="mediaUrl" type="application/pdf" width="100%" height="100%" class="media-item">
        <p>The PDF cannot be displayed, please <a :href="mediaUrl" target="_blank">click here</a> to download.</p>
      </iframe>

      <!-- 其他文件类型 -->
      <div v-if="isOtherType" class="media-item">
        <a :href="mediaUrl" target="_blank">{{mediaUrl ? 'Download File' : 'No File'}}</a>
      </div>
    </section>
  </div>
</template>

<script>
export default {
  layout: "blank_layout",
  data() {
    return {
      mediaUrl: "",
      fileExtension: "",
      loading: true,
      type: null,
    };
  },
  computed: {
    isImageType() {
      return this.type === 1 || this.type === 8 || this.isType(["jpg", "jpeg", "png", "gif", "bmp", "webp"]);
    },
    isVideoType() {
      return this.type === 5 || this.isType(["mp4", "webm", "ogg"]);
    },
    isAudioType() {
      return this.isType(["mp3", "wav", "ogg"]);
    },
    isPdfType() {
      return this.isType(["pdf"]);
    },
    isOtherType() {
      return !this.isImageType && !this.isVideoType && !this.isAudioType && !this.isPdfType;
    },
  },
  created() {
    this.$axios
      .get(`/uk-api/data/detail/${+this.$route.params.id}`)
      .then((response) => {
        const { media_url, type } = response.result;
        this.mediaUrl = media_url;
        this.type = type;
        const url = new URL(this.mediaUrl);
        this.fileExtension = url.pathname.split(".").pop().toLowerCase();
        this.loading = false;
      })
      .catch((error) => {
        console.error("Fail:", error);
        this.loading = false;
      });
  },
  methods: {
    isType(types) {
      return types.includes(this.fileExtension);
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.media-item {
  max-width: 100%;
  max-height: 100%;
  a {
    font-size: 20px;
    font-weight: 700;
  }
}
</style>
