<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>
        <template v-if="checkPrivilege('condition', 'condition')">
          <el-form-item label="学期：">
            <semester-select
              v-model.trim="filter.semesterId"
              placeholder="学期"
              clearable
            ></semester-select>
          </el-form-item>
          <el-form-item label="考试：">
            <exam-select
              v-model="filter.examId"
              :semester-id="filter.semesterId"
            ></exam-select>
          </el-form-item>
          <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="印刷室：">
            <print-room-select
              v-model.trim="filter.printHouseId"
              placeholder="印刷室"
              clearable
              @change="printPlanChange"
            ></print-room-select>
          </el-form-item>
          <el-form-item label="印刷状态：">
            <el-select
              v-model="filter.status"
              style="width: 120px;"
              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="打印时间：">
            <el-date-picker
              v-model="printTime"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="打印开始时间"
              end-placeholder="打印结束时间"
              value-format="timestamp"
              align="right"
              unlink-panels
            >
            </el-date-picker>
          </el-form-item>
        </template>
        <el-form-item label-width="0px">
          <el-button
            v-if="checkPrivilege('button', 'select')"
            type="primary"
            @click="search"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="part-box-action">
        <el-button
          v-if="checkPrivilege('button', 'BatchDownload')"
          icon="el-icon-download"
          type="primary"
          :disabled="loading"
          @click="toExport"
        >
          批量下载PDF
        </el-button>
      </div>
    </div>
    <div class="part-box part-box-pad box-justify">
      <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
          >总印量：<i class="color-primary">{{
            totalInfo.paperPages + totalInfo.cardPages
          }}</i>
          张</span
        >
        <span
          >（试卷：<i class="color-primary">{{ totalInfo.paperPages }}</i>
          张，</span
        >
        <span
          >题卡：<i class="color-primary">{{ totalInfo.cardPages }}</i>
          张）</span
        >
      </p>
      <p>
        <span
          >剩余印量：<i class="color-danger">{{
            totalInfo.paperPagesLeft + totalInfo.cardPagesLeft
          }}</i>
          张</span
        >
        <span
          >（试卷：<i class="color-danger">{{ totalInfo.paperPagesLeft }}</i>
          张，</span
        >
        <span
          >题卡：<i class="color-danger">{{ totalInfo.cardPagesLeft }}</i>
          张）</span
        >
      </p>
    </div>
    <div class="part-box part-box-pad">
      <el-table
        ref="TableList"
        :data="dataList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="60"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column
          prop="semesterName"
          label="学期"
          min-width="160"
        ></el-table-column>
        <el-table-column
          prop="examName"
          label="考试"
          min-width="160"
        ></el-table-column>
        <el-table-column
          prop="packageCode"
          label="卷袋编号"
          min-width="160"
        ></el-table-column>
        <el-table-column
          prop="printPlanName"
          label="印刷计划"
          min-width="200"
        ></el-table-column>
        <el-table-column
          prop="printHouseName"
          label="印刷室"
          min-width="160"
        ></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="课程（代码）"
          min-width="200"
        >
        </el-table-column>
        <el-table-column
          prop="paperNumber"
          label="试卷编号"
          min-width="160"
        ></el-table-column>
        <el-table-column
          prop="examPlace"
          label="考点"
          min-width="160"
        ></el-table-column>
        <el-table-column
          prop="examRoom"
          label="考场"
          min-width="160"
        ></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="170">
          <span slot-scope="scope">{{
            scope.row.printStartTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="printEndTime" label="打印完成时间" width="170">
          <span slot-scope="scope">{{
            scope.row.printEndTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="normal" label="任务状态" width="80">
          <span slot-scope="scope">{{
            scope.row.normal ? "正常" : "作废"
          }}</span>
        </el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          width="160"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              v-if="checkPrivilege('link', 'download')"
              class="btn-primary"
              type="text"
              @click="toViewPdf(scope.row)"
              >查看pdf</el-button
            >
            <el-button
              v-if="
                scope.row.status === 'READY' && checkPrivilege('link', 'submit')
              "
              class="btn-primary"
              type="text"
              @click="toSubmit(scope.row)"
              >提交印刷</el-button
            >
            <!-- <el-button
              v-if="scope.row.status === 'PRINTING'"
              class="btn-primary"
              type="text"
              @click="toResubmit(scope.row)"
            >重新提交</el-button> -->
            <el-button
              v-if="
                scope.row.status === 'WAITING' && checkPrivilege('link', 'end')
              "
              class="btn-danger"
              type="text"
              @click="toCancel(scope.row)"
              >撤回提交</el-button
            >
            <el-button
              v-if="
                (scope.row.status === 'END' ||
                  scope.row.status === 'PRINT_FINISH') &&
                  checkPrivilege('link', 'normal')
              "
              :class="scope.row.normal ? 'btn-danger' : 'btn-primary'"
              type="text"
              @click="toNormal(scope.row)"
              >{{ scope.row.normal ? "作废" : "恢复" }}</el-button
            >
            <!-- <el-button
              class="btn-primary"
              type="text"
              @click="toPreview(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>

    <!-- PreviewPrintTaskTemplate-->
    <preview-print-task-template
      :instance="curTask"
      ref="PreviewPrintTaskTemplate"
    ></preview-print-task-template>
    <!-- pdf-view -->
    <el-dialog
      class="pdf-view-dialog"
      :visible.sync="padViewDialogVisible"
      title="请选择PDF类型"
      top="10vh"
      width="540px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-button
        v-for="item in pdfList"
        :key="item.name"
        type="primary"
        size="large"
        @click="viewPdf(item)"
        >{{ item.type | printPdfTypeFilter }}</el-button
      >
      <div slot="footer"></div>
    </el-dialog>
  </div>
</template>

<script>
import {
  printTaskListPage,
  submitPrintTask,
  resubmitPrintTask,
  cancelPrintTask,
  printTaskTotalInfo,
  getPrintTaskPdf,
  downloadPrintTaskPdf,
  printTaskNormal
} 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: {
        semesterId: "",
        examId: "",
        printPlanId: "",
        printHouseId: "",
        status: "",
        courseCode: "",
        paperNumber: "",
        examPlace: "",
        examRoom: "",
        examStartTime: "",
        examEndTime: "",
        printStartTime: "",
        printEndTime: ""
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      totalInfo: {},
      dataList: [],
      curRow: {},
      multipleSelection: [],
      PRINT_TASK_STATUS,
      loading: false,
      // view-pdf
      padViewDialogVisible: false,
      pdfList: [],
      // view-template
      curTask: {},
      // date-picker
      createTime: [],
      printTime: [],
      pickerOptions
    };
  },
  mounted() {
    this.search();
  },
  methods: {
    async getList() {
      if (!this.checkPrivilege("list", "list")) return;

      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size
      };
      if (this.createTime) {
        datas.examStartTime = this.createTime[0];
        datas.examEndTime = this.createTime[1];
      }
      if (this.printTime) {
        datas.printStartTime = this.printTime[0];
        datas.printEndTime = this.printTime[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("确定提交该印刷任务吗？", "提示", {
        type: "warning"
      })
        .then(async () => {
          const data = await submitPrintTask(row.examDetailId);
          if (!data) return;

          this.$message.success("提交成功！");
          this.getList();
        })
        .catch(() => {});
    },
    toResubmit(row) {
      this.$confirm("确定重新提交该印刷任务吗？", "提示", {
        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("确定撤回该印刷任务的提交吗？", "提示", {
        type: "warning"
      })
        .then(async () => {
          const data = await cancelPrintTask(row.examDetailId);
          if (!data) return;

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

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

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

      this.$message.success("文件下载任务提交成功！");
    },
    async toNormal(row) {
      const typeName = row.normal ? "作废" : "恢复";
      const action = await this.$confirm(
        `确定${typeName}该印刷任务吗？`,
        "提示",
        {
          type: "warning"
        }
      ).catch(() => {});
      if (action !== "confirm") return;

      const data = await printTaskNormal({
        id: row.examDetailId,
        normal: !row.normal
      });
      if (!data) return;

      row.normal = !row.normal;
      this.$message.success("撤回成功！");
    }
  }
};
</script>
