<template>
  <el-dialog
    class="upload-paper-answer-dialog"
    :visible.sync="modalIsShow"
    title="上传试卷标答PDF文档"
    top="10vh"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    destroy-on-close
    @open="visibleChange"
  >
    <el-form ref="modalFormComp" :model="infos" label-width="50px">
      <div class="part-box">
        <h3 class="mb-2">卷型{{ instance.paperType }}</h3>
        <el-form-item prop="file" label="标答：">
          <select-file
            :format="fileFormat"
            :disabled="isSubmit"
            @file-change="fileChange"
          ></select-file>
        </el-form-item>
      </div>
    </el-form>
    <div slot="footer">
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { examStructureUploadAnswer } from "../api";
import SelectFile from "./SelectFile.vue";

export default {
  name: "upload-paper-answer-dialog",
  components: { SelectFile },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      infos: { file: null, md5: null, errorMsg: null },
      fileFormat: ["pdf"]
    };
  },
  methods: {
    visibleChange() {
      this.infos = { file: null, md5: null, errorMsg: null };
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    fileChange(data) {
      if (data.errorMsg) {
        this.infos.file = null;
        this.infos.md5 = null;
        this.infos.errorMsg = data.errorMsg;
      } else {
        this.infos.file = data.file;
        this.infos.md5 = data.md5;
        this.infos.errorMsg = null;
      }
    },
    async submit() {
      if (!this.infos.file) {
        this.$message.error("请选择标答文件");
        return;
      }

      if (this.isSubmit) return;
      this.isSubmit = true;

      let formData = new FormData();
      formData.append("id", this.instance.id);
      formData.append(`file`, this.infos.file);
      formData.append(`md5`, this.infos.md5);
      const data = await examStructureUploadAnswer(formData).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      this.$message.success("上传成功！");
      this.$emit("modified");
      this.cancel();
    }
  }
};
</script>
