<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>
import { attachmentWatermarkPreview } from "@/modules/login/api";
import { objTypeOf, blobToText } from "@/plugins/utils";

export default {
  name: "preview-file",
  props: {
    data: {
      type: Object,
      default() {
        return {
          id: "",
          url: "",
          type: "",
        };
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      url: "",
    };
  },
  methods: {
    visibleChange() {
      if (this.data.id) {
        this.getIdFile();
      } else {
        this.getUrlFile();
      }
      this.registResizeEvent();
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async getIdFile() {
      let errorInfo = null;
      const res = await attachmentWatermarkPreview(this.data.id).catch((e) => {
        errorInfo = e;
      });

      // 展示后台错误信息
      if (errorInfo && objTypeOf(errorInfo) === "blob") {
        const res = await blobToText(errorInfo).catch(() => {});
        if (!res) return Promise.reject("下载失败！");
        const resJson = JSON.parse(res);
        this.$message.error(resJson);
        return;
      }

      this.url = URL.createObjectURL(
        new Blob([res.data], { type: this.data.type })
      );

      this.$nextTick(() => {
        document.getElementById("frame-content").height =
          window.innerHeight - 51;
      });
    },
    getUrlFile() {
      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>
