<template>
  <el-dialog
    class="modify-student"
    :visible.sync="modalIsShow"
    :title="title"
    top="10px"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    destroy-on-close
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      :key="modalForm.id"
      label-width="120px"
    >
      <!-- 必填信息 -->
      <el-form-item prop="semesterId" label="学期：">
        <semester-select
          v-model="modalForm.semesterId"
          placeholder="学期"
          :disabled="isEdit"
          style="width: 100%"
        ></semester-select>
      </el-form-item>
      <el-form-item prop="examId" label="考试：">
        <exam-select
          v-model="modalForm.examId"
          :semester-id="modalForm.semesterId"
          placeholder="考试"
          :disabled="isEdit"
          class="width-full"
          @change="examChange"
        ></exam-select>
      </el-form-item>
      <el-form-item
        v-if="checkRequiredFieldValid('studentName')"
        prop="studentName"
        label="姓名："
      >
        <el-input
          v-model.trim="modalForm.studentName"
          placeholder="请输入姓名"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        v-if="checkRequiredFieldValid('studentCode')"
        prop="studentCode"
        label="学号："
      >
        <el-input
          v-model.trim="modalForm.studentCode"
          placeholder="请输入学号"
          clearable
          :disabled="isEdit"
        ></el-input>
      </el-form-item>
      <el-form-item
        v-if="checkRequiredFieldValid('teachingRoomName')"
        prop="teachingRoomId"
        label="开课学院："
      >
        <org-select
          v-model="modalForm.teachingRoomId"
          placeholder="开课学院"
          :filter-param="{
            withoutSecondOrg: true,
          }"
          style="width: 100%"
          :disabled="isEdit"
          @change="teachingRoomChange"
        ></org-select>
      </el-form-item>
      <el-form-item
        v-if="checkRequiredFieldValid('courseCode')"
        prop="courseId"
        label="课程："
      >
        <el-select
          v-model="modalForm.courseId"
          class="width-full"
          placeholder="课程"
          filterable
          :disabled="isEdit"
        >
          <el-option
            v-for="(item, index) in courseList"
            :key="index"
            :value="item.id"
            :label="`${item.name}（${item.code}）`"
          >
            <span>{{ `${item.name}（${item.code}）` }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="checkRequiredFieldValid('examDate')"
        prop="examStartTime"
        label="考试时间："
      >
        <one-date-time-range
          :start-date-time.sync="modalForm.examStartTime"
          :end-date-time.sync="modalForm.examEndTime"
        >
        </one-date-time-range>
      </el-form-item>
      <el-form-item
        v-if="checkRequiredFieldValid('examRoom')"
        prop="examRoom"
        label="考试教室(考场)："
      >
        <el-input
          v-model.trim="modalForm.examRoom"
          placeholder="请输入考试教室(考场)"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        v-if="checkRequiredFieldValid('collegeName')"
        prop="collegeName"
        label="学院："
      >
        <el-input
          v-model.trim="modalForm.collegeName"
          placeholder="请输入学院"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item
        v-if="checkRequiredFieldValid('teachClassName')"
        prop="teachClassName"
        label="教学班："
      >
        <el-input
          v-model.trim="modalForm.teachClassName"
          placeholder="请输入教学班"
          clearable
        ></el-input>
      </el-form-item>

      <el-form-item prop="paperType" label="卷型：">
        <el-input
          v-model.trim="modalForm.paperType"
          placeholder="请输入卷型"
          clearable
          :maxlength="1"
          class="width-200"
          :disabled="isEdit && !!instance.paperType"
        >
        </el-input>
      </el-form-item>

      <!-- 选填信息 -->
      <el-form-item
        v-for="item in optionalFields"
        :key="`${item.code}${item.name}`"
        :prop="item.code"
        :label="`${item.name}：`"
      >
        <el-input
          v-model.trim="modalForm[item.code]"
          :placeholder="`请输入${item.name}`"
          clearable
          :disabled="
            item.code === 'paperNumber' && isEdit && !!instance[item.code]
          "
        ></el-input>
      </el-form-item>

      <!-- 扩展字段 -->
      <el-form-item
        v-for="item in extendFields"
        :key="`${item.code}${item.name}`"
        :prop="item.code"
        :label="`${item.name}：`"
      >
        <el-input
          v-model.trim="modalForm[item.code]"
          :placeholder="`请输入${item.name}`"
          clearable
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { deepCopy } from "@/plugins/utils";
import { updateExamStudent, examRuleDetail, courseQuery } from "../api";
import OneDateTimeRange from "@/components/OneDateTimeRange.vue";

const requiredModalForm = {
  id: null,
  semesterId: "",
  examId: "",
  studentName: "",
  studentCode: "",
  courseId: "",
  examEndTime: null,
  examStartTime: null,
  collegeName: "",
  examRoom: "",
  teachClassName: "",
  teachingRoomId: "",
  paperType: "",
};

export default {
  name: "modify-exam-student",
  components: { OneDateTimeRange },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
    examData: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "考生";
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...requiredModalForm },
      initModalForm: {},
      requiredRules: {
        semesterId: [
          {
            required: true,
            message: "请选择学期",
            trigger: "change",
          },
        ],
        examId: [
          {
            required: true,
            message: "请选择考试",
            trigger: "change",
          },
        ],
        studentName: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "change",
          },
          {
            message: "姓名不能超过50个字",
            max: 50,
            trigger: "change",
          },
        ],
        studentCode: [
          {
            required: true,
            message: "请输入学号",
            trigger: "change",
          },
          {
            pattern: /^[a-zA-Z0-9]{1,30}$/,
            message: "学号只能由数字、字母组成",
            trigger: "change",
          },
          {
            message: "学号不能超过30个字",
            max: 30,
            trigger: "change",
          },
        ],
        courseId: [
          {
            required: true,
            message: "请选择课程",
            trigger: "change",
          },
        ],
        examStartTime: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (
                rule.required &&
                (!this.modalForm.examStartTime || !this.modalForm.examEndTime)
              ) {
                return callback(new Error("请选择考试时间"));
              }

              if (
                (this.modalForm.examStartTime || this.modalForm.examEndTime) &&
                this.modalForm.examStartTime >= this.modalForm.examEndTime
              ) {
                return callback(new Error("开始时间要早于结束时间"));
              }

              return callback();
            },
          },
        ],
        examRoom: [
          {
            required: true,
            message: "请输入考试教室(考场)",
            trigger: "change",
          },
          {
            message: "考试教室(考场)不能超过30个字",
            max: 30,
            trigger: "change",
          },
        ],
        collegeName: [
          {
            required: true,
            message: "请输入学院",
            trigger: "change",
          },
          {
            message: "学院不能超过30个字",
            max: 30,
            trigger: "change",
          },
        ],
        teachClassName: [
          {
            required: true,
            message: "请输入教学班",
            trigger: "change",
          },
          {
            message: "教学班不能超过30个字",
            max: 30,
            trigger: "change",
          },
        ],
        teachingRoomId: [
          {
            required: true,
            message: "请输入开课学院",
            trigger: "change",
          },
          {
            message: "开课学院不能超过30个字",
            max: 30,
            trigger: "change",
          },
        ],
        paperType: [
          {
            trigger: "change",
            validator: (rule, value, callback) => {
              if (!value) {
                return callback();
              }

              if (!/^[A-Z]{1}$/.test(value)) {
                return callback(new Error(`只能输入一个大写英文字母`));
              }

              return callback();
            },
          },
        ],
      },
      rules: {},
      requiredFields: [
        "studentName",
        "studentCode",
        "courseCode",
        "examDate",
        "examRoom",
        "collegeName",
        "teachClassName",
        "teachingRoomName",
      ],
      optionalFields: [],
      extendFields: [],
      courseList: [],
      curExam: null,
    };
  },
  methods: {
    async initData(val) {
      await this.initFields();

      if (val.id) {
        this.modalForm = this.$objAssign(this.initModalForm, val);

        const extendFieldData = val.extendFields
          ? JSON.parse(val.extendFields)
          : [];
        extendFieldData.forEach((item) => {
          this.modalForm[item.code] = item.value;
        });
        await this.getCourses();
      } else {
        this.modalForm = { ...this.initModalForm };
        this.courseList = [];
      }

      this.curExam = { ...this.examData };

      this.updateRules();

      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
      });
    },
    async initFields() {
      const examRule = await examRuleDetail();
      if (!examRule.id) {
        this.$message.warning("当前系统还没有考务规则，请修改保存！");
        return;
      }

      const requiredFieldData = JSON.parse(examRule.requiredFields);
      this.requiredFields = requiredFieldData
        .filter((item) => item.disabled)
        .map((item) => item.code);
      this.optionalFields = requiredFieldData.filter(
        (item) => !item.disabled && item.enable
      );
      const extendFieldData = examRule.extendFields
        ? JSON.parse(examRule.extendFields)
        : [];
      this.extendFields = extendFieldData.filter((item) => item.enable);

      this.initModalForm = { ...requiredModalForm };
      [...this.optionalFields, ...this.extendFields].forEach((item) => {
        this.initModalForm[item.code] = "";
      });
    },
    checkRequiredFieldValid(fieldName) {
      return this.requiredFields.includes(fieldName);
    },
    visibleChange() {
      this.initData(this.instance);
    },
    async teachingRoomChange() {
      this.modalForm.courseId = "";
      this.courseList = [];
      await this.getCourses();
    },
    async getCourses() {
      if (!this.modalForm.teachingRoomId) return;

      const res = await courseQuery({
        teachingRoomId: this.modalForm.teachingRoomId,
      });

      this.courseList = res.basicCourseList || [];
    },
    examChange(val) {
      this.curExam = val || null;
      this.updateRules();
      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
      });
    },
    updateRules() {
      const nrules = { ...this.requiredRules };
      [...this.optionalFields, ...this.extendFields].forEach((item) => {
        nrules[item.code] = [
          // {
          //   required: false,
          //   message: `请输入${item.name}`,
          //   trigger: "change",
          // },
          {
            message: `${item.name}不能超过30个字`,
            max: 30,
            trigger: "change",
          },
        ];
      });

      const rules = deepCopy(nrules);
      if (this.curExam?.examModel === "MODEL4") {
        const unRequireFields = ["examStartTime", "examRoom", "collegeName"];
        Object.keys(rules)
          .filter((k) => unRequireFields.includes(k))
          .forEach((k) => {
            rules[k][0].required = false;
          });
        rules.paperNumber[0].required = true;
      }
      this.rules = rules;
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    updateClazz() {
      this.modalForm.clazzId = "";
    },
    getModelData() {
      const data = this.$objAssign(requiredModalForm, this.modalForm);
      this.optionalFields.forEach((item) => {
        data[item.code] = this.modalForm[item.code];
      });

      const extendFields = this.extendFields.map((item) => {
        return { ...item, value: this.modalForm[item.code] };
      });
      data.extendFields = JSON.stringify(extendFields);
      return data;
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      const data = await updateExamStudent(this.getModelData()).catch(() => {});
      this.isSubmit = false;

      if (!data) return;

      this.$message.success(this.title + "成功！");
      this.$emit("modified");
      this.cancel();
    },
  },
};
</script>
