<template>
  <iframe title="文档预览" ref="frame" :src="src" class="iframe-viewer"/>
</template>

<script>

// 查看器的源，当前示例为本源，指定为location.origin即可
const viewerOrigin = location.origin;

// iframe路径指向构建产物，这里是/，因为放在了public下面
// 如果使用cdn，请使用https://viewer.flyfish.dev
const source = '/dist/index.html'

export default {
  name: 'IframeViewer',
  props: {
    url: String,
    file: File,
    name: String,
  },
  mounted() {
    this.sendFileData();
  },
  computed: {
    // 构建完整url
    src() {
      // 文件名称，建议传递，提高体验性
      const name = this.name || '';
      if (this.url) {
        // 直接拼接url
        return `${source}?url=${encodeURIComponent(this.url)}&name=${encodeURIComponent(name)}`
      } else if (this.file) {
        // 直接拼接来源origin
        return `${source}?from=${encodeURIComponent(viewerOrigin)}&name=${encodeURIComponent(name)}`
      } else {
        return source;
      }
    }
  },
  methods: {
    // 发送文件数据
    sendFileData() {
      this.nextTick(() => {
        // iframe引用
        const viewer = this.$refs.frame;
        if (!viewer || !this.file) return;
        viewer.onload = () => viewer.contentWindow?.postMessage(this.file, viewerOrigin);
      })
    }
  }
}
</script>

<style scoped>
.iframe-viewer {
  height: calc(100vh - 2px);
  width: 100%;
  border: 0
}
</style>
