<template>
  <object v-if="type === 'NPAPI'" :id="$style.wps" type="application/x-wps" :class="$style.wps" />
  <div v-else-if="flag === 1 && type === 'WebOfficeSDK'" :class="$style.wps" />
  <iframe v-else-if="flag === 1" :src="url" :class="$style.wps" scrolling="no" />
  <a-result v-else-if="flag === -1" status="warning" title="预览正文异常"> </a-result>
  <sdLoading v-else-if="flag === 0" />
</template>

<script>
import loginService from '@/login/login-service'
import qs from 'qs'
import axios from '../services/axios-instance'
import { sdLocalStorage } from '../services/storage-service'
import sdLoading from '../pages/sd-loading.vue'
import components from './_import-components/sd-wps-reader-import'

/**
 * 嵌入网页中方式预览查看word、wps、pdf、ofd等类型文件，需配合【预览控件管理】使用
 * @displayName SdWpsReader 附件预览查看
 */
export default {
  name: 'SdWpsReader',
  metaInfo: {},
  components: { ...components, sdLoading },
  props: {
    /**
     * 附件code
     */
    code: {
      type: String,
      default: '',
    },
    /**
     * 附件后缀如doc,pdf等（仅在使用永中预览服务时需要该参数）
     */
    filetype: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      url: '',
      flag: 0,
      type: 'iframe',
    }
  },
  mounted() {
    const config = JSON.parse(sdLocalStorage.getItem('commonConfig') || '{}').oaDocPreview || {}
    let domain = `${location.origin}${location.pathname}`
    if (!config.localServiceAddress) {
      // eslint-disable-next-line no-console
      console.warn('请配置【预览控件管理】中的nginx服务地址,否则预转换功能将失效')
    } else {
      domain = config.localServiceAddress + '/'
    }
    if (
      // 信创环境或x86环境下的树科轻阅读
      (this.sdPlatform.isXC &&
        config.standardPreviewMode === 'LIGHT_READING' &&
        config.xcPreviewServiceType === 'SUWELL_LIGHT_READING') ||
      (!this.sdPlatform.isXC && config.previewServiceType === 'SUWELL_LIGHT_READING')
    ) {
      this.flag = 1
      loginService.updateAccessToken().then(() => {
        const url = `${domain}api/framework/v1/suwell-preview/reversion/${this.code}?access_token=${
          // 树科对参数编码了反而打不开，所以去掉
          loginService.getTokens().access_token
        }`
        this.url = `${config.previewServiceAddress}/reader?file=${encodeURIComponent(url)}`
      })
    } else if (
      // 信创环境或x86环境下的wps轻阅读
      (this.sdPlatform.isXC &&
        config.standardPreviewMode === 'LIGHT_READING' &&
        config.xcPreviewServiceType === 'WPS_LIGHT_READING') ||
      (!this.sdPlatform.isXC && config.previewServiceType === 'WPS_LIGHT_READING')
    ) {
      axios
        .get('api/framework/v1/attachment-extend/attachments-wpspreview-url/' + this.code)
        .then((res) => {
          if (res.data) {
            this.flag = 1
            this.url = res.data?.url
          } else {
            this.flag = -1
          }
        })
    } else if (
      // 信创或x86环境永中轻阅读
      (this.sdPlatform.isXC &&
        config.standardPreviewMode === 'LIGHT_READING' &&
        config.xcPreviewServiceType === 'YOZO_LIGHT_READING') ||
      (!this.sdPlatform.isXC && config.previewServiceType === 'YOZO_LIGHT_READING')
    ) {
      // 永中预览转换参数https://www.yozodcs.com/page/help.html
      const convertType = {
        wps: 0,
        docx: 0,
        doc: 0,
        pdf: 14,
        ofd: 21,
      }[this.filetype]
      let fileUrl = `${domain}api/framework/v1/task-form-process/download-attachments/${this.code}`
      loginService.updateAccessToken().then(() => {
        fileUrl =
          fileUrl + '?access_token=' + encodeURIComponent(loginService.getTokens().access_token)
        axios
          .post(
            `${config.previewServiceAddress}/composite/httpfile`,
            qs.stringify({
              fileUrl,
              convertType,
              num: 2,
              isShowTitle: 0,
              showFooter: 0,
            }),
            { headers: { 'content-type': 'application/x-www-form-urlencoded' } }
          )
          .then((res) => {
            this.flag = 1
            this.url = res.data.data.viewUrl
          })
          .catch((e) => {
            this.flag = -1
            // eslint-disable-next-line no-console
            console.error('调用永中预览接口失败')
          })
      })
    } else if (this.sdPlatform.isXC && config.standardPreviewMode === 'NPAPI') {
      this.type = 'NPAPI'
      this.$nextTick().then(() => {
        this.url = `${location.origin}${location.pathname}api/framework/v1/task-form-process/download-attachments/${this.code}`
        loginService.updateAccessToken().then(() => {
          this.url = this.url + '?access_token=' + loginService.getTokens().access_token
          // 来获取wps的插件对象
          var Application = document.getElementById(this.$style.wps).Application
          // 获取WPS对象树的根节点，后续功能调用都是根据 Application 逐步得到的
          Application.OpenDocumentFromServer(this.url, '{"readOnly" :true}')
          Application.setToolbarAllVisible(false)
          Application.showRevision(2)
        })
      })
    } else if (
      // 信创环境或x86环境下的福昕轻阅读
      (this.sdPlatform.isXC &&
        config.standardPreviewMode === 'LIGHT_READING' &&
        config.xcPreviewServiceType === 'FOXIT_LIGHT_READING') ||
      (!this.sdPlatform.isXC && config.previewServiceType === 'FOXIT_LIGHT_READING')
    ) {
      this.flag = 1
      loginService.updateAccessToken().then(() => {
        const url = `${domain}api/framework/v1/foxit-preview/reversion/${this.code}?access_token=${
          loginService.getTokens().access_token
        }`
        this.url = `${config.previewServiceAddress}?docuri=${encodeURIComponent(url)}`
      })
    } else if (
      // 信创环境或x86环境下的点聚
      (this.sdPlatform.isXC &&
        config.standardPreviewMode === 'LIGHT_READING' &&
        config.xcPreviewServiceType === 'DIANJU_LIGHT_READING') ||
      (!this.sdPlatform.isXC && config.previewServiceType === 'DIANJU_LIGHT_READING')
    ) {
      loginService.updateAccessToken().then(() => {
        axios
          .get('api/framework/v1/dianju-preview/reversion/' + this.code)
          .then((res) => {
            this.flag = 1
            this.url =
              config.previewServiceAddress +
              '/preview/preview.jsp?showSeal=false&fileId=' +
              res.data?.previewId
          })
          .catch(() => {
            this.flag = -1
          })
      })
    } else if (
      // 信创环境或x86环境下的wpsV6轻阅读
      (this.sdPlatform.isXC &&
        config.standardPreviewMode === 'LIGHT_READING' &&
        config.xcPreviewServiceType.startsWith('WPS_')) ||
      (!this.sdPlatform.isXC && config.previewServiceType.startsWith('WPS_'))
    ) {
      this.type = 'WebOfficeSDK'
      const { openAuthType, openAuthParameter } = this.$route.query
      axios
        .get(
          `api/framework/v1/wps-doc-middle-end/view-url/${this.code}?editable=false&environment=${
            this.sdPlatform.isXC ? 'xc' : 'x86'
          }&openAuthType=${openAuthType}&openAuthParameter=${openAuthParameter}`
        )
        .then((res) => {
          this.flag = 1
          loginService.updateAccessToken().then((token) => {
            import(/* webpackChunkName: "WebOfficeSDK" */ '@external/web-office-sdk.js').then(
              (WebOfficeSDK) => {
                const timeout = loginService.getTokens().expires_in * 1000
                const jssdk = WebOfficeSDK.config({
                  url: res.data.url,
                  refreshToken() {
                    return loginService.updateAccessToken((token) => ({ token, timeout }))
                  },
                  mount: document.querySelector('.' + this.$style.wps),
                })
                jssdk.setToken({ token, timeout })
              }
            )
          })
        })
    }
  },
  methods: {},
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.wps {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #e7e7e7;
  border: none;
}
:global(#office-iframe) {
  // 强制修改wps自带iframe样式
  /* stylelint-disable-next-line  */
  width: 100% !important;
  /* stylelint-disable-next-line  */
  height: 100% !important;
}
</style>
