<script lang="ts" setup>
import { useRoute } from 'vue-router'
import { DocumentEditor } from "@onlyoffice/document-editor-vue";
import { useUserStore } from "@/store/modules/user";

const route = useRoute()
const userStore = useUserStore();
const siteHost=document.location.origin; 
const apiURL=import.meta.env.VITE_APP_BASE_API+"/hxpan/api"
const onlyOfficeHost= import.meta.env.VITE_ONLYOFFICE_HOST
const props = withDefaults(defineProps<{
  fileurl:string
}>(),{})

const config=ref({
  document: {
    title: "Example Document Title.docx",
    url:"", //云盘服务文件地址
    key:""
  },
  
  documentType: "word",
  editorConfig: {
    "lang": "zh-CN",//"en-US",
    mode: "view",//设置编辑模式，view, edit，review
    callbackUrl: `${siteHost}${apiURL}/matter/save`,    //当前网站的域名
    user: {
      id: userStore.userInfoCont.number,
      name: userStore.userInfoCont.nickname,
    },
  }
})

function onLoadComponentError (errorCode:number, errorDescription:string) {
  switch(errorCode) {
    case -1: // Unknown error loading component
      alert(errorDescription);
      break;
    case -2: // Error load DocsAPI from http://documentserver/
      alert(errorDescription);
      break;
    case -3: // DocsAPI is not defined
      alert(errorDescription);
      break;
  }
}

onMounted(()=>{
  const query = route.query
  if (query.fileurl){
    const info=query.info?.toString()??"error"
    const _info=decodeURIComponent(atob(info))
    const _url=decodeURIComponent(window.atob(query.fileurl))
    const name=query.name?.toString()??""
    const dtype=query.dtype?.toString()??"word"
    //验证一下文件名是否合规
    if (_info.includes(name)){
      config.value.document.url=_url
      config.value.document.title=name
      const _key=_url.match(/(\w+-\w+-\w+)/)![0]
      if(_key) config.value.document.key=_key  //合作编辑必须要有一个unique key
      config.value.documentType=dtype
      config.value.editorConfig.callbackUrl+=`?info=${_info}`
      //设置编辑模式
      if(!query.verify) return;
      const _verify = atob(query.verify)
      //1：必须是验证通过，以true结尾  2：校验uuid是否匹配
      if(_verify.endsWith("true") &&  _key.includes(_verify.replace("true",""))){
        config.value.editorConfig.mode="edit"
      }
    }
  }
})
  
</script>

<template>
  <DocumentEditor 
    id="docEditor"
    style="height: inherit;"
    :documentServerUrl="onlyOfficeHost"
    :config="config"
    :onLoadComponentError="onLoadComponentError"
  /> 
</template>
<style>

    
</style>