<template>
  <div class="docx-preview-container">
    <!-- 文档渲染的容器 -->
    <div ref="docxContainer" class="docx-preview"></div>
    <!-- 错误信息 -->
    <div v-if="error" class="docx-error">{{ error }}</div>
  </div>
</template>

<script>
import { renderAsync } from "docx-preview";

export default {
  props: {
    docxUrl: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      error: null, // 用于显示错误信息
    };
  },
  async mounted() {
    await this.loadDocx();
  },
  methods: {
    async loadDocx() {
      try {
        // 获取 .docx 文件的 ArrayBuffer
        const response = await fetch(this.docxUrl);
        if (!response.ok) {
          throw new Error(`无法加载文档：HTTP ${response.status}`);
        }
        const arrayBuffer = await response.arrayBuffer();

        // 渲染 .docx 文件到指定容器
        const container = this.$refs.docxContainer;
        await renderAsync(arrayBuffer, container); // 使用 docx-preview 渲染
      } catch (error) {
        console.error("加载 DOCX 文件失败:", error);
        this.error = "加载文档失败，请检查文件路径或格式。";
      }
    },
  },
};
</script>

<style>
.docx-preview-container {
  padding: 16px;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  overflow: auto;
  min-height: 200px;
  position: relative;
}

.docx-preview {
  font-family: Arial, sans-serif;
  color: #333;
}

.docx-error {
  color: red;
  text-align: center;
  margin-top: 16px;
}
</style>
