<template>
  <el-dialog
    class="page-dialog preview-file"
    :visible.sync="modalIsShow"
    title="预览"
    fullscreen
    append-to-body
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @open="visibleChange"
    @close="removeResizeEvent"
  >
    <iframe
      v-if="url && modalIsShow"
      :src="url"
      id="frame-content"
      width="100%"
      height="600px"
      style="border: 0"
    >
    </iframe>

    <div slot="footer"></div>
  </el-dialog>
</template>

<script>
export default {
  name: "preview-file",
  props: {
    data: {
      type: Object,
      default() {
        return {
          url: "",
          type: "",
        };
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      url: "",
    };
  },
  methods: {
    visibleChange() {
      this.getFile();
      this.registResizeEvent();
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    getFile() {
      fetch(this.data.url)
        .then((response) => response.blob())
        .then((blob) => {
          this.url = URL.createObjectURL(
            new Blob([blob], { type: this.data.type })
          );

          this.$nextTick(() => {
            document.getElementById("frame-content").height =
              window.innerHeight - 51;
          });
        })
        .catch((error) => console.error("Error fetching PDF:", error));
    },
    resizeEvent() {
      document.getElementById("frame-content").height = window.innerHeight - 51;
    },
    registResizeEvent() {
      window.addEventListener("resize", this.resizeEvent);
    },
    removeResizeEvent() {
      window.removeEventListener("resize", this.resizeEvent);
    },
  },
  beforeDestroy() {
    this.removeResizeEvent();
  },
};
</script>
