<template>
  <div class="print-task-manage">
    <div class="part-box part-box-filter">
      <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="学期"
              default-select
            ></semester-select>
          </el-form-item>
          <el-form-item label="考试：">
            <exam-select
              v-model="filter.examId"
              :semester-id="filter.semesterId"
              default-select
              @default-selected="search"
            ></exam-select>
          </el-form-item>
          <el-form-item label="印刷计划：">
            <print-plan-select
              v-model.trim="filter.printPlanId"
              placeholder="印刷计划"
              clearable
              :semester-id="filter.semesterId"
              :exam-id="filter.examId"
              @change="printPlanChange"
            ></print-plan-select>
          </el-form-item>
          <el-form-item label="课程（代码）：" label-width="110px">
            <course-select
              v-model.trim="filter.courseId"
              :semester-id="filter.semesterId"
              :exam-id="filter.examId"
              :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"
              :semester-id="filter.semesterId"
              :exam-id="filter.examId"
              :print-plan-id="filter.printPlanId"
              :course-id="filter.courseId"
              placeholder="试卷编号"
              clearable
            ></paper-number-select>
          </el-form-item>
          <el-form-item label="印刷室：">
            <print-room-select
              v-model.trim="filter.printHouseId"
              placeholder="印刷室"
              clearable
            ></print-room-select>
          </el-form-item>
          <el-form-item label="印刷状态：">
            <status-select
              v-model="filter.status"
              type="EXAM_DETAIL_STATUS_ENUM"
              placeholder="印刷状态"
              style="width: 120px"
              clearable
            >
            </status-select>
          </el-form-item>
          <el-form-item label="考点：" label-width="55px">
            <place-select
              v-model.trim="filter.examPlace"
              :exam-id="filter.examId"
              :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"
              :exam-id="filter.examId"
              :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="box-justify">
        <div>
          <el-button
            v-if="checkPrivilege('button', 'CreateWholePdf')"
            icon="el-icon-document"
            :disabled="!searchfilter.paperNumber"
            :loading="pdfLoading"
            :type="wholePdfInfo.status === 'RUNNING' ? 'default' : 'success'"
            @click="toViewWholePdf"
          >
            {{ wholePdfBtnName }}
          </el-button>
        </div>
        <div>
          <el-button
            v-if="checkPrivilege('button', 'BatchEnd')"
            icon="el-icon-finished"
            type="success"
            :disabled="searchfilter.status !== 'WAITING'"
            @click="toBatchCancelOrSubmit('finish')"
          >
            批量完成
          </el-button>
          <el-button
            v-if="checkPrivilege('button', 'BatchEnd')"
            icon="el-icon-bottom-left"
            type="danger"
            :disabled="searchfilter.status !== 'WAITING'"
            @click="toBatchCancelOrSubmit('cancel')"
          >
            批量撤回
          </el-button>
          <el-button
            v-if="checkPrivilege('button', 'BatchEnd')"
            icon="el-icon-top-right"
            type="primary"
            :disabled="searchfilter.status !== 'READY'"
            @click="toBatchCancelOrSubmit('submit')"
          >
            批量提交
          </el-button>
          <el-button
            v-if="checkPrivilege('button', 'BatchDownload')"
            icon="el-icon-download"
            type="primary"
            :disabled="loading"
            @click="toExport"
          >
            批量下载PDF
          </el-button>
          <el-button
            v-if="checkPrivilege('button', 'BatchDownload')"
            type="primary"
            icon="el-icon-s-order"
            @click="toDataTask"
            >下载结果查询</el-button
          >
        </div>
      </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"
          fixed="left"
          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="210"
        ></el-table-column>
        <el-table-column
          prop="examName"
          label="考试"
          min-width="160"
        ></el-table-column> -->
        <el-table-column
          prop="printPlanName"
          label="印刷计划"
          min-width="240"
        ></el-table-column>
        <el-table-column
          prop="courseNameCode"
          label="课程（代码）"
          min-width="260"
        >
        </el-table-column>
        <el-table-column
          prop="paperNumber"
          label="试卷编号"
          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="packageCode"
          label="卷袋编号"
          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="printHouseName"
          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="statusDisplay" label="印刷状态" width="80">
        </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') &&
                (scope.row.status === 'READY' ||
                  scope.row.status === 'WAITING' ||
                  scope.row.status === 'PRINTING' ||
                  scope.row.status === 'FINISH' ||
                  scope.row.status === 'CANCEL')
              "
              class="btn-primary"
              type="text"
              @click="toActionPdf(scope.row, 'view')"
              >预览</el-button
            >
            <el-button
              v-if="
                checkPrivilege('link', 'createpdf') &&
                (scope.row.status === 'READY' ||
                  scope.row.status === 'CANCEL' ||
                  !scope.row.normal)
              "
              class="btn-primary"
              type="text"
              @click="toActionPdf(scope.row, 'build')"
              >重新生成</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 === '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, sizes, prev, pager, next, jumper"
          :pager-count="5"
          :current-page="current"
          :total="total"
          :page-size="size"
          @current-change="toPage"
          @size-change="pageSizeChange"
        >
        </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="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <div class="text-center">
        <el-button
          v-if="actionType === 'build'"
          size="large"
          @click="actionPdf({ type: undefined })"
          >全部</el-button
        >
        <el-button
          v-for="item in pdfList"
          :key="item.name"
          type="primary"
          size="large"
          @click="actionPdf(item)"
          >{{ item.type | printPdfTypeFilter }}</el-button
        >
      </div>
      <div slot="footer"></div>
    </el-dialog>
    <!-- data-task-dialog -->
    <data-task-dialog
      v-if="checkPrivilege('button', 'BatchDownload')"
      ref="DataTaskDialog"
      task-type="PRINT_PDF_DOWNLOAD"
    ></data-task-dialog>

    <!-- PreviewAttachment -->
    <preview-attachment
      ref="PreviewAttachment"
      :attachment-id="curAttachmentId"
    ></preview-attachment>

    <!-- PreviewFile -->
    <preview-file ref="PreviewFile" :data="curFile"></preview-file>
  </div>
