<template>
  <Modal
    class="modify-unformal-grading-task"
    v-model="modalIsShow"
    title="创建试评任务"
    :mask-closable="false"
    @on-visible-change="visibleChange"
  >
    <div class="task-body">
      <upload-button
        btn-icon="md-cloud-upload"
        :btn-content="uploadBtnName"
        :upload-url="uploadUrl"
        :upload-data="uploadData"
        :format="['xls', 'xlsx']"
        :auto-upload="false"
        @upload-success="uploadSuccess"
        @file-change="selectedFile"
        ref="UploadButton"
      >
        <Button
          type="primary"
          :disabled="$refs.UploadButton && $refs.UploadButton.loading"
          @click="startUpload"
          style="margin-left: 10px"
          slot="extra"
          >开始上传</Button
        >
      </upload-button>
    </div>
    <div slot="footer">
      <Button type="text" @click="cancel">取消</Button>
      <Button type="primary" :disabled="isSubmit" @click="toStartTask"
        >开始试评</Button
      >
      <Button type="error" :disabled="isSubmit" @click="toOverTask"
        >结束并清空数据</Button
      >
    </div>
  </Modal>
</template>

<script>
import { createTryGradingTask, finishTryGradingTask } from "@/api";
import UploadButton from "@/components/UploadButton";

export default {
  name: "modify-unformal-grading-task",
  components: { UploadButton },
  props: {
    curSubject: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      uploadData: {},
      uploadBtnName: "导入考生数据",
      uploadUrl: this.GLOBAL.domain + "/import/students/batchAllForTrial"
    };
  },
  created() {
    this.uploadData = {
      workId: this.curSubject.workId,
      subject: this.curSubject.subject
    };
  },
  methods: {
    visibleChange(visible) {
      if (visible) {
        console.log("try");
      }
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    startUpload() {
      this.$refs.UploadButton.startUpload();
    },
    selectedFile(file) {
      this.uploadBtnName = file.name;
    },
    uploadSuccess(response) {
      this.uploadBtnName = "导入考生数据";
      console.log(response);
    },
    async toStartTask() {
      if (this.isSubmit) return;
      this.isSubmit = true;
      const data = await createTryGradingTask(this.uploadData).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      this.$Message.success("发布任务成功！");
      this.$emit("modified");
      this.cancel();
    },
    async toOverTask() {
      if (this.isSubmit) return;
      this.isSubmit = true;
      const data = await finishTryGradingTask(this.data).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      this.$Message.success("操作成功！");
      this.$emit("modified");
      this.cancel();
    }
  }
};
</script>
