<template>
  <el-dialog
    class="batch-add-exam-task"
    :visible.sync="modalIsShow"
    title="批量新建命题任务"
    top="10vh"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-position="top"
    >
      <el-form-item prop="batchNo" label="命题任务表：">
        <upload-file-view
          :upload-url="uploadExamTaskUrl"
          @upload-success="uploadExamTaskSuccess"
          ref="ExamTaskUploadFileView"
          v-if="modalIsShow"
        ></upload-file-view>
        <el-button
          type="success"
          icon="el-icon-download"
          style="margin-left:10px;"
        >
          <a :href="downloadUrl" download="命题任务导入模板.xlsx">模板下载</a>
        </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 prop="cardRuleId" label="题卡规则：">
        <card-rule-select
          ref="CardRuleSelect"
          v-model.trim="modalForm.cardRuleId"
          placeholder="请选择"
          clearable
        ></card-rule-select>
        <p class="tips-info">
          说明：若选择全部通卡，则命题老师只能选择通卡，若选择题卡规则，则专卡和通卡均可选择
        </p>
      </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
              >
                <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";

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

export default {
  name: "batch-add-exam-task",
  components: { UploadFileView },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
      createTime: [],
      tasks: [],
      batchConfirmMessage: "",
      rules: {
        batchNo: [
          {
            required: true,
            message: "请上传命题任务表",
            trigger: "change"
          }
        ],
        startTime: [
          {
            required: true,
            message: "请设置命题时间",
            trigger: "change"
          }
        ],
        cardRuleId: [
          {
            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 {
          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 => {
        item.userId = item.users.length === 1 ? item.users[0].id : "";
        return item;
      });
      this.$refs.modalFormComp.validateField("batchNo");
    }
  }
};
</script>
