<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
          ></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="item in PRINT_STATUS_LIST"
              :key="item.key"
              :value="item.key"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程（代码）：" label-width="110px">
          <course-select
            v-model.trim="filter.courseCode"
            placeholder="请选择"
            clearable
          ></course-select>
        </el-form-item>
        <el-form-item label="试卷编号：">
          <paper-number-select
            ref="PaperNumberSelect"
            v-model="filter.paperNumber"
            placeholder="请选择"
            clearable
          ></paper-number-select>
        </el-form-item>
        <el-form-item label="考点：" label-width="55px">
          <place-select
            v-model.trim="filter.examPlace"
            placeholder="请选择"
            clearable
          ></place-select>
        </el-form-item>
        <el-form-item label="考场：" label-width="55px">
          <room-select
            v-model.trim="filter.examRoom"
            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="icon 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.packageCount
          }}</i>
          个</span
        >
        <span class="mr-4"
          >A3印量累计：<i class="color-primary">{{ totalInfo.pageA3 }}</i>
          张</span
        >
        <span class="mr-4"
          >A4印量累计：<i class="color-primary">{{ totalInfo.pageA4 }}</i>
          张</span
        >
      </p>
      <p>
        <span class="mr-4"
          >A3剩余印量：<i class="color-primary">{{ totalInfo.pageA3Left }}</i>
          张</span
        >
        <span
          >A4剩余印量：<i class="color-primary">{{ totalInfo.pageA4Left }}</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="55"></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="70"
          align="center"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column prop="packageCode" label="卷袋编号"></el-table-column>
        <el-table-column
          prop="printPlanName"
          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="courseNameCode" label="课程（代码）" width="160">
        </el-table-column>
        <el-table-column
          prop="paperNumber"
          label="试卷编号"
          width="120"
        ></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="pageA3" label="单科次A3(页)"></el-table-column>
        <el-table-column prop="pageA4" label="单科次A4(页)"></el-table-column>
        <el-table-column prop="totalSubjects" label="科次"></el-table-column>
        <el-table-column prop="totalPages" label="印刷小计"></el-table-column>
        <el-table-column prop="status" label="印刷状态">
          <span slot-scope="scope">{{
            scope.row.status | printStatusFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="validate" label="是否校验">
          <span slot-scope="scope">{{ scope.row.validate ? "是" : "否" }}</span>
        </el-table-column>
        <el-table-column prop="printTime" label="打印开始时间" width="160">
          <span slot-scope="scope">{{
            scope.row.printTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column
          prop="expectPrintTime"
          label="打印完成时间"
          width="160"
        >
          <span slot-scope="scope">{{
            scope.row.expectPrintTime | 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-circle-share"
              @click="toSubmit(scope.row)"
              title="提交印刷"
            ></el-button>
            <el-button
              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>
            <el-button
              class="btn-table-icon"
              type="text"
              icon="icon icon-download-act"
              @click="toViewPdf(scope.row)"
              title="查看pdf"
            ></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>
  </div>
</template>

<script>
import {
  printTaskListPage,
  submitPrintTask,
  cancelPrintTask,
  printTaskTotalInfo,
  getPrintTaskPdf
} from "../api";
import { PRINT_STATUS_LIST } from "@/constants/enumerate";
import { download, randomCode } from "@/plugins/utils";

export default {
  name: "print-task-manage",
  data() {
    return {
      filter: {
        printPlanId: "",
        status: "",
        courseCode: "",
        paperNumber: "",
        examPlace: "",
        examRoom: "",
        examStartTime: "",
        examEndTime: ""
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      totalInfo: {},
      dataList: [],
      curRow: {},
      createTime: [],
      multipleSelection: [],
      PRINT_STATUS_LIST,
      loading: false,
      // date-picker
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      }
    };
  },
  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;
      this.total = data.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
      this.multipleSelection = [];
    },
    search() {
      this.toPage(1);
      this.getTotalInfo();
    },
    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];
      }
      this.totalInfo = await printTaskTotalInfo(datas);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.id);
    },
    toPreview(row) {},
    toSubmit(row) {
      this.$confirm("确定提交该印刷计划吗？", "提示", {
        cancelButtonClass: "el-button--danger is-plain",
        confirmButtonClass: "el-button--primary",
        type: "warning"
      })
        .then(async () => {
          const data = await submitPrintTask(row.id);
          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.id);
          if (!data) return;

          this.$message.success("撤回成功！");
          this.getList();
        })
        .catch(() => {});
    },
    async toViewPdf(row) {
      const data = await getPrintTaskPdf(row.id);
      if (!data) return;
      window.open(data.path);
    },
    async toExport() {
      if (this.loading) return;

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

      this.loading = true;
      const res = await download({
        type: "post",
        url: this.GLOBAL.domain + "/api/exam/print_task/download_pdf",
        data: {
          examTaskIds: this.multipleSelection
        },
        fileName: `${Date.now()}${randomCode()}.zip`,
        header: {
          schoolId: this.$ls.get("schoolId"),
          userId: this.$ls.get("user", { id: "" }).id
        }
      }).catch(error => {
        this.$message.error(error + "文件下载失败，请重新尝试！");
      });
      this.loading = false;
      if (!res) return;
      this.$message.success("文件下载成功！");
    }
  }
};
</script>
