<template>
  <el-dialog
    ref="dialog"
    :title="'导入' + '监考设置'"
    width="450px"
    :visible.sync="visible"
    @close="closeDialog"
  >
    <el-form
      :model="form"
      ref="form"
      :rules="rules"
      label-position="right"
      label-width="120px"
    >
      <el-row>
        <el-form-item label="选择文件">
          <input @change="selectFile" type="file" />
        </el-form-item>
      </el-row>
      <el-row class="d-flex justify-content-center">
        <el-button type="primary" @click="submitForm" :loading="loading"
          >导入</el-button
        >
        <el-button @click="closeDialog">取消</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script>
import { importInvigilator } from "@/api/examwork-task";
import MD5 from "js-md5";

export default {
  name: "InvigilateImportDialog",
  props: {
    examId: String,
  },
  data() {
    return {
      visible: false,
      form: {
        file: "",
        fileName: "",
      },
      rules: {},
      loading: false,
    };
  },
  watch: {
    examId: {
      immediate: true,
      handler() {
        this.form = {
          processPaper: false,
          processAnswer: false,
          objectiveShuffle: false,
          optionShuffle: false,
          audioPlayCount: 0,
          file: "",
          fileName: "",
        };
      },
    },
  },
  methods: {
    openDialog() {
      this.visible = true;
    },
    closeDialog() {
      this.visible = false;
    },
    selectFile(e) {
      this.form.file = e.target.files[0];
      this.form.fileName = this.form.file?.name;
    },
    async submitForm() {
      async function blobToArray(blob) {
        return new Promise((resolve) => {
          var reader = new FileReader();
          reader.addEventListener("loadend", function () {
            // reader.result contains the contents of blob as a typed array
            resolve(reader.result);
          });
          reader.readAsArrayBuffer(blob);
        });
      }
      const ab = await blobToArray(this.form.file);
      const md5 = MD5(ab);

      try {
        this.loading = true;
        await importInvigilator({
          examId: this.examId,
          file: this.form.file,
          fileName: this.form.fileName,
          md5,
        });
        this.$emit("reload");
        this.$notify({ title: "导入任务已成功启动", type: "success" });
        this.closeDialog();
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style></style>
