<template>
  <el-dialog
    class="batch-add-exam-task"
    :visible.sync="modalIsShow"
    title="批量新建命题任务"
    top="10vh"
    width="700px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="110px"
    >
      <el-form-item prop="semesterId" label="学期：">
        <semester-select
          v-model="modalForm.semesterId"
          class="width-400"
        ></semester-select>
      </el-form-item>
      <el-form-item prop="examId" label="考试：">
        <exam-select
          v-model="modalForm.examId"
          class="width-400"
          :semester-id="modalForm.semesterId"
        ></exam-select>
      </el-form-item>
      <el-form-item prop="batchNo" label="命题任务表：">
        <upload-file-view
          v-if="modalIsShow"
          :upload-url="uploadExamTaskUrl"
          input-width="300px"
          @upload-success="uploadExamTaskSuccess"
          ref="ExamTaskUploadFileView"
        ></upload-file-view>
        <el-button
          type="success"
          icon="el-icon-download"
          style="margin-left: 10px"
          @click="downloadTemplate('examTask')"
        >
          模板下载
        </el-button>
      </el-form-item>
      <el-form-item prop="startTime" label="命题时间：">
        <el-date-picker
          v-model="createTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="timestamp"
          align="right"
          unlink-panels
          @change="dateChange"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="指派命题老师：">
        <el-table class="el-table--noback" :data="tasks" border>
          <el-table-column prop="courseName" label="课程（代码）">
            <span slot-scope="scope">
              {{ scope.row.courseName }}（{{ scope.row.courseCode }}）
            </span>
          </el-table-column>
          <el-table-column prop="paperNumber" label="试卷编号">
            <template slot-scope="scope">
              {{ scope.row.paperNumber | defaultFieldFilter }}
            </template>
          </el-table-column>
          <el-table-column label="命题老师" width="180px">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.userId"
                size="small"
                style="width: 150px"
                placeholder="请选择"
                clearable
                filterable
              >
                <el-option
                  v-for="user in scope.row.users"
                  :key="user.id"
                  :value="user.id"
                  :label="user.name"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>

    <div slot="footer">
      <el-button type="primary" :disabled="isSubmit" @click="toSave"
        >确认</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { batchAddExamTask } from "../api";
import UploadFileView from "@/components/UploadFileView";
import templateDownload from "@/mixins/templateDownload";

const initModalForm = {
  semesterId: "",
  examId: "",
  cardRuleId: "",
  startTime: "",
  endTime: "",
  batchNo: "",
  userIds: [],
};

export default {
  name: "batch-add-exam-task",
  components: { UploadFileView },
  mixins: [templateDownload],
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
      createTime: [],
      tasks: [],
      batchConfirmMessage: "",
      rules: {
        semesterId: [
          {
            required: true,
            message: "请选择学期",
            trigger: "change",
          },
        ],
        examId: [
          {
            required: true,
            message: "请选择考试",
            trigger: "change",
          },
        ],
        batchNo: [
          {
            required: true,
            message: "请上传命题任务表",
            trigger: "change",
          },
        ],
        startTime: [
          {
            required: true,
            message: "请设置命题时间",
            trigger: "change",
          },
        ],
      },
      downloadUrl: "/temps/examTaskTemplate.xlsx",
      // import
      uploadExamTaskUrl: "/api/admin/exam/task/import",
    };
  },
  methods: {
    visibleChange() {
      this.modalForm = { ...initModalForm };
      this.tasks = [];
      this.createTime = [];
      this.batchConfirmMessage = "";

      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    dateChange() {
      if (this.createTime) {
        this.modalForm.startTime = this.createTime[0];
        this.modalForm.endTime = this.createTime[1];
      } else {
        this.modalForm.startTime = "";
        this.modalForm.endTime = "";
      }
    },
    toSave() {
      if (!this.batchConfirmMessage) {
        this.save();
        return;
      }

      this.$confirm(`${this.batchConfirmMessage}, 是否继续提交?`, "提示", {
        type: "warning",
      })
        .then(() => {
          this.save();
        })
        .catch(() => {});
    },
    async save() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      let datas = {
        ...this.modalForm,
      };
      datas.users = this.tasks.map((task) => {
        return {
          courseId: task.courseId,
          courseCode: task.courseCode,
          courseName: task.courseName,
          paperNumber: task.paperNumber,
          specialty: task.specialty,
          userId: task.userId,
        };
      });

      const data = await batchAddExamTask(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      this.$message.success("保存成功！");
      this.$emit("modified");
      this.cancel();
    },
    // upload-handler
    // uplaodError(errorData) {
    // let message = errorData.message;
    // try {
    //   message = JSON.parse(errorData.error);
    //   message = message.map(item => item.excelErrorType).join("，");
    // } catch (msg) {
    //   console.error(msg);
    // }
    // if (message) this.$notify.error({ title: "错误提示", message });
    // },
    uploadExamTaskSuccess(data) {
      this.$message.success("上传成功！");
      this.modalForm.batchNo = data.batchNo;
      this.batchConfirmMessage = data.errorMsg;
      this.tasks = data.tasks.map((item) => {
        if (!item.userId)
          item.userId = item.users.length === 1 ? item.users[0].id : "";
        return item;
      });
      this.$refs.modalFormComp.validateField("batchNo");
    },
  },
};
</script>
