<template>
  <div class="comp-only-office">
    <DocumentEditor
      v-if="config"
      id="fileEdit"
      :documentServerUrl="env.VITE_API_ONLYOFFICE_URL"
      :config="config"
      :events_onDocumentReady="loadedFun"
      :onLoadComponentError="errorFun"
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { DocumentEditor } from '@onlyoffice/document-editor-vue';

const env = import.meta.env;

// 支持DOCX XLSX PPTX PDF
interface Props {
  fileId: any;
  fileData: any;
  fileKey: any;
}

const props = withDefaults(defineProps<Props>(), {
  fileId: '',
  fileData: {},
  fileKey: '',
});

const config = ref<any>(null);

onMounted(() => {
  initFun();
});

const onDocumentReadyFun = () => {};

const onDocumentStateChangeFun = () => {
  // const documentEditor = window.DocEditor.instances['fileEdit'];
  // const connector = documentEditor.createConnector();
  // connector.callCommand(() => {
  //   const doc = Api.GetDocument();
  //   const allControls = doc.GetAllContentControls();
  //   for (let i = 0; i < allControls.length; i++) {
  //     const control = allControls[i];
  //     const tag = control.GetTag();
  //     const type = tag?.split('_')[0];
  //     const key = tag?.split('_')[1];
  //     if (type === 'text') {
  //       const value = control.GetDataForXmlMapping();
  //     } else if (type === 'table') {
  //       const paragraphs = control.GetContent().GetAllParagraphs();
  //       for (let i = 0; i < paragraphs.length; i++) {
  //         const paragraph = paragraphs[i];
  //       }
  //     } else if (type === 'img') {
  //       const images = control.GetParentParagraph().GetAllImages();
  //       for (let i = 0; i < images.length; i++) {
  //         const image = images[i].Image;
  //       }
  //     }
  //   }
  // });
};

const initFun = () => {
  const { url, fileType, fileName } = props.fileData;
  config.value = {
    type: 'desktop', // 桌面模式
    width: '100%',
    height: '100%',
    document: {
      title: fileName,
      url: url, // 文件地址
      fileType: fileType,
      key: props.fileKey,
      permissions: {
        // 操作权限
        download: true,
        edit: true,
        fillForms: true,
        print: true,
      },
    },
    editorConfig: {
      lang: 'zh-CN', // 语言
      callbackUrl: env.VITE_API_ONLYOFFICE_CALLBACK, // 保持回调地址
      customization: {
        anonymous: {
          request: false, // 不允许匿名编辑
        },
        autosave: false, // 自动保存
        forcesave: true, // 强制保存
      },
    },
    events: {
      onDocumentReady: onDocumentReadyFun,
      onDocumentStateChange: onDocumentStateChangeFun,
    },
  };
};

const loadedFun = () => {
  console.warn('文件加载完成');
};

const errorFun = () => {
  console.warn('文件加载失败');
};
</script>

<style lang="scss" scoped>
.comp-only-office {
  width: 100%;
  height: 100%;
}
</style>
