<template>
  <el-dialog
    class="create-print-task"
    :visible.sync="modalIsShow"
    :title="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="印刷计划：">
        <span>{{ instance.printPlanName }}</span>
      </el-form-item>
      <el-form-item label="考试时间："
        >{{ instance.examStartTime | timestampFilter }} 至
        {{ instance.examEndTime | timestampFilter }}
      </el-form-item>
      <el-form-item prop="examRoom" label="考场：">
        <el-input
          v-model="modalForm.examRoom"
          placeholder="请填写考场名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="examPlace" label="考点：">
        <el-input
          v-model="modalForm.examPlace"
          placeholder="请填写考点名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="监考老师：">
        <el-input
          v-model="modalForm.invigilatorTeacher"
          placeholder="请填写监考老师"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="classId" label="考试对象：">
        <el-select
          v-model="classIds"
          placeholder="请选择"
          multiple
          clearable
          @change="classChange"
        >
          <el-option
            v-for="clazz in classList"
            :key="clazz.classId"
            :value="clazz.classId"
            :label="clazz.className"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="studentCount" label="人数：">
        <el-input-number
          v-model="modalForm.studentCount"
          :min="0"
          :max="10000"
          :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="请选择"
          @change="printHouseChange"
        >
          <el-option
            v-for="room in printRooms"
            :key="room.houseId"
            :value="room.houseId"
            :label="room.houseName"
          ></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";
import {
  createTaskPrint,
  listTaskPrintHouse,
  listTaskPrintClass
} from "../api";

export default {
  name: "create-print-task",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    },
    extendFields: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "印刷任务";
    }
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: {},
      tableData: [],
      printRooms: [],
      teachers: [],
      classList: [],
      classIds: [],
      rules: {
        examRoom: [
          {
            required: true,
            message: "请输入考场名称",
            trigger: "change"
          }
        ],
        examPlace: [
          {
            required: true,
            message: "请输入考点名称",
            trigger: "change"
          }
        ],
        invigilatorTeacher: [
          {
            required: true,
            message: "请选择监考老师",
            trigger: "change"
          }
        ],
        classId: [
          {
            required: true,
            message: "请选择考试对象",
            trigger: "change"
          }
        ],
        studentCount: [
          {
            required: true,
            message: "请输入人数",
            trigger: "change"
          }
        ],
        printHouseId: [
          {
            required: true,
            message: "请选择印刷室",
            trigger: "change"
          }
        ]
      },
      // extend field
      extendFieldModal: {},
      extendFieldRules: {}
    };
  },
  created() {
    this.getPrintHouses();
    this.extendFields.forEach(field => {
      this.extendFieldRules[field.code] = [
        {
          required: true,
          message: `请输入${field.name}`,
          trigger: "change"
        }
      ];
    });
  },
  methods: {
    async getPrintHouses() {
      this.printRooms = await listTaskPrintHouse();
    },
    async getClazzs() {
      const data = await listTaskPrintClass({
        printPlanId: this.instance.printPlanId,
        courseCode: this.instance.courseCode,
        paperNumber: this.instance.paperNumber,
        examTaskPrintId: this.instance.id
      });
      this.classList = data || [];
    },
    visibleChange() {
      this.getClazzs();
      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.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
        this.$refs.extendFieldFormComp.clearValidate();
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    classChange(vals) {
      const classes = this.classList.filter(item =>
        vals.includes(item.classId)
      );
      this.modalForm.className = classes.map(item => item.className).join(",");
      this.modalForm.classId = this.classIds.join(",");
      this.modalForm.studentCount = calcSum(
        classes.map(item => item.studentCount)
      );
    },
    printHouseChange(val) {
      const curHouse = this.printRooms.find(item => item.houseId === val);
      if (curHouse) {
        this.modalForm.printHouseName = curHouse.houseName;
      }
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

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

      if (this.isSubmit) return;
      this.isSubmit = true;

      let datas = { ...this.modalForm };
      const extendFields = this.extendFields.map(field => {
        let info = { ...field };
        info.value = this.extendFieldModal[field.code];
        return info;
      });
      datas.extendFields = JSON.stringify(extendFields);

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

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