<script setup>
import { ref, computed, watch } from "vue";
const props = defineProps({
  url: {
    type: String,
    required: true
  },
  mimeType: {
    type: String,
    default: ""
  },
  // 圖片/視頻的寬高
  width: {
    type: String,
    default: "100%"
  },
  height: {
    type: String,
    default: "500px"
  },
  // 圖片的 fit 模式
  fit: {
    type: String,
    default: "contain"
  }
});
const textContent = ref("");
const isLoading = ref(false);
const error = ref(null);
const fileType = computed(() => {
  const mime = props.mimeType.toLowerCase();
  if (mime.startsWith("image/")) return "image";
  if (mime.startsWith("video/")) return "video";
  if (mime.startsWith("audio/")) return "audio";
  if (mime === "application/pdf") return "pdf";
  if (mime.startsWith("text/") || mime === "application/json") return "text";
  if (mime.includes("word") || mime.includes("spreadsheet") || mime.includes("presentation") || mime.includes("excel") || mime.includes("powerpoint") || mime.includes("msword") || mime.includes("officedocument")) {
    return "office";
  }
  return "unknown";
});
const officeViewerUrl = computed(() => {
  if (fileType.value === "office") {
    return `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(props.url)}`;
  }
  return "";
});
const loadTextContent = async () => {
  if (fileType.value !== "text") return;
  isLoading.value = true;
  error.value = null;
  try {
    const response = await fetch(props.url);
    if (!response.ok) throw new Error("\u7121\u6CD5\u8F09\u5165\u6587\u4EF6");
    textContent.value = await response.text();
  } catch (e) {
    error.value = e instanceof Error ? e.message : "\u8F09\u5165\u5931\u6557";
  } finally {
    isLoading.value = false;
  }
};
watch(() => [props.url, fileType.value], () => {
  if (fileType.value === "text") {
    loadTextContent();
  }
}, { immediate: true });
</script>

<template>
    <div class="l-document-viewer">
        <!-- 圖片預覽 -->
        <q-img
            v-if="fileType === 'image'"
            :src="url"
            :fit="fit"
            :style="{ width, height }"
            spinner-color="primary"
        >
            <template #error>
                <div class="absolute-full flex flex-center bg-negative text-white">
                    無法載入圖片
                </div>
            </template>
        </q-img>

        <!-- 視頻預覽 -->
        <q-video
            v-else-if="fileType === 'video'"
            :src="url"
            :style="{ width, height }"
        />

        <!-- 音頻預覽 -->
        <audio
            v-else-if="fileType === 'audio'"
            :src="url"
            controls
            style="width: 100%"
        >
            您的瀏覽器不支援音頻播放
        </audio>

        <!-- PDF 預覽 -->
        <iframe
            v-else-if="fileType === 'pdf'"
            :src="url"
            :style="{ width, height, border: 'none' }"
            title="PDF Viewer"
        />

        <!-- 文字預覽 (txt, json 等) -->
        <div v-else-if="fileType === 'text'" class="text-viewer" :style="{ height }">
            <q-spinner v-if="isLoading" color="primary" size="3em" />
            <q-banner v-else-if="error" class="bg-negative text-white">
                {{ error }}
            </q-banner>
            <pre v-else class="text-content">{{ textContent }}</pre>
        </div>

        <!-- Office 文件預覽 -->
        <iframe
            v-else-if="fileType === 'office'"
            :src="officeViewerUrl"
            :style="{ width, height, border: 'none' }"
            title="Office Viewer"
        />

        <!-- 不支援的類型 -->
        <div v-else class="unsupported flex flex-center" :style="{ height }">
            <div class="text-center">
                <q-icon name="sym_r_description" size="64px" color="grey-5" />
                <div class="text-grey-7 q-mt-md">
                    不支援預覽此文件類型
                </div>
                <div class="text-caption text-grey-5">
                    {{ mimeType || "\u672A\u77E5\u985E\u578B" }}
                </div>
                <q-btn
                    class="q-mt-md"
                    color="primary"
                    icon="sym_r_download"
                    label="下載文件"
                    :href="url"
                    target="_blank"
                    outline
                />
            </div>
        </div>
    </div>
</template>

<style scoped>
.l-document-viewer{width:100%}.text-viewer{background:#f5f5f5;border-radius:4px;overflow:auto;padding:16px}.text-content{margin:0;white-space:pre-wrap;word-wrap:break-word;font-family:Consolas,Monaco,monospace;font-size:14px;line-height:1.5}.unsupported{background:#fafafa;border:1px dashed #e0e0e0;border-radius:8px}
</style>
