<template>
  <div class="print-task-manage">
    <div class="part-box part-box-filter part-box-flex">
      <el-form ref="FilterForm" label-position="left" label-width="85px" inline>
        <el-form-item label="印刷计划：">
          <print-plan-select
            v-model.trim="filter.printPlanId"
            placeholder="请选择"
            clearable
            @change="printPlanChange"
          ></print-plan-select>
        </el-form-item>
        <el-form-item label="印刷状态：">
          <el-select
            v-model="filter.status"
            style="width: 100px;"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="(val, key) in PRINT_TASK_STATUS"
              :key="key"
              :value="key"
              :label="val"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程（代码）：" label-width="110px">
          <course-select
            v-model.trim="filter.courseCode"
            :print-plan-id="filter.printPlanId"
            placeholder="请选择"
            clearable
          ></course-select>
        </el-form-item>
        <el-form-item label="试卷编号：">
          <paper-number-select
            ref="PaperNumberSelect"
            v-model="filter.paperNumber"
            :print-plan-id="filter.printPlanId"
            placeholder="请选择"
            clearable
          ></paper-number-select>
        </el-form-item>
        <el-form-item label="考点：" label-width="55px">
          <place-select
            v-model.trim="filter.examPlace"
            :print-plan-id="filter.printPlanId"
            placeholder="请选择"
            clearable
          ></place-select>
        </el-form-item>
        <el-form-item label="考场：" label-width="55px">
          <room-select
            v-model.trim="filter.examRoom"
            :print-plan-id="filter.printPlanId"
            placeholder="请选择"
            clearable
          ></room-select>
        </el-form-item>
        <el-form-item label="考试日期：">
          <el-date-picker
            v-model="createTime"
            type="daterange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="timestamp"
            align="right"
            unlink-panels
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label-width="0px">
          <el-button type="primary" icon="el-icon-search" @click="search"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="part-box-action">
        <el-button
          icon="el-icon-download"
          type="primary"
          :disabled="loading"
          @click="toExport"
        >
          批量下载PDF
        </el-button>
      </div>
    </div>
    <div class="part-box part-box-flex">
      <p>
        <span class="mr-4"
          >科次总计：<i class="color-primary">{{ totalInfo.totalSubjects }}</i>
          科次</span
        >
        <span class="mr-4"
          >试卷总计：<i class="color-primary">{{ totalInfo.paperCount }}</i>
          个</span
        >
        <span class="mr-4"
          >卷袋数量总计：<i class="color-primary">{{
            totalInfo.packageCount
          }}</i>
          个</span
        >
        <span class="mr-4"
          >A3印量总计：<i class="color-primary">{{ totalInfo.pagesA3 }}</i>
          张</span
        >
        <span class="mr-4"
          >A4印量总计：<i class="color-primary">{{ totalInfo.pagesA4 }}</i>
          张</span
        >
      </p>
      <p>
        <span class="mr-4"
          >A3剩余印量：<i class="color-primary">{{ totalInfo.pagesA3Left }}</i>
          张</span
        >
        <span
          >A4剩余印量：<i class="color-primary">{{ totalInfo.pagesA4Left }}</i>
          张</span
        >
      </p>
    </div>
    <div class="part-box">
      <el-table
        ref="TableList"
        :data="dataList"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="60"
          align="center"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column prop="packageCode" label="卷袋编号"></el-table-column>
        <el-table-column
          prop="printPlanName"
          label="印刷计划"
        ></el-table-column>
        <el-table-column
          prop="examDate"
          label="考试日期"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="examTime"
          label="考试时间"
          width="100"
        ></el-table-column>
        <el-table-column prop="courseNameCode" label="课程（代码）">
        </el-table-column>
        <el-table-column prop="paperNumber" label="试卷编号"></el-table-column>
        <el-table-column prop="examPlace" label="考点"></el-table-column>
        <el-table-column prop="examRoom" label="考场"></el-table-column>
        <el-table-column
          prop="singlePagesA3"
          label="单科次准印量A3(页)"
          width="80"
        ></el-table-column>
        <el-table-column
          prop="totalSubjects"
          label="科次"
          width="80"
        ></el-table-column>
        <el-table-column
          prop="pagesA3"
          label="A3准印量小计(页)"
          width="80"
        ></el-table-column>
        <el-table-column
          prop="pagesA4"
          label="A4准印量小计(页)"
          width="80"
        ></el-table-column>
        <el-table-column prop="status" label="印刷状态" width="80">
          <span slot-scope="scope">{{
            scope.row.status | printTaskStatusFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="validate" label="是否校验" width="80">
          <span slot-scope="scope">{{ scope.row.validate ? "是" : "否" }}</span>
        </el-table-column>
        <el-table-column prop="printStartTime" label="打印开始时间" width="160">
          <span slot-scope="scope">{{
            scope.row.printStartTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="printEndTime" label="打印完成时间" width="160">
          <span slot-scope="scope">{{
            scope.row.printEndTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          align="center"
          width="120px"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              class="btn-table-icon"
              type="text"
              icon="icon icon-download-act"
              @click="toViewPdf(scope.row)"
              title="查看pdf"
            ></el-button>
            <el-button
              v-if="scope.row.status === 'READY'"
              class="btn-table-icon"
              type="text"
              icon="icon icon-circle-share"
              @click="toSubmit(scope.row)"
              title="提交印刷"
            ></el-button>
            <el-button
              v-if="scope.row.status === 'PRINTING'"
              class="btn-table-icon"
              type="text"
              icon="icon icon-circle-share"
              @click="toResubmit(scope.row)"
              title="重新提交"
            ></el-button>
            <el-button
              v-if="scope.row.status === 'WAITING'"
              class="btn-table-icon"
              type="text"
              icon="icon icon-close-act"
              @click="toCancel(scope.row)"
              title="撤回提交"
            ></el-button>
            <!-- <el-button
              class="btn-table-icon"
              type="text"
              icon="icon icon-circle-right"
              @click="toPreview(scope.row)"
              title="查看印品模板"
            ></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>

    <!-- PreviewPrintTaskTemplate-->
    <preview-print-task-template
      :instance="curTask"
      ref="PreviewPrintTaskTemplate"
    ></preview-print-task-template>
  </div>
</template>

<script>
import {
  printTaskListPage,
  submitPrintTask,
  resubmitPrintTask,
  cancelPrintTask,
  printTaskTotalInfo,
  getPrintTaskPdf,
  downloadPrintTaskPdf
} from "../api";
import { PRINT_TASK_STATUS } from "@/constants/enumerate";
import pickerOptions from "@/constants/datePickerOptions";
import { parseTimeRangeDateAndTime } from "@/plugins/utils";
import PreviewPrintTaskTemplate from "../components/PreviewPrintTaskTemplate";

export default {
  name: "print-task-manage",
  components: { PreviewPrintTaskTemplate },
  data() {
    return {
      filter: {
        printPlanId: "",
        status: "",
        courseCode: "",
        paperNumber: "",
        examPlace: "",
        examRoom: "",
        examStartTime: "",
        examEndTime: ""
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      totalInfo: {},
      dataList: [],
      curRow: {},
      multipleSelection: [],
      PRINT_TASK_STATUS,
      loading: false,
      // view-template
      curTask: {},
      // date-picker
      createTime: [],
      pickerOptions
    };
  },
  created() {
    this.search();
  },
  methods: {
    async getList() {
      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size
      };
      if (this.createTime) {
        datas.examStartTime = this.createTime[0];
        datas.examEndTime = this.createTime[1];
      }
      const data = await printTaskListPage(datas);
      this.dataList = data.records.map(item => {
        const { date, time } = parseTimeRangeDateAndTime(
          item.examStartTime,
          item.examEndTime
        );
        item.examDate = date;
        item.examTime = time;
        return item;
      });
      this.total = data.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
      this.multipleSelection = [];
    },
    search() {
      this.toPage(1);
      this.getTotalInfo();
    },
    printPlanChange() {
      this.filter.paperNumber = "";
      this.filter.courseCode = "";
      this.filter.examRoom = "";
      this.filter.examPlace = "";
    },
    async getTotalInfo() {
      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size
      };
      if (this.createTime) {
        datas.examStartTime = this.createTime[0];
        datas.examEndTime = this.createTime[1];
      }
      const data = await printTaskTotalInfo(datas);
      this.totalInfo = data || {};
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.examDetailId);
    },
    toPreview(row) {
      this.curTask = row;
      this.$refs.PreviewPrintTaskTemplate.open();
    },
    toSubmit(row) {
      this.$confirm("确定提交该印刷任务吗？", "提示", {
        cancelButtonClass: "el-button--danger is-plain",
        confirmButtonClass: "el-button--primary",
        type: "warning"
      })
        .then(async () => {
          const data = await submitPrintTask(row.examDetailId);
          if (!data) return;

          this.$message.success("提交成功！");
          this.getList();
        })
        .catch(() => {});
    },
    toResubmit(row) {
      this.$confirm("确定重新提交该印刷任务吗？", "提示", {
        cancelButtonClass: "el-button--danger is-plain",
        confirmButtonClass: "el-button--primary",
        type: "warning"
      })
        .then(async () => {
          const data = await resubmitPrintTask({
            id: row.examDetailId,
            printPlanId: row.printPlanId
          });
          if (!data) return;

          this.$message.success("提交成功！");
          this.getList();
        })
        .catch(() => {});
    },
    toCancel(row) {
      this.$confirm("确定撤回该印刷任务的提交吗？", "提示", {
        cancelButtonClass: "el-button--danger is-plain",
        confirmButtonClass: "el-button--primary",
        type: "warning"
      })
        .then(async () => {
          const data = await cancelPrintTask(row.examDetailId);
          if (!data) return;

          this.$message.success("撤回成功！");
          this.getList();
        })
        .catch(() => {});
    },
    async toViewPdf(row) {
      let result = true;
      const data = await getPrintTaskPdf(row.examDetailId).catch(() => {
        result = false;
      });
      if (!result) return;
      if (data) {
        window.open(data);
      } else {
        this.$message.error("当前任务pdf还未生成好，请稍后再试！");
      }
    },
    async toExport() {
      if (this.loading) return;

      if (!this.multipleSelection.length) {
        this.$message.error("请选择要下载的记录！");
        return;
      }

      this.loading = true;
      const data = await downloadPrintTaskPdf(this.multipleSelection);
      this.loading = false;
      if (!data) return;

      this.$message.success("文件下载任务提交成功！");
    }
  }
};
</script>
