<template>
  <el-dialog
    :visible.sync="modalIsShow"
    title="手动输入"
    top="10px"
    width="500px"
    :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="100px"
      @submit.native.prevent
    >
      <el-form-item prop="studentCode" label="学号：">
        <div @keyup.enter="searchStudent">
          <el-input
            v-model.trim="modalForm.studentCode"
            placeholder="请输入学号"
            clearable
          ></el-input>
        </div>
        <p>注意：请输入学号后回车</p>
      </el-form-item>
      <el-form-item prop="studentCode" label="姓名：">
        <el-input
          v-model.trim="modalForm.studentName"
          placeholder="请输入姓名"
          clearable
          :disabled="editDisabled"
        ></el-input>
      </el-form-item>
      <el-form-item prop="courseName" label="课程名称：">
        <el-input
          v-model.trim="modalForm.courseName"
          placeholder="请输入课程名称"
          clearable
          :disabled="editDisabled"
        ></el-input>
      </el-form-item>
      <el-form-item prop="courseCode" label="课程代码：">
        <el-input
          v-model.trim="modalForm.courseCode"
          placeholder="请输入课程代码"
          clearable
          :disabled="editDisabled"
        ></el-input>
      </el-form-item>
      <el-form-item prop="teacher" label="任课老师：">
        <el-input
          v-model.trim="modalForm.teacher"
          placeholder="请输入任课老师"
          clearable
          :disabled="editDisabled"
        ></el-input>
      </el-form-item>
      <el-form-item prop="teachClass" label="教学班：">
        <el-input
          v-model.trim="modalForm.teachClass"
          placeholder="请输入教学班"
          clearable
          :disabled="editDisabled"
        ></el-input>
      </el-form-item>
      <el-form-item prop="collegeName" label="学院：">
        <el-input
          v-model.trim="modalForm.collegeName"
          placeholder="请输入学院"
          clearable
          :disabled="editDisabled"
        ></el-input>
      </el-form-item>
      <el-form-item prop="majorName" label="专业：">
        <el-input
          v-model.trim="modalForm.majorName"
          placeholder="请输入专业"
          clearable
          :disabled="editDisabled"
        ></el-input>
      </el-form-item>
      <el-form-item prop="className" label="班级：">
        <el-input
          v-model.trim="modalForm.className"
          placeholder="请输入班级"
          clearable
          :disabled="editDisabled"
        ></el-input>
      </el-form-item>
      <el-form-item prop="score" label="成绩：">
        <el-input-number
          v-model="modalForm.score"
          :min="0"
          :max="999"
          :step="1"
          step-strictly
          :controls="false"
          :disabled="editDisabled"
        ></el-input-number>
      </el-form-item>
      <el-form-item prop="remark" label="备注：">
        <el-input
          v-model.trim="modalForm.remark"
          placeholder="请输入备注"
          clearable
          :disabled="editDisabled"
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="primary" :disabled="!canSubmit" @click="submit"
        >绑定</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getStudentInfo, updateStudent } from "../api";

const initModalForm = {
  id: null,
  studentCode: "",
  studentName: "",
  courseCode: "",
  courseName: "",
  teacher: "",
  teachClass: "",
  collegeName: "",
  majorName: "",
  className: "",
  score: undefined,
  remark: "",
};

export default {
  name: "manual-bind-dialog",
  props: {
    datas: {
      type: Array,
      default() {
        return [];
      },
    },
    task: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      releaseStudent: null,
      modalForm: { ...initModalForm },
      rules: {
        studentName: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "change",
          },
          {
            message: "姓名不能超过50字符",
            max: 50,
            trigger: "change",
          },
        ],
        studentCode: [
          {
            required: true,
            message: "请输入学号",
            trigger: "change",
          },
          {
            message: "学号只能由数字、字母和下划线组成，长度1-30个字符",
            pattern: /^[a-zA-Z0-9_-]{1,30}$/,
            trigger: "change",
          },
        ],
        collegeName: [
          {
            message: "学院不能超过50字符",
            max: 50,
            trigger: "change",
          },
        ],
        majorName: [
          {
            message: "专业不能超过50字符",
            max: 50,
            trigger: "change",
          },
        ],
        className: [
          {
            message: "班级不能超过50字符",
            max: 50,
            trigger: "change",
          },
        ],
        teacher: [
          {
            message: "任课老师不能超过30字符",
            max: 30,
            trigger: "change",
          },
        ],
        teachClass: [
          {
            message: "教学班不能超过50字符",
            max: 50,
            trigger: "change",
          },
        ],
        courseName: [
          {
            required: true,
            message: "请输入课程名称",
            trigger: "change",
          },
          {
            message: "课程名称不能超过50字符",
            max: 50,
            trigger: "change",
          },
        ],
        courseCode: [
          {
            required: true,
            message: "请输入课程代码",
            trigger: "change",
          },
          {
            message: "课程代码不能超过50字符",
            max: 50,
            trigger: "change",
          },
        ],
        examRoom: [
          {
            message: "考场不能超过50字符",
            max: 50,
            trigger: "change",
          },
        ],
        remark: [
          {
            message: "备注不能超过50字符",
            max: 50,
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {
    editDisabled() {
      return Boolean(this.releaseStudent);
    },
    canSubmit() {
      return (
        this.releaseStudent &&
        this.releaseStudent.studentCode === this.modalForm.studentCode
      );
    },
  },
  methods: {
    visibleChange() {
      if (this.datas.length === 1) {
        this.modalForm = this.$objAssign(initModalForm, this.datas[0]);
        if (this.datas[0].studentName) {
          this.releaseStudent = { ...this.modalForm };
        } else {
          this.releaseStudent = null;
        }
      } else {
        this.modalForm = { ...initModalForm };
        this.releaseStudent = null;
      }

      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    checkField(field) {
      return new Promise((resolve, reject) => {
        this.$refs.modalFormComp.validateField(field, (unvalid) => {
          if (unvalid) {
            reject();
          } else {
            resolve(true);
          }
        });
      });
    },
    async searchStudent() {
      const valid = await this.checkField("studentCode").catch(() => {});
      if (!valid) return;

      const res = await getStudentInfo({
        examId: this.task.examId,
        courseCode: this.task.courseCode,
        studentCode: this.modalForm.studentCode,
      }).catch(() => {});
      if (res) {
        this.releaseStudent = res;
        this.modalForm = this.$objAssign(this.modalForm, res);
      } else {
        this.releaseStudent = null;
        this.modalForm = {
          ...initModalForm,
          studentCode: this.modalForm.studentCode,
        };
      }

      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
      });
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (!this.editDisabled) {
        // 新创建的考生，先保存
        const res = await updateStudent(this.modalForm).catch(() => {});
        if (!res) return;
        this.modalForm.id = res;
      }

      this.$emit("confirm", this.modalForm);
      this.cancel();
    },
  },
};
</script>
