<template>
  <el-dialog
    class="publish-print-task"
    :visible.sync="modalIsShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    append-to-body
    fullscreen
    destroy-on-close
    @opened="visibleChange"
  >
    <div slot="title">
      <span class="el-dialog__title">发布印刷任务</span>
      <button class="el-dialog__headerbtn" @click="close"></button>
    </div>
    <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>
    <div class="mb-2">
      <el-button :disabled="curPlanSubmit" type="primary" @click="toAdd"
        >增加考试对象</el-button
      >
      <el-button
        type="success"
        :loading="loading"
        :disabled="curPlanSubmit || !tableData.length"
        @click="toSubmit"
        >发布</el-button
      >
    </div>
    <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="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
            v-if="!curPlanSubmit"
            class="btn-primary"
            type="text"
            @click="toEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            v-if="scope.row.status === 'NEW' || scope.row.status === 'READY'"
            class="btn-danger"
            type="text"
            @click="toDelete(scope.row)"
            >取消</el-button
          >
          <el-button
            v-if="scope.row.status === 'WAITING'"
            class="btn-danger"
            type="text"
            @click="toCancel(scope.row)"
            >撤回提交</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <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, submitTaskPrint } from "../api";
import { cancelPrintTask } from "../../print/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,
      filter: {
        printPlanName: "",
        printPlanId: "",
        examStartTime: "",
        examEndTime: "",
        paperNumber: "",
        courseName: "",
        courseCode: ""
      },
      loading: false,
      curPlanSubmit: false,
      timeDisabled: false,
      tableData: [],
      curRow: {},
      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 = {};
      this.timeDisabled = false;
      this.createDate = "";
      this.createTime = [...this.curCreateTime];
      this.curPlanSubmit = false;
    },
    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.list) {
        this.tableData = data.list.map(item => {
          item.extends = {};
          const extendFields = item.extendFields
            ? JSON.parse(item.extendFields)
            : [];
          extendFields.forEach(field => {
            item.extends[field.code] = field.value;
          });
          return item;
        });
      } else {
        this.tableData = [];
      }
      this.curPlanSubmit = data.submit;
      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;
      }
    },
    printPlanChange(val) {
      if (!val) {
        this.timeDisabled = false;
        this.createDate = "";
        this.createTime = [...this.curCreateTime];
        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;
    },
    async close() {
      if (this.tableData.length && !this.curPlanSubmit) {
        const result = await this.$confirm(
          `当前印刷计划下印刷任务还没有发布，是否要发布?`,
          "提示",
          {
            type: "warning"
          }
        ).catch(() => {});
        if (result === "confirm") {
          await this.sumbitTask();
        }
      }
      this.cancel();
    },
    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 toSubmit() {
      const result = await this.$confirm(
        `确定要发布当前计划所有印刷任务吗?`,
        "提示",
        {
          type: "warning"
        }
      ).catch(() => {});
      if (result !== "confirm") return;

      await this.sumbitTask();
      this.cancel();
    },
    async sumbitTask() {
      const datas = {
        printPlanId: this.filter.printPlanId,
        list: this.tableData.map(item => item.examDetailId)
      };
      this.loading = true;
      const res = await submitTaskPrint(datas).catch(() => {});
      this.loading = false;
      if (!res) return;

      this.curPlanSubmit = true;
      this.$message.success("印刷任务发布成功！");
    },
    async toCancel(row) {
      const result = await this.$confirm(`确定撤回该印刷任务吗？`, "提示", {
        type: "warning"
      }).catch(() => {});
      if (result !== "confirm") return;

      const data = await cancelPrintTask(row.examDetailId);
      if (!data) return;

      this.$message.success("撤回成功！");
      this.getList();
    },
    async toDelete(row) {
      const result = await this.$confirm(`确定要取消当前卷袋吗?`, "提示", {
        type: "warning"
      }).catch(() => {});
      if (result !== "confirm") return;

      await removeTaskPrint(row.id);
      this.$message.success("取消成功！");
      this.getList();
    }
  }
};
</script>
