<template>
  <div class="info-print-task">
    <p v-if="IS_MODEL2" class="tips-info mb-2">
      考试需要命题老师提交具体印刷份数
    </p>
    <p v-else class="tips-info mb-2">
      考试需要命题老师提交完整的考务数据，每个卷袋表示一个考场，人数字段为应考人数，备份数量为该考场试卷题卡备用数量
    </p>
    <el-form ref="modalFormComp" label-position="top">
      <el-form-item label="考试时间：" required>
        <el-date-picker
          v-model="createDate"
          type="date"
          value-format="timestamp"
          placeholder="考试日期"
          style="width: 150px"
          :editable="false"
          @change="timeChange"
        >
        </el-date-picker>
        <el-time-picker
          is-range
          v-model="createTime"
          range-separator="至"
          start-placeholder="考试开始时间"
          end-placeholder="考试结束时间"
          placeholder="选择时间范围"
          value-format="timestamp"
          :editable="false"
          @change="timeChange"
        >
        </el-time-picker>
      </el-form-item>
      <el-form-item label="考试对象：" required></el-form-item>
    </el-form>
    <div v-if="IS_MODEL2" class="part-box">
      <table class="table">
        <colgroup>
          <col width="50" />
          <col width="50" />
          <col width="50" />
          <col width="100" />
        </colgroup>
        <tr>
          <th>卷袋序号</th>
          <th>印刷份数</th>
          <th>备份数量</th>
          <th>印刷室</th>
        </tr>
        <tr>
          <td>1</td>
          <td>
            <el-input-number
              v-model="modalForm.printCount"
              style="width:80px"
              :min="1"
              :max="999999"
              :step="1"
              step-strictly
              :controls="false"
            ></el-input-number>
          </td>
          <td>{{ infoExamPrintPlan.backupCount }}</td>
          <td>
            <el-select
              v-model="modalForm.printHouseId"
              placeholder="请选择"
              filterable
            >
              <el-option
                v-for="room in printHouses"
                :key="room.printHouseId"
                :value="room.printHouseId"
                :label="room.printHouseName"
              ></el-option>
            </el-select>
          </td>
        </tr>
      </table>
    </div>
    <div v-else class="part-box">
      <div class="box-justify mb-2">
        <p>
          共{{ packageInfos.packageCount }}个卷袋，{{
            packageInfos.studentCount
          }}个考生，共印试卷{{ packageInfos.paperCount }}份（正式{{
            packageInfos.paperReleaseCount
          }}份，备用{{ packageInfos.paperBackupCount }}份）
        </p>
        <el-button type="primary" @click="toAdd" :disabled="cannotAdd"
          >新增考试对象</el-button
        >
      </div>
      <el-table ref="TableList" :data="tableData" border>
        <el-table-column type="index" width="50" label="卷袋序号">
        </el-table-column>
        <el-table-column prop="className" label="考试对象"> </el-table-column>
        <el-table-column prop="studentCount" label="人数" width="60">
        </el-table-column>
        <el-table-column prop="backupCount" label="备份数量" width="90">
          <!-- <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.backupCount"
              style="width:60px"
              :min="1"
              :max="99999"
              :step="1"
              step-strictly
              :controls="false"
              @change="backupCountChange"
            ></el-input-number>
          </template> -->
        </el-table-column>
        <el-table-column prop="examPlace" label="考点名称">
          <template slot-scope="scope">
            <el-input
              v-model.trim="scope.row.examPlace"
              :maxlength="100"
              clearable
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="examRoom" label="考场名称">
          <template slot-scope="scope">
            <el-input
              v-model.trim="scope.row.examRoom"
              :maxlength="50"
              clearable
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="printHouseName" label="印刷室">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.printHouseId"
              placeholder="请选择"
              filterable
              @change="() => printHouseChange(scope.row)"
            >
              <el-option
                v-for="room in printHouses"
                :key="room.printHouseId"
                :value="room.printHouseId"
                :label="room.printHouseName"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          v-for="item in extendFields"
          :key="item.code"
          :label="item.name"
        >
          <div slot-scope="scope">
            <el-input
              v-model="scope.row.extends[item.code]"
              placeholder="请输入"
              clearable
            ></el-input>
          </div>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              class="btn-danger"
              type="text"
              @click="toDelete(scope.row)"
              >取消</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- ModifyPrintTask -->
    <modify-print-task
      ref="ModifyPrintTask"
      :instance="curRow"
      :print-houses="printHouses"
      :class-list="unusedClassList"
      :extend-fields="extendFields"
      @modified="modified"
    ></modify-print-task>
  </div>
