<template>
  <el-dialog
    ref="dialog"
    title="导入考生"
    width="540px"
    destroy-on-close
    :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" accept=".xlsx,.xls" />
        </el-form-item>
        <el-form-item label="">
          {{ uploadingPercent ? ` 上传中(${uploadingPercent}%)` : "" }}
        </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 { importExamStudent } from "@/api/examwork-task";

export default {
  name: "ExamStudentImportDialog",
  props: {
    examId: String,
    examStudent: Object,
  },
  computed: {
    isEdit() {
      return this.examStudent.id;
    },
  },
  data() {
    return {
      visible: false,
      form: {
        file: "",
        fileName: "",
      },
      rules: {},
      loading: false,
      uploadingPercent: 0,
    };
  },
  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() {
      try {
        this.loading = true;
        this.uploadingPercent = 0;
        await importExamStudent({
          examId: this.examId,
          file: this.form.file,
          fileName: this.form.fileName,
          onUploadProgress: (percent) => (this.uploadingPercent = percent),
        });
        this.$emit("reload");
        this.$notify({ title: "导入任务已成功启动", type: "success" });
        this.closeDialog();
      } finally {
        this.loading = false;
        this.uploadingPercent = 0;
      }
    },
  },
};
</script>

<style></style>
