<template>
  <div class="onlyoffice-container">
    <div id="placeholder" class="editor-placeholder"></div>
  </div>
</template>

<script>
import { getConfigAPI, generateCallbackTokenAPI } from '@/api/common/onlyOfficeViewer'
export default {
  name: 'OnlyOfficeViewer',
  props: {
    // 可以添加 props 来动态配置
    documentUrl: {
      type: String,
      default: 'http://192.168.0.14:9090/smart-bid/technicalSolutionDatabase/2025/11/03/716d9f3d89434c56bc49296dbbccc226.docx'
    },
    documentTitle: {
      type: String,
      default: '716d9f3d89434c56bc49296dbbccc226.docx'
    },
    documentKey: {
      type: String,
      default: '1'
    },
    fileName: {
      type: String,
      default: 'technicalSolutionDatabase/2025/11/03/716d9f3d89434c56bc49296dbbccc226.docx'
    },
    mode: {
      type: String,
      default: 'view', // 'view' 或 'edit'
      validator: (value) => ['view', 'edit'].includes(value)
    },
    type: {
      type: String,
      default: 'desktop', // 'desktop', 'mobile', 'embedded'
      validator: (value) => ['desktop', 'mobile', 'embedded'].includes(value)
    }
  },


  data() {
    return {
      docEditor: null,
      onlyOfficeScriptLoaded: false,
      editorConfig: {}
    };
  },
  created() {
    this.getConfig();
  },
  mounted() {
    this.initOnlyOffice();
  },

  beforeDestroy() {
    this.destroyEditor();
  },

  methods: {
    // 加载编辑器配置
    async getConfig() {
      try {
        const res = await getConfigAPI({
          fileId: this.documentKey,
          fileName: this.fileName,
          mode: this.mode,
          type: this.type
        })
        if (res.code !== 200) {
          throw new Error(res.msg || '获取编辑器配置失败');
        }
        if (!res.data) {
          throw new Error('配置数据为空');
        }
        

        this.editorConfig = res.data;
        this.$set(this.editorConfig, 'events', {
          onDocumentReady: this.onDocumentReady,
          onError: this.onEditorError,
          onAppReady: this.onAppReady
        });
        
        console.log('编辑器配置', this.editorConfig);

      }
      catch (error) {
        console.error('获取编辑器配置失败:', error);
        throw new Error('获取编辑器配置失败');
      }
    },

    /**
     * 初始化 OnlyOffice
     */
    async initOnlyOffice() {
      try {
        // 加载 OnlyOffice 脚本
        await this.loadOnlyOfficeScript();

        // 初始化编辑器
        this.initDocEditor();
      } catch (error) {
        console.error('初始化 OnlyOffice 失败:', error);
        this.$emit('error', error);
      }
    },

    /**
     * 加载 OnlyOffice 脚本
     */
    loadOnlyOfficeScript() {
      return new Promise((resolve, reject) => {
        // 如果已经加载，直接返回
        if (window.DocsAPI) {
          this.onlyOfficeScriptLoaded = true;
          resolve();
          return;
        }

        // 检查是否正在加载
        const existingScript = document.querySelector('script[data-onlyoffice]');
        if (existingScript) {
          existingScript.addEventListener('load', () => {
            this.onlyOfficeScriptLoaded = true;
            resolve();
          });
          existingScript.addEventListener('error', reject);
          return;
        }

        // 创建新的脚本元素
        const script = document.createElement('script');
        // onlyOfficeUrl 是 OnlyOffice 服务地址
        const onlyOfficeUrl = process.env.VUE_APP_ONLYOFFICE_URL;
        script.src = `${onlyOfficeUrl}/web-apps/apps/api/documents/api.js`;
        script.setAttribute('data-onlyoffice', 'true');

        script.onload = () => {
          this.onlyOfficeScriptLoaded = true;
          // 等待 API 完全初始化
          setTimeout(() => {
            if (window.DocsAPI) {
              resolve();
            } else {
              reject(new Error('OnlyOffice API 未正确加载'));
            }
          }, 100);
        };

        script.onerror = () => {
          reject(new Error('加载 OnlyOffice 脚本失败'));
        };

        document.head.appendChild(script);
      });
    },

    /**
     * 初始化文档编辑器
     */
    initDocEditor() {
      if (!window.DocsAPI) {
        console.error('DocsAPI 未加载');
        return;
      }

      try {
        this.docEditor = new window.DocsAPI.DocEditor("placeholder", this.editorConfig);
        this.$emit('initialized', this.docEditor);
      } catch (error) {
        console.error('创建 OnlyOffice 编辑器失败:', error);
        this.$emit('error', error);
      }
    },

    /**
     * 文档准备就绪回调
     */
    onDocumentReady() {
      console.log("文档准备好了");
      this.$emit('document-ready');
    },

    /**
     * 应用准备就绪回调
     */
    onAppReady() {
      console.log("OnlyOffice 应用准备就绪");
      this.$emit('app-ready');
    },

    /**
     * 编辑器错误回调
     */
    onEditorError(error) {
      console.error("OnlyOffice 错误:", error);
      this.$emit('error', error);
    },

    /**
     * 销毁编辑器
     */
    destroyEditor() {
      if (this.docEditor && typeof this.docEditor.destroy === 'function') {
        try {
          this.docEditor.destroy();
        } catch (error) {
          console.warn('销毁编辑器时出错:', error);
        }
      }
      this.docEditor = null;
    },

    /**
     * 重新加载文档
     */
    reloadDocument(newConfig = {}) {
      this.destroyEditor();

      // 可以在这里更新配置
      if (newConfig.documentUrl) {
        this.documentUrl = newConfig.documentUrl;
      }
      if (newConfig.documentTitle) {
        this.documentTitle = newConfig.documentTitle;
      }
      if (newConfig.mode) {
        this.mode = newConfig.mode;
      }

      // 等待 DOM 更新后重新初始化
      this.$nextTick(() => {
        this.initDocEditor();
      });
    }
  }
};
</script>

<style scoped>
.onlyoffice-container {
  width: 100%;
  height: 90vh;
  display: flex;
  flex-direction: column;
}

.editor-placeholder {
  width: 100%;
  height: 100vh;
  min-height: 600px;
}
</style>