</template>

<script>
import {
  printTaskListPage,
  submitPrintTask,
  resubmitPrintTask,
  cancelPrintTask,
  batchCancelPrintTask,
  printTaskTotalInfo,
  getPrintTaskPdf,
  downloadPrintTaskPdf,
  rebuildPrintTaskPdf,
  printTaskNormal,
  getPrintTaskWholePdf,
  createPrintTaskWholePdf,
} from "../api";
import { PRINT_TASK_STATUS } from "@/constants/enumerate";
import pickerOptions from "@/constants/datePickerOptions";
import { parseTimeRangeDateAndTime } from "@/plugins/utils";
import PreviewPrintTaskTemplate from "../components/PreviewPrintTaskTemplate";
import PreviewAttachment from "@/components/PreviewAttachment.vue";
import PreviewFile from "@/components/PreviewFile.vue";

const defaultTotalInfo = {
  totalSubjects: 0,
  packageCount: 0,
  paperCount: 0,
  paperPages: 0,
  cardPages: 0,
  pagesA4: 0,
  paperPagesLeft: 0,
  cardPagesLeft: 0,
  pagesA4Left: 0,
};

export default {
  name: "print-task-manage",
  components: { PreviewPrintTaskTemplate, PreviewAttachment, PreviewFile },
  data() {
    return {
      filter: {
        semesterId: "",
        examId: "",
        printPlanId: "",
        printHouseId: "",
        status: "",
        courseId: "",
        paperNumber: "",
        examPlace: "",
        examRoom: "",
        examStartTime: "",
        examEndTime: "",
        printStartTime: "",
        printEndTime: "",
      },
      searchfilter: {},
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      totalInfo: { ...defaultTotalInfo },
      dataList: [],
      curRow: {},
      multipleSelection: [],
      PRINT_TASK_STATUS,
      loading: false,
      // attachmentId preview
      curAttachmentId: "",
      // view-pdf
      padViewDialogVisible: false,
      pdfList: [],
      actionType: "view",
      // view-template
      curTask: {},
      // whole pdf
      wholePdfInfo: {
        status: "INIT",
        url: "",
      },
      pdfLoading: false,
      // date-picker
      createTime: [],
      printTime: [],
      pickerOptions,
      // preview file
      curFile: {
        url: "",
        type: "",
      },
    };
  },
  computed: {
    wholePdfBtnName() {
      if (this.wholePdfInfo.status === "RUNNING") {
        return "生成pdf中...";
      }
      if (this.wholePdfInfo.status === "FINISH" && this.wholePdfInfo.url) {
        return "查看合并PDF";
      }
      return "生成合并PDF";
    },
  },
  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;
      this.searchfilter = { ...this.filter };
    },
    toPage(page) {
      this.current = page;
      this.getList();
      this.multipleSelection = [];
    },
    search() {
      this.toPage(1);
      this.getTotalInfo();
      this.fetchWholePdf();
    },

    printPlanChange() {
      this.filter.paperNumber = "";
      this.filter.courseId = "";
      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 || { ...defaultTotalInfo };
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map((item) => item.examDetailId);
    },
    async fetchWholePdf() {
      if (!this.checkPrivilege("button", "CreateWholePdf")) return;
      if (!this.filter.paperNumber) {
        this.wholePdfInfo = { status: "INIT", url: "" };
        return;
      }
      this.wholePdfInfo = await getPrintTaskWholePdf({
        examId: this.filter.examId,
        courseId: this.filter.courseId,
        paperNumber: this.filter.paperNumber,
      });
    },
    async toViewWholePdf() {
      if (this.wholePdfInfo.status === "RUNNING") {
        return;
      }
      if (this.wholePdfInfo.url && this.wholePdfInfo.status === "FINISH") {
        this.curFile = {
          url: this.wholePdfInfo.url,
          type: "application/pdf",
        };
        this.$refs.PreviewFile.open();
        // window.open(this.wholePdfInfo.url);
        return;
      }

      if (this.pdfLoading) return;
      this.pdfLoading = true;

      const res = await createPrintTaskWholePdf({
        examId: this.filter.examId,
        courseId: this.filter.courseId,
        paperNumber: this.filter.paperNumber,
      }).catch(() => {});
      this.pdfLoading = false;

      if (!res) return;
      this.$message.success("生成任务已经提交");
      this.wholePdfInfo.status = "RUNNING";
    },
    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(() => {});
    },
    toBatchCancelOrSubmit(type) {
      const names = {
        finish: "完成",
        submit: "提交",
        cancel: "撤回",
      };
      const name = names[type];
      if (!this.multipleSelection.length) {
        this.$message.error(`请选择要${name}的记录！`);
        return;
      }
      this.$confirm(`确定${name}选中的印刷任务的提交吗？`, "提示", {
        type: "warning",
      })
        .then(async () => {
          const data = await batchCancelPrintTask(
            this.multipleSelection.join(),
            type
          );
          if (!data) return;

          this.$message.success("操作成功！");
          this.getList();
        })
        .catch(() => {});
    },
    async toActionPdf(row, actionType) {
      this.curTask = row;
      this.actionType = actionType;
      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.actionPdf(data[0]);
      } else {
        this.pdfList = data;
        this.padViewDialogVisible = true;
      }
    },
    actionPdf(item) {
      if (this.actionType === "view") {
        this.viewPdf(item);
      } else {
        this.rebuildPdf(item);
      }
    },
    toViewAttachment(curAttachmentId) {
      this.curAttachmentId = curAttachmentId;
      this.$refs.PreviewAttachment.open();
    },
    async rebuildPdf(item) {
      const action = await this.$confirm(
        `确定要重新生成该印刷任务PDF吗？`,
        "提示",
        {
          type: "warning",
        }
      ).catch(() => {});
      if (action !== "confirm") return;

      const res = await rebuildPrintTaskPdf(
        this.curTask.examDetailId,
        item.type
      );
      if (!res) return;
      this.$message.success("操作成功！");
      this.padViewDialogVisible = false;
      this.getList();
    },
    viewPdf(item) {
      this.curFile = {
        url: item.url,
        type: "application/pdf",
      };
      this.$refs.PreviewFile.open();
      // 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("文件下载任务提交成功！");
    },
    toDataTask() {
      this.$refs.DataTaskDialog.open();
    },
    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>
