<!--onlyoffice 编辑器-->
<template>
  <div style="height:100%;width:100%" v-loading="loading">
    <div class="menu_btn">
      <el-button size="small" type="primary" @click="saveNewFile">保存新文件</el-button>
    </div>
    
    <div id='vabOnlyOffice' v-if="show"></div>
    <addNewFile ref="addNewFile"></addNewFile>
  </div>
 
</template>

<script>
import addNewFile from './addNewFile.vue'
import mixins from './index.js'
  export default {
    name: 'VabOnlyOffice',
    components:{
      addNewFile
    },
    mixins:[mixins],
    props: {
      option: {
        type: Object,
        default: () => {
          return {}
        },
      },
    },
    data() {
      return {
        doctype: '',
        docEditor: null,
        loading:false,
        show:true,
        currentVersion:{},
        historyData:[]
      }
    },
    beforeDestroy() {
      if (this.docEditor !== null) {
        this.docEditor.destroyEditor();
        this.docEditor = null;
      }
   },
    watch: {
      // option: {
      //   handler: function(n) {
      //     this.setEditor(n)
      //     this.doctype = this.getFileType(n.fileType)
      //   },
      //   deep: true,
      // },
    },
    mounted() {
      if (this.option.url) {
        this.setEditor(this.option)
      }
    },
    methods: {
      async insetText(){
        console.log(this.docEditor,this.docEditor.connector())
        return
        // document.execCommand('insertText', true, '插入的文本')
        // return
        // this.docEditor.blurFocus('要复制的文本内容')
        // this.setClipboardText('要复制的文本内容').then(() => {
        //   console.log('复制成功');
        //   document.execCommand('paste');
        //   console.log(document.execCommand('paste'))
        // }).catch(err => {
        //   console.error('复制失败', err);
        // })
        // await navigator.clipboard.writeText('插入的文本')
        // var dom = Api.createParagraph();
        //   dom.addText('插入的文本')
        var connector = this.docEditor.createConnector()
        console.log(connector)
        connector.callCommand(function(){
          var dom = Api.createParagraph();
          dom.addText('插入的文本')
        },function(){
          console.log('123')
        })
        console.log(window.AscEmbed.initWorker)
        window.Asc.plugin.callCommand(function() {
          var oWorksheet = Api.createParagraph();
          oWorksheet.addText('插入的文本')
        }, true);
       
      },
      setClipboardText(text) {
        return new Promise((resolve, reject) => {
          const clipboard = navigator.clipboard;
          if (clipboard && clipboard.writeText) {
            clipboard.writeText(text)
              .then(() => resolve())
              .catch(error => reject(error));
          } else {
            const textArea = document.createElement('textarea');
            textArea.value = text;
            // 防止元素显示在屏幕上
            textArea.style.position = 'fixed';
            textArea.style.top = '0';
            textArea.style.left = '0';
            textArea.style.width = '2em';
            textArea.style.height = '2em';
            textArea.style.padding = '0';
            textArea.style.border = 'none';
            textArea.style.outline = 'none';
            textArea.style.boxShadow = 'none';
            textArea.style.background = 'transparent';
            document.body.appendChild(textArea);
            textArea.select();
        
            try {
              const successful = document.execCommand('copy');
              successful ? resolve() : reject();
            } catch (err) {
              reject(err);
            }
        
            document.body.removeChild(textArea);
          }
        });
      },

      async setEditor(option) {
        if (this.docEditor !== null) {
          this.docEditor.destroyEditor();
          this.docEditor = null;
        }
        var params = {
          guid:this.option.id,
        }
        await this.$api.getCurrentVersionData(params).then(response=>{
          if(response.code == 200){
            if(response.data && response.data.fileType){
              var obj = response.data
              this.option.fileType=obj.fileType,
              this.option.key=obj.key,
              this.option.version = obj.version
              this.option.url=this.$c.url+ (this.$c.env=='production'?'/api':'')+'/fileManager/downloadFile?fileId=' +obj.url
            }
          }
        })
        this.doctype = this.getFileType(option.fileType)
        var user={
          id:option.user.id,
          name:option.user.name
        }
        let config = {
          document: {
            //后缀
            fileType: option.fileType,
            key: option.key ||'',
            title: option.title,
            permissions: {
              edit: option.isEdit,//是否可以编辑: 只能查看，传false
              print: option.isPrint,
              download: true,
              fillForms: true,//是否可以填写表格，如果将mode参数设置为edit，则填写表单仅对文档编辑器可用。 默认值与edit或review参数的值一致。
              review: true, //跟踪变化
              comment:true,//是否可以注释文档
              copy:true,
              chat: true,
            },
            url: option.url,
          },
          documentType: this.doctype,
          editorConfig: {
            // callbackUrl: 'http://192.168.2.24:8803/Test/TestQuery',//"编辑word后保存时回调的地址，这个api需要自己写了，将编辑后的文件通过这个api保存到自己想要的位置
            callbackUrl: `http://192.168.2.103:5000/onlyOffice/callback?guid=${option.id}&fileName=${option.title}&created=${option.created}&user=${JSON.stringify(user)}&previousVersion=${option.version}`,//"编辑word后保存时回调的地址，这个api需要自己写了，将编辑后的文件通过这个api保存到自己想要的位置
            lang: option.lang,//语言设置
            //定制
            customization: {
              comments:true,
              about:false,
              autosave: true,//是否自动保存
              forcesave:true,
              
              help: false,
              // "hideRightMenu": false,//定义在第一次加载时是显示还是隐藏右侧菜单。 默认值为false
              //是否显示插件
              plugins: false,
              // "about": true,
              // "feedback": false
              // customer:{
              //   logo:'https://www.xsip.cn/api/fileManager/downloadFile?fileId=9ba11d7c72d24387a8cb2f484c23e0a5',
              //   address:'',
              //   info:'',
              //   logoDark:'https://www.xsip.cn/api/fileManager/downloadFile?fileId=9ba11d7c72d24387a8cb2f484c23e0a5',
              //   mail:'',
              //   name:'',
              //   www:'',
              // },
              logo: {
              //   image: "https://www.xsip.cn/api/fileManager/downloadFile?fileId=9ba11d7c72d24387a8cb2f484c23e0a5",
              //   imageDark: "https://www.xsip.cn/api/fileManager/downloadFile?fileId=9ba11d7c72d24387a8cb2f484c23e0a5",
              //   url: "",
                visible: false,
              },
            },
            user:user,
            mode:option.model?option.model:'edit',
            // "canCoAuthoring": true
          },
          events:{
            onRequestHistory:this.onRequestHistory,//获取历史记录
            onRequestHistoryData:this.onRequestHistoryData,//获取历史文件
            onRequestRestore:this.onRequestRestore,//恢复
            onRequestHistoryClose:this.onRequestHistoryClose,//关闭历史
          },
          width: '100%',
          height: '100%',
          // token:option.token||'',
          // frameEditorId: "vabOnlyOffice",
          // parentOrigin: window.location.origin,
          // type: "desktop"
        }
        if(!config.token){
          //获取token并赋值
          var data = {
            jsons:JSON.stringify(config)
          }
          this.loading = true
          await this.$api.GetJWT(data).then(response=>{
            if(response.code == 200){
              config.token = response.data
              this.option.token = response.data
              this.loading = false
            }
          }).catch(error=>{
            this.loading  = false
          })
          // config.token = this.getJWT(config)
         
        }
       
        // eslint-disable-next-line no-undef,no-unused-vars
        this.docEditor = new DocsAPI.DocEditor('vabOnlyOffice', config)

      },
      async onRequestHistory(event){
        var params = {
          guid:this.option.id
        }
        var that = this
        await this.$api.queryFileVersion(params).then(response=>{
          if(response.code == 200){
            that.currentVersion = response.data.currentVersion
            that.historyData = response.data.history
          }
        })
        
        if(this.historyData.length == 0 || !this.currentVersion){
          that.docEditor.refreshHistory({
            currentVersion:'',
            history:[]
          })
          return
        }
        var currentVersion = this.currentVersion.currentVersion
        this.option.version = currentVersion
        var history = []
        for(var i = 0;i<that.historyData.length;i++){
          var item = that.historyData[i]
            history.push(
                {
                  serverVersion:item.serverVersion,
                  // changes:item.changes,
                  created:item.created,
                  user:item.user,
                  version:item.version,
                  key:item.key,
                }
              )
        }
        history.reverse()
        this.docEditor.refreshHistory(
          {
            currentVersion:currentVersion,
            history:history
          }
        )
        return
      },
      async onRequestHistoryData(event){
        const version = event.data
        var obj = this.historyData.find(item=>{
          return item.version == version
        })
        if(obj){
          var obj1 = null
          if(obj.previousVersion){
            obj1 = this.historyData.find(item=>{
              return item.version == obj.previousVersion
            })
          }
          var obj2 = {
            fileType:obj.fileType,
            key:obj.key,
            url:this.$c.url+ (this.$c.env=='production'?'/api':'')+'/fileManager/downloadFile?fileId=' +obj.url,
            version:obj.version,
            // previous:obj1?{
            //   fileType:obj1.fileType,
            //   key:obj1.key,
            //   url:this.$c.url+ (this.$c.env=='production'?'/api':'')+'/fileManager/downloadFile?fileId=' +obj1.url,
            // }:null,
            // changesUrl:obj.changesUrl?(this.$c.url+ (this.$c.env=='production'?'/api':'')+'/fileManager/downloadFile?fileId=' +obj.changesUrl):""
          }
          var params = {
            jsons:JSON.stringify(obj2)
          }
          this.loading = true
          await this.$api.GetJWT(params).then(response=>{
            if(response.code == 200){
              obj2.token = response.data
              this.option.token = response.data
              this.loading = false
            }
          }).catch(error=>{
            this.loading  = false
          })
          this.docEditor.setHistoryData(obj2)
          }
      },
      //恢复
      onRequestRestore(event){
        const version = event.data.version
        var params = {
          userId:this.option.user.id,
          userName:this.option.user.name,
          restoreVersion:version,
          previousVersion:this.option.version,
          guid:this.option.id
        }
        this.$api.restoreVersion(params).then(response=>{
          if(response.code == 200){
            this.setEditor(this.option)
          }
        })
      },
      onRequestHistoryClose(event){
        this.setEditor(this.option)
      },
      getFileType(fileType) {
        let docType = ''
        let fileTypesDoc = [
            'doc', 'docm', 'docx', 'dot', 'dotm', 'dotx', 'epub', 'fodt', 'htm', 'html', 'mht', 'odt', 'ott', 'pdf', 'rtf', 'txt', 'djvu', 'xps',
        ]
        let fileTypesCsv = [
            'csv', 'fods', 'ods', 'ots', 'xls', 'xlsm', 'xlsx', 'xlt', 'xltm', 'xltx',
        ]
        let fileTypesPPt = [
            'fodp', 'odp', 'otp', 'pot', 'potm', 'potx', 'pps', 'ppsm', 'ppsx', 'ppt', 'pptm', 'pptx',
        ]
        if (fileTypesDoc.includes(fileType)) {
            docType = 'text'
        }
        if (fileTypesCsv.includes(fileType)) {
            docType = 'spreadsheet'
        }
        if (fileTypesPPt.includes(fileType)) {
            docType = 'presentation'
        }
        return docType
      },
    },
  }
</script>
<style>
.extra #header-logo i{
  background-image: url('../../assets/logo.png') !important;
}
</style>

<style lang="scss" scoped>
  .menu_btn{
    height: 45px;
    padding: 0 20px;
    display: flex;
    align-items: center;
    flex-direction: row-reverse;
  }
</style>
