<template>
  <el-dialog
    class="modify-print-task"
    :visible.sync="modalIsShow"
    title="新增考试对象"
    top="10px"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @opened="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      label-width="100px"
      :rules="rules"
      :model="modalForm"
    >
      <el-form-item label="考试时间："
        >{{ instance.examStartTime | timestampFilter }} 至
        {{ instance.examEndTime | timestampFilter }}
      </el-form-item>
      <el-form-item prop="classId" label="考试对象：">
        <clazz-select
          v-model="classIds"
          placeholder="请选择"
          multiple
          clearable
          :datas="classList"
          style="width:100%;"
          @change="classChange"
        ></clazz-select>
      </el-form-item>
      <el-form-item prop="studentCount" label="人数：">
        <el-input-number
          v-model="modalForm.studentCount"
          :min="0"
          :step="1"
          step-strictly
          disabled
          :controls="false"
        ></el-input-number>
      </el-form-item>
      <el-form-item prop="printHouseId" label="印刷室：">
        <el-select
          v-model="modalForm.printHouseId"
          placeholder="请选择"
          filterable
          @change="printHouseChange"
        >
          <el-option
            v-for="room in printHouses"
            :key="room.printHouseId"
            :value="room.printHouseId"
            :label="room.printHouseName"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-form
      ref="extendFieldFormComp"
      label-width="100px"
      :rules="extendFieldRules"
      :model="extendFieldModal"
    >
      <el-form-item
        v-for="item in extendFields"
        :key="item.code"
        :label="`${item.name}：`"
        :prop="item.code"
      >
        <el-input
          v-model="extendFieldModal[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 { calcSum } from "@/plugins/utils";

export default {
  name: "modify-print-task",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    },
    extendFields: {
      type: Array,
      default() {
        return [];
      }
    },
    printHouses: {
      type: Array,
      default() {
        return [];
      }
    },
    classList: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: {},
      tableData: [],
      teachers: [],
      classIds: [],
      rules: {
        classId: [
          {
            required: true,
            message: "请选择考试对象",
            trigger: "change"
          }
        ],
        studentCount: [
          {
            required: true,
            message: "请输入人数",
            trigger: "change"
          }
        ],
        printHouseId: [
          {
            required: true,
            message: "请选择印刷室",
            trigger: "change"
          }
        ]
      },
      // extend field
      extendFieldModal: {},
      extendFieldRules: {}
    };
  },
  methods: {
    visibleChange() {
      this.modalForm = { ...this.instance };
      this.classIds = this.modalForm.classId
        ? this.modalForm.classId.split(",")
        : [];
      const extendVals = this.instance.extends;
      let extendFieldModal = {};
      this.extendFields.forEach(field => {
        extendFieldModal[field.code] = extendVals ? extendVals[field.code] : "";
      });
      this.extendFieldModal = extendFieldModal;

      this.extendFieldRules = {};
      this.extendFields.forEach(field => {
        this.extendFieldRules[field.code] = [
          {
            required: true,
            message: `请输入${field.name}`,
            trigger: "change"
          },
          {
            max: 100,
            message: `${field.name}不能超过100个字符`,
            trigger: "change"
          }
        ];
      });
      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
        this.$refs.extendFieldFormComp.clearValidate();
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    classChange(classes) {
      this.modalForm.className = classes.map(item => item.name).join();
      this.modalForm.classId = this.classIds.join();
      this.modalForm.studentCount = calcSum(
        classes.map(item => item.studentCount)
      );
      this.$refs.modalFormComp.validateField("classId", () => {});
    },
    printHouseChange(val) {
      const curHouse = this.printHouses.find(item => item.printHouseId === val);
      if (curHouse) {
        this.modalForm.printHouseName = curHouse.printHouseName;
      }
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      const extendValid = await this.$refs.extendFieldFormComp
        .validate()
        .catch(() => {});
      if (!extendValid) return;

      let datas = { ...this.modalForm };
      datas.extends = { ...this.extendFieldModal };

      this.$emit("modified", datas);
      this.cancel();
    }
  }
};
</script>
