<template>
  <el-dialog
    class="show-file"
    :visible="dialogVisibleShowFile"
    width="900px"
    title="查看文件"
    @close="dialogShowFileClose"
  >
    <template v-if="fileType === 'pdf'">
      <pdf v-for="i in numPages" :key="i" :src="pdfSrc" :page="i" />
    </template>

    <template v-else-if="isImage(fileType)">
      <div class="image-parent">
        <el-image fit="contain" :src="fileUrl" />
      </div>
    </template>

    <template v-else>
      <iframe
        :src="'https://view.officeapps.live.com/op/view.aspx?src=' + `${fileUrl}`"
        width="100%"
        height="490px"
        scrolling="no"
      />
    </template>

    <div slot="footer">
      <el-button @click="dialogShowFileClose">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import pdf from 'vue-pdf';

export default {
  components: { pdf },
  props: {
    fileName: {
      default: '',
      type: String
    },
    fileUrl: {
      default: '',
      type: String
    }
  },
  data() {
    return {
      dialogVisibleShowFile: false,
      pdfSrc: '',
      numPages: 1
    };
  },
  computed: {
    fileType() {
      return this.fileName.slice(this.fileName.lastIndexOf('.') + 1, this.fileName.length);
    }
  },
  methods: {
    getNumPages(url) {
      let loadingTask = pdf.createLoadingTask(url);
      loadingTask.promise
        .then(pdf => {
          this.pdfSrc = loadingTask;
          this.numPages = pdf.numPages;
        })
        .catch(err => {
          console.error('pdf加载失败', err);
          this.$message.error('pdf加载失败');
        });
    },

    showDialog() {
      this.dialogVisibleShowFile = true;
    },

    dialogShowFileClose() {
      this.dialogVisibleShowFile = false;
    },

    isImage(type) {
      return ['jpeg', 'gif', 'jpg', 'png', 'bmp', 'pic', 'svg'].includes(type);
    }
  }
};
</script>

<style lang="scss">
@import '~@/styles/mixin.scss';

.show-file {
  @include dialog;

  .image-parent {
    display: flex;
    justify-content: center;
  }
}
</style>
