<template>
  <div>
    <!-- 预览
    <input class="file-select" type="file" @change="handleChange"> -->
    <!-- <iframe :src="url" frameborder="0" style="width: 100%; height: 100vh"></iframe> -->
    <div ref="output" v-loading="loading" class="well"></div>
  </div>
</template>

<script>
import { getExtend, readBuffer, render } from '@/utils/perview'
import { parse } from 'qs'
import { getFilePerview } from '@/api/dictionary'
export default {
  data() {
    return {
      // 加载状态跟踪
      loading: false,
      // 上个渲染实例
      last: null,
      // 隐藏头部，当基于消息机制渲染，将隐藏
      hidden: false,
      url: ''
    }
  },
  created() {
    // 允许使用预留的消息机制发送二进制数据，必须在url后添加?name=xxx.xxx&from=xxx
    const { from, name } = parse(location.search.substr(1))
    if (from) {
      window.addEventListener('message', (event) => {
        const { origin, data: blob } = event
        if (origin === from && blob instanceof Blob) {
          // 构造响应，自动渲染
          const file = new File([blob], name, {})
          this.hidden = true
          this.handleChange({ target: { files: [file] }})
        }
      })
    }
    this.getFile()
  },
  methods: {
    async handleChange(e) {
      this.loading = true
      try {
        const [file] = e.target.files
        const arrayBuffer = await readBuffer(file)
        this.loading = false
        this.last = await this.displayResult(arrayBuffer, file)
      } catch (e) {
        console.error(e)
      } finally {
        this.loading = false
      }
    },
    displayResult(buffer, file) {
      // 取得文件名
      const { name } = file
      // 取得扩展名
      const extend = getExtend(name)
      // 输出目的地
      const { output } = this.$refs
      // 生成新的dom
      const node = document.createElement('div')
      // 添加孩子，防止vue实例替换dom元素
      if (this.last) {
        output.removeChild(this.last.$el)
        this.last.$destroy()
      }
      const child = output.appendChild(node)
      // 调用渲染方法进行渲染
      return new Promise((resolve, reject) =>
        render(buffer, extend, child).then(resolve).catch(reject)
      )
    },
    getFile() {
      const { absolutePath, name } = this.$route.query
      if (!absolutePath) return
      this.loading = true
      getFilePerview({ absolutePath }).then(async(res) => {
        // const blob = new Blob([res.data], {
        //   type: 'application/pdf;chartset=UTF-8'
        // })
        // this.url = window.URL.createObjectURL(blob)
        // console.log(this.url)
        const file = new File([res.data], name, {})
        this.handleChange({ target: { files: [file] }})
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.well {
  height: calc(100vh - 12px);
}

</style>