</template>

<script>
import { calcSum, getTimeDatestamp } from "@/plugins/utils";
import { examRuleDetail } from "../../../base/api";
import { listTaskPrintHouse, listTaskApplyClass } from "../../api";
import ModifyPrintTask from "./ModifyPrintTask";
import { mapState, mapMutations } from "vuex";

export default {
  name: "info-print-task",
  components: { ModifyPrintTask },
  data() {
    return {
      modalForm: {
        examStartTime: "",
        examEndTime: "",
        paperNumber: "",
        courseName: "",
        courseCode: "",
        printCount: 1,
        printHouseId: ""
      },
      tableData: [],
      curRow: {},
      classList: [],
      validClassList: [],
      unusedClassList: [],
      printHouses: [],
      extendFields: [],
      packageInfos: {
        packageCount: 0,
        studentCount: 0,
        paperCount: 0,
        paperReleaseCount: 0,
        paperBackupCount: 0
      },
      // date-picker
      curCreateTime: [],
      createDate: "",
      createTime: []
    };
  },
  computed: {
    ...mapState("exam", [
      "infoExamTask",
      "infoExamTaskDetail",
      "infoPrintTask",
      "infoExamPrintPlan"
    ]),
    cannotAdd() {
      return !this.unusedClassList.length;
    },
    IS_MODEL2() {
      return this.infoExamTask.examModel === "MODEL2";
    }
  },
  watch: {
    "infoExamTask.courseCode": function(val, oldval) {
      if (val !== oldval) this.initData();
    },
    "infoExamPrintPlan.backupCount": function(val, oldval) {
      if (val !== oldval) this.planBackupCountChange();
    }
  },
  mounted() {
    this.getExtendFields();
    this.getPrintHouses();

    const curDate = getTimeDatestamp(Date.now());
    const hour = 60 * 60 * 1000;
    this.curCreateTime = [curDate + 8 * hour, curDate + 10 * hour];
    this.createTime = [...this.curCreateTime];
  },
  methods: {
    ...mapMutations("exam", ["updateTaskInfo"]),
    async initData() {
      if (this.IS_MODEL2) return;

      this.modalForm = Object.assign(this.modalForm, {
        paperNumber: this.infoExamTask.paperNumber,
        courseName: this.infoExamTask.courseName,
        courseCode: this.infoExamTask.courseCode
      });

      await this.getClassList();

      const { examStartTime, examEndTime } = this.infoPrintTask;
      if (examStartTime && examEndTime) {
        this.createTime = [examStartTime, examEndTime];
        this.createDate = getTimeDatestamp(examStartTime);
        this.modalForm.examStartTime = this.createTime[0];
        this.modalForm.examEndTime = this.createTime[1];
      }

      this.tableData = [];
      this.unusedClassList = [];
      this.buildTableData();
      this.updatePackageInfos();
      this.updeteData();
    },
    planBackupCountChange() {
      this.tableData.forEach(item => {
        item.backupCount = this.infoExamPrintPlan.backupCount || 0;
      });
      this.updatePackageInfos();
    },
    checkTime() {
      if (!this.modalForm.examStartTime || !this.modalForm.examEndTime) {
        this.$message.error("请选择考试时间！");
        return false;
      }

      if (this.modalForm.examStartTime >= this.modalForm.examEndTime) {
        this.$message.error("考试开始时间必须小于考试结束时间！");
        return false;
      }
      return true;
    },
    checkData() {
      if (!this.checkTime()) return Promise.reject();

      if (this.IS_MODEL2) {
        if (!this.modalForm.printCount) {
          this.$message.error("请输入印刷分数！");
          return Promise.reject();
        }
        if (!this.modalForm.printHouseId) {
          this.$message.error("请选择印刷室！");
          return Promise.reject();
        }
        return Promise.resolve(true);
      }

      if (!this.tableData.length) {
        this.$message.error("请添加考试对象！");
        return Promise.reject();
      }

      let errorMsg = [];
      this.tableData.forEach(row => {
        let errorFields = [];
        this.extendFields.forEach(field => {
          if (!row.extends[field.code]) {
            errorFields.push(field.name);
          }
        });

        if (!row.printHouseId) {
          errorFields.push("印刷室");
        }
        if (errorFields.length) {
          errorMsg.push(
            `考试对象${row.className}中，${errorFields.join("、")}必须填写`
          );
        }
      });
      if (errorMsg.length) {
        this.$message.error(errorMsg.join("。"));
        return Promise.reject();
      }
      return Promise.resolve(true);
    },
    updeteData() {
      const tableList = this.tableData.map(row => {
        let nrow = { ...row };
        let extendFields = this.extendFields.map(field => {
          let info = { ...field };
          info.value = row.extends[field.code];
          return info;
        });

        nrow.extendFields = JSON.stringify(extendFields);
        nrow.examStartTime = this.modalForm.examStartTime;
        nrow.examEndTime = this.modalForm.examEndTime;
        return nrow;
      });

      this.updateTaskInfo({
        infoPrintTask: {
          ...this.modalForm,
          list: tableList
        }
      });
    },
    updateData() {
      this.$emit("data-change", this.getData());
    },
    buildTableData() {
      this.tableData = this.classList.map(clazz => {
        let modalFormData = { ...this.modalForm };
        delete modalFormData.printHouseId;
        let data = {
          examPlace: "",
          examRoom: "",
          classId: clazz.id,
          className: clazz.name,
          studentCount: clazz.studentCount,
          printHouseId: clazz.printHouseId,
          printHouseName: clazz.printHouseName,
          extendFields: "",
          backupCount: this.infoExamPrintPlan.backupCount,
          ...modalFormData
        };
        let extendFieldModal = {};
        this.extendFields.forEach(field => {
          extendFieldModal[field.code] = "";
        });
        data.extends = extendFieldModal;
        return data;
      });
    },
    updateUnusedClassList() {
      let usedClassIds = [];
      this.tableData.forEach(row => {
        usedClassIds = [...usedClassIds, ...row.classId.split(",")];
      });

      this.unusedClassList = this.classList.filter(
        item => !usedClassIds.includes(item.id)
      );
    },
    updatePackageInfos() {
      this.packageInfos.packageCount = this.tableData.length;
      this.packageInfos.studentCount = calcSum(
        this.tableData.map(item => item.studentCount)
      );
      this.packageInfos.paperReleaseCount = this.packageInfos.studentCount;
      this.packageInfos.paperBackupCount = calcSum(
        this.tableData.map(item => item.backupCount || 0)
      );
      this.packageInfos.paperCount =
        this.packageInfos.paperReleaseCount +
        this.packageInfos.paperBackupCount;
    },
    async getExtendFields() {
      const examRule = await examRuleDetail();
      this.extendFields = examRule.extendFields
        ? JSON.parse(examRule.extendFields)
        : [];
    },
    async getPrintHouses() {
      this.printHouses = await listTaskPrintHouse();
    },
    async getClassList() {
      this.classList = [];
      if (!this.infoExamTask.courseCode) return;

      const data = await listTaskApplyClass({
        courseCode: this.infoExamTask.courseCode
      });
      if (!data) return;

      this.classList = data.map(item => {
        return {
          id: item.classId,
          name: item.className,
          studentCount: item.studentCount,
          printHouseId: item.printHouseId,
          printHouseName: item.printHouseName
        };
      });
    },
    timeChange() {
      if (!this.createDate || !this.createTime) {
        this.modalForm.examStartTime = null;
        this.modalForm.examEndTime = null;
        return;
      }

      const curDate = getTimeDatestamp(this.createDate);
      const timeDate = getTimeDatestamp(this.createTime[0]);

      this.modalForm.examStartTime = curDate + this.createTime[0] - timeDate;
      this.modalForm.examEndTime = curDate + this.createTime[1] - timeDate;
    },
    backupCountChange() {
      this.updatePackageInfos();
    },
    printHouseChange(row) {
      const curHouse = this.printHouses.find(
        item => item.printHouseId === row.printHouseId
      );
      if (curHouse) {
        row.printHouseName = curHouse.printHouseName;
      }
    },
    toAdd() {
      if (!this.checkTime()) return;

      this.curRow = {
        examPlace: "",
        examRoom: "",
        classId: "",
        className: "",
        studentCount: null,
        printHouseId: null,
        printHouseName: null,
        extendFields: "",
        backupCount: this.infoExamPrintPlan.backupCount,
        ...this.modalForm
      };
      let extendFieldModal = {};
      this.extendFields.forEach(field => {
        extendFieldModal[field.code] = "";
      });
      this.curRow.extends = extendFieldModal;
      this.$refs.ModifyPrintTask.open();
    },
    toEdit(row) {
      this.curRow = { ...row };
      this.$refs.ModifyPrintTask.open();
    },
    toDelete(row) {
      this.tableData = this.tableData.filter(
        item => item.classId !== row.classId
      );
      this.updateUnusedClassList();
      this.updatePackageInfos();
    },
    modified(data) {
      this.tableData.push(data);
      this.updateUnusedClassList();
      this.updatePackageInfos();
    }
  }
};
</script>
