<template>
  <div ref="progressProportion"
       v-loading="loading"
       :style="{height}"
       class="xy-doc-report"
       element-loading-text="报告生成中..."
  >
  </div>
</template>

<script>
import JSZip from 'jszip'
import docxtemplater from 'docxtemplater'
import { renderAsync } from 'docx-preview'

export default {
  name: 'doc-report',
  inject: ['getToken', 'getSetting', 'reject'],
  props: {
    templateData: Object,
    height: [String],
    rid: [String],
  },
  data () {
    return {
      // 文件输出流
      out: null,
      // 加载状态
      loading: true,
      // 当前最新token
      token: '',
      // 团测模板 路径
      templatePath: '',
      // 团测模板数据
      templateCompleteData: {},
    }
  },
  created () {
    this.init()
  },
  mounted () {
    // this.init()
  },
  methods: {
    download (title = new Date().Format('yyyy_MM_dd-hh:mm:ss') + '.docx') {
      saveAs(this.out, title)
    },
    preview () {
      //预览
      renderAsync(this.out, this.$refs.progressProportion, null, {
        className: 'docx', // 默认和文档样式类的类名/前缀
        inWrapper: true, // 启用围绕文档内容渲染包装器
        ignoreWidth: false, // 禁止页面渲染宽度
        ignoreHeight: false, // 禁止页面渲染高度
        ignoreFonts: false, // 禁止字体渲染
        breakPages: true, // 在分页符上启用分页
        ignoreLastRenderedPageBreak: true,//禁用lastRenderedPageBreak元素的分页
        experimental: false, //启用实验性功能（制表符停止计算）
        trimXmlDeclaration: true, //如果为真，xml声明将在解析之前从xml文档中删除
        debug: false
      })
    },

    async init () {
      this.loading = true
      if (!this.rid) {
        throw new Error('无模板id')
      }
      // 更新当前token
      this.token = await this.getToken()
      if (!!this.token) {
        // 获取模板地址
        await this.$tool.request({
          url: this.getSetting().host + this.getSetting().hostSuffix + '/gl/template/getDocTemplatePath/' + this.rid,
          headers: { Authorization: this.token, },
          method: 'get',
        }).then(res => {
          if (res.code === 200) {
            this.templatePath = this.getSetting().host + this.getSetting().hostSuffix + res.data
          } else {
            this.reject(res)
          }
        }).catch(err => {
          this.reject(err)
        })

        // 获取模板数据
        await this.$tool.request({
          url: this.getSetting().host + this.getSetting().hostSuffix + '/gauge/analyse/groupreport',
          headers: {
            Authorization: this.token,
          },
          method: 'post',
          data: this.templateData,
        }).then((res) => {
          if (res.code === 200) {
            this.templateCompleteData = res.data
          } else {
            this.reject(res)
          }
        }).catch(err => {
          this.reject(err)
        })
        await this.processingTemplate()
      }
    },
    processingTemplate (data = this.templateCompleteData, docUrlPath = this.templatePath) {
      let _this = this
      // 获取转换数据
      this.$tool.request({
        url: docUrlPath,
        responseType: 'arraybuffer',
        method: 'get',
        headers: {
          Authorization: this.token,
        },
      }).then(res => {
        if (!res) {
          this.reject({ code: 404, msg: '未找到模板' })
          throw new Error('模板获取失败')
        }
        let doc = new docxtemplater().loadZip(new JSZip(res))
        doc.setData({
          ...data,
        })
        try {
          doc.render()
        } catch (error) {
          // let e = {
          //   message: error.message,
          //   name: error.name,
          //   stack: error.stack,
          //   properties: error.properties
          // }
          // console.log(JSON.stringify({ error: e }))
          throw error
        }

        _this.out = doc.getZip().generate({
          type: 'blob',
          mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        })
        // 关闭加载
        _this.loading = false
        // 打开预览
        _this.preview()
        // 显示下载、打印按钮
        _this.$emit('refreshOperation', true, '50px')
      }).catch((err) => {
        this.reject(err)
      })
    },
  }
}
</script>

<style scoped>
.xy-doc-report {
  overflow-y: auto;
}
</style>
