<template>
  <el-dialog
    class="publish-print-task"
    :visible.sync="modalIsShow"
    title="发布印刷任务"
    fullscreen
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @opened="visibleChange"
  >
    <div class="md-4">
      <el-form ref="FilterForm" label-position="left" label-width="0" inline>
        <el-form-item>
          <print-plan-select
            v-model.trim="filter.printPlanId"
            placeholder="印刷计划"
            clearable
            @change="printPlanChange"
          ></print-plan-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="createDate"
            type="date"
            :disabled="timeDisabled"
            value-format="timestamp"
            placeholder="考试日期"
            style="width: 150px"
            @change="timeChange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-time-picker
            is-range
            v-model="createTime"
            range-separator="至"
            start-placeholder="考试开始时间"
            end-placeholder="考试结束时间"
            placeholder="选择时间范围"
            value-format="timestamp"
            :disabled="timeDisabled"
            @change="timeChange"
          >
          </el-time-picker>
        </el-form-item>
      </el-form>
    </div>
    <el-button class="mb-2" type="primary" @click="toAdd"
      >增加考试对象</el-button
    >
    <el-table ref="TableList" :data="tableData">
      <el-table-column type="index" width="80" label="卷袋序号">
      </el-table-column>
      <el-table-column prop="examRoom" label="考场"> </el-table-column>
      <el-table-column prop="examPlace" label="考点"> </el-table-column>
      <el-table-column prop="invigilatorTeacher" label="监考老师">
      </el-table-column>
      <el-table-column prop="className" label="考试对象"> </el-table-column>
      <el-table-column prop="studentCount" label="人数"> </el-table-column>
      <el-table-column prop="printHouseName" label="印刷室"> </el-table-column>
      <el-table-column
        v-for="item in extendFields"
        :key="item.code"
        :label="item.name"
      >
        <div slot-scope="scope">
          {{ scope.row.extends[item.code] }}
        </div>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template slot-scope="scope">
          <el-button
            class="btn-primary"
            type="text"
            @click="toPreview(scope.row)"
            >考生明细</el-button
          >
          <el-button class="btn-primary" type="text" @click="toEdit(scope.row)"
            >编辑</el-button
          >
          <el-button class="btn-danger" type="text" @click="toDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="part-page">
      <el-pagination
        background
        layout="total,prev, pager, next"
        :current-page="current"
        :total="total"
        :page-size="size"
        @current-change="toPage"
      >
      </el-pagination>
    </div>

    <div slot="footer"></div>

    <!-- CreatePrintTask -->
    <create-print-task
      ref="CreatePrintTask"
      :instance="curRow"
      :clazzs="clazzs"
      :extend-fields="extendFields"
      @modified="getList"
    ></create-print-task>
    <!-- PrintTaskStudents -->
    <print-task-students
      ref="PrintTaskStudents"
      :class-id="curClassId"
    ></print-task-students>
  </el-dialog>
</template>

<script>
import { listTaskPrint, removeTaskPrint } from "../api";
import { examRuleDetail } from "../../base/api";
import CreatePrintTask from "./CreatePrintTask";
import PrintTaskStudents from "./PrintTaskStudents";
import { getTimeDatestamp } from "@/plugins/utils";

export default {
  name: "publish-print-task",
  components: { CreatePrintTask, PrintTaskStudents },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      filter: {
        printPlanName: "",
        printPlanId: "",
        examStartTime: "",
        examEndTime: "",
        paperNumber: "",
        courseName: "",
        courseCode: ""
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      timeDisabled: false,
      tableData: [],
      curRow: {},
      printRooms: [],
      teachers: [],
      clazzs: [],
      curClassId: "",
      extendFields: [],
      // date-picker
      curCreateTime: [],
      createDate: "",
      createTime: []
    };
  },
  created() {
    this.getExtendFields();

    const curDate = getTimeDatestamp(Date.now());
    const hour = 60 * 60 * 1000;
    this.curCreateTime = [curDate + 8 * hour, curDate + 10 * hour];
    this.createTime = [...this.curCreateTime];
  },
  methods: {
    visibleChange() {
      this.filter = this.$objAssign(this.filter, this.instance);
      this.tableData = [];
      this.curRow = {};
    },
    async getExtendFields() {
      const examRule = await examRuleDetail();
      this.extendFields = examRule.extendFields
        ? JSON.parse(examRule.extendFields)
        : [];
    },
    async getList() {
      const datas = {
        printPlanId: this.filter.printPlanId,
        courseCode: this.instance.courseCode,
        paperNumber: this.instance.paperNumber,
        pageNumber: this.current,
        pageSize: this.size
      };
      const data = await listTaskPrint(datas);
      if (data.iPage) {
        this.tableData = data.iPage.records.map(item => {
          item.extends = {};
          const extendFields = item.extendFields
            ? JSON.parse(item.extendFields)
            : [];
          extendFields.forEach(field => {
            item.extends[field.code] = field.value;
          });
          return item;
        });
        this.total = data.iPage.total;
      } else {
        this.tableData = [];
      }
      if (data.examStartTime && data.examEndTime) {
        this.createTime = [data.examStartTime, data.examEndTime];
        this.createDate = getTimeDatestamp(data.examStartTime);
        this.filter.examStartTime = this.createTime[0];
        this.filter.examEndTime = this.createTime[1];
        this.timeDisabled = true;
      } else {
        this.createTime = [...this.curCreateTime];
        this.createDate = null;
        this.filter.examStartTime = "";
        this.filter.examEndTime = "";
        this.timeDisabled = false;
      }
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    printPlanChange(val) {
      if (!val) return;
      this.filter.printPlanName = val && val.name;
      this.getList();
    },
    timeChange() {
      if (!this.createDate || !this.createTime) {
        this.filter.examStartTime = null;
        this.filter.examEndTime = null;
        return;
      }

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

      this.filter.examStartTime = curDate + this.createTime[0] - timeDate;
      this.filter.examEndTime = curDate + this.createTime[1] - timeDate;
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    toAdd() {
      if (
        !this.filter.printPlanId ||
        !this.filter.examStartTime ||
        !this.filter.examEndTime
      ) {
        this.$message.error("请选择印刷计划和考试时间！");
        return;
      }

      if (this.filter.examStartTime === this.filter.examEndTime) {
        this.$message.error("考试开始时间不能等于考试结束时间！");
        return;
      }

      this.curRow = {
        examPlace: "",
        examRoom: "",
        invigilatorTeacher: "",
        classId: "",
        className: "",
        studentCount: null,
        printHouseId: null,
        printHouseName: null,
        ...this.filter
      };
      this.$refs.CreatePrintTask.open();
    },
    toEdit(row) {
      this.curRow = { ...row, ...this.filter };
      this.$refs.CreatePrintTask.open();
    },
    toPreview(row) {
      this.curClassId = row.classId;
      this.$refs.PrintTaskStudents.open();
    },
    async toDelete(row) {
      const result = await this.$confirm(`确定要删除当前卷袋吗?`, "提示", {
        type: "warning"
      }).catch(() => {});
      if (result !== "confirm") return;

      await removeTaskPrint(row.id);
      this.$message.success("删除成功！");
      this.deletePageLastItem();
    }
  }
};
</script>
