<template>
    <section>
      <!-- 图片预览 -->
      <el-dialog title="图片预览" :append-to-body="true" :visible.sync="previewVisible" width="50%">
        <div v-viewer>
          <img :src="previewPath" :alt="previewName" style="width:100%;height:100%" />
        </div>
      </el-dialog>
    </section>
</template>

<script>
  import { downloadUrl } from '@/api/file'
  import { getFileExt } from '@/api/util'
  import { component as Viewer } from 'v-viewer';
export default {
    name: 'preview-component',
    components: { Viewer },
    data () {
      return {
        previewPath: '',
        previewName: '',
        previewVisible: false
      }
    },
    methods: {
      init (fileName, url) {
        this.handlePreview(fileName, url)
      },
      // 预览
      handlePreview (fileName, url) {
        if (!fileName || !url) {
          this.$message.error('没有可预览的文件！')
          return
        }
        let ext = getFileExt(fileName)
        if (ext === 'jpg' || ext === 'jpeg' || ext === 'png' || ext === 'gif') {
          this.previewPath = downloadUrl + url
          this.previewName = fileName
          this.previewVisible = false

          this.$viewerApi({
            images: [this.previewPath],
            options: { toolbar: false } // 隐藏工具栏
          });
        } else {
          // 弹出新页面显示下载文件
          window.open(downloadUrl + url, '_blank')
        }
      }
    }
  }
</script>

<style scoped>

</style>
