<template>
  <el-dialog
    class="report-preview"
    :visible.sync="modalIsShow"
    top="0"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    append-to-body
    fullscreen
  >
    <div class="box-justify" slot="title">
      <h2 class="el-dialog__title">成绩报告</h2>
      <span>{{ title }}</span>

      <div>
        <el-button
          type="primary"
          :loading="downloading"
          icon="el-icon-download"
          @click="toExportScore"
          >下载报告</el-button
        >
        <el-button class="btn-back" @click="cancel">
          返回<i class="el-icon-arrow-right"></i>
        </el-button>
      </div>
    </div>

    <report v-if="modalIsShow" ref="reportRef" :baseinfo="instance"></report>

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

<script>
import Report from "./report/Report.vue";
import { downloadByApi } from "@/plugins/download";
import { scoreReportExport } from "../api";

export default {
  name: "score-report-preview",
  components: { Report },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      downloading: false,
    };
  },
  computed: {
    title() {
      const course = `${this.instance.courseName}（${this.instance.courseCode}）`;
      return course;
    },
  },
  methods: {
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async toExportScore() {
      if (this.downloading) return;
      this.downloading = true;

      const filename = `${this.title}.pdf`;
      const res = await downloadByApi(() => {
        const formData = new FormData();
        const htmlFile = new File(
          [this.$refs.reportRef.getTemp()],
          `${Date.now()}.html`,
          { type: "text/html" }
        );
        formData.append("file", htmlFile);
        return scoreReportExport(formData);
      }, filename).catch((e) => {
        this.$message.error(e || "下载失败，请重新尝试！");
      });
      this.downloading = false;

      if (!res) return;
      this.$message.success("下载成功！");
    },
  },
};
</script>
