<template>
  <el-dialog
    class="paper-preview-dialog"
    :visible.sync="modalIsShow"
    :title="title"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    fullscreen
    @open="visibleChange"
  >
    <div v-if="loading" class="preview-loading">
      <i class="el-icon-loading"></i>
    </div>
    <div ref="PaperPreview" class="paper-preview"></div>

    <div slot="footer">
      <el-button type="primary" :disabled="loading" @click="toOrigin"
        >实际大小</el-button
      >
      <el-button
        type="primary"
        :disabled="loading || rate >= maxScale"
        @click="toMagnify"
        >放大</el-button
      >
      <el-button
        type="primary"
        :disabled="loading || rate <= minScale"
        @click="toShrink"
        >缩小</el-button
      >
      <el-button type="success" :loading="loading" @click="toDownload"
        >下载</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { buildCanvas, downloadPaper } from "./downloadPaper";
import papers from "./paper";

export default {
  name: "modify-user",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  computed: {
    title() {
      return "试卷预览" + this.instance.studentName;
    }
  },
  data() {
    return {
      modalIsShow: false,
      loading: false,
      papers: [],
      rate: 1,
      minScale: 0.5,
      maxScale: 2,
      canvas: null
    };
  },
  methods: {
    visibleChange() {
      this.papers = papers;
      this.rebuild();
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async rebuild() {
      this.loading = true;
      this.canvas = null;
      const canvas = await buildCanvas(papers, this.rate).catch(() => {});
      if (!canvas) {
        this.$message.error("试卷绘制错误！");
        this.loading = false;
        return;
      }
      const previewDom = this.$refs.PaperPreview;
      previewDom.childNodes.forEach(node => {
        previewDom.removeChild(node);
      });
      previewDom.appendChild(canvas);
      this.canvas = canvas;
      this.loading = false;
    },
    toOrigin() {
      this.rate = 1;
      this.rebuild();
    },
    toMagnify() {
      const rate = this.rate * 1.2;
      this.rate = rate >= this.maxScale ? this.maxScale : rate;
      this.rebuild();
    },
    toShrink() {
      const rate = this.rate * 0.75;
      this.rate = rate <= this.minScale ? this.minScale : rate;
      this.rebuild();
    },
    async toDownload() {
      if (this.loading) return;
      this.loading = true;
      const filename = ``;
      const res = await downloadPaper(this.papers, filename).catch(() => {});
      this.loading = false;
      if (!res) {
        this.$message.error("下载失败，请重新尝试！");
        return;
      }

      this.$message.success("下载成功！");
    }
  }
};
</script>
