<template>
  <div class="data-task-manage">
    <div class="part-box part-box-filter part-box-flex">
      <el-form ref="FilterForm" label-position="left" label-width="55px" inline>
        <template v-if="checkPrivilege('condition', 'condition')">
          <secp-select
            v-model="filter"
            defaultSelectExam
            @exam-default="toPage(1)"
          ></secp-select>
          <el-form-item label="状态：">
            <el-select
              v-model="filter.status"
              placeholder="状态"
              clearable
              style="width: 120px"
            >
              <el-option
                v-for="(val, key) in DATA_TASK_STATUS"
                :key="key"
                :value="key"
                :label="val"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数据结果：" label-width="85px">
            <el-select
              v-model="filter.result"
              placeholder="数据结果"
              clearable
              style="width: 120px"
            >
              <el-option
                v-for="(val, key) in DATA_TASK_RESULT"
                :key="key"
                :value="key"
                :label="val"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="考点：">
            <el-input
              v-model.trim="filter.examPlace"
              placeholder="考点"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="考场：">
            <el-input
              v-model.trim="filter.examRoom"
              placeholder="考场"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="考试时间：">
            <el-date-picker
              v-model="createTime"
              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>
          <el-button
            v-if="checkPrivilege('button', 'select')"
            type="primary"
            @click="toPage(1)"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="part-box part-box-pad">
      <el-table ref="TableList" :data="dataList">
        <el-table-column
          type="index"
          label="序号"
          width="50"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column
          prop="paperNumber"
          label="试卷编号"
          min-width="100"
        ></el-table-column>
        <el-table-column
          prop="courseNameCode"
          label="课程（代码）"
          min-width="200"
        >
        </el-table-column>
        <el-table-column
          prop="printPlanName"
          label="项目"
          min-width="120"
        ></el-table-column>
        <el-table-column prop="createTypeDisplay" label="类别" width="160">
        </el-table-column>
        <el-table-column prop="examPlace" label="考点" width="160">
        </el-table-column>
        <el-table-column prop="examRoom" label="考场" width="160">
        </el-table-column>
        <el-table-column prop="statusDisplay" label="状态" width="100">
        </el-table-column>
        <el-table-column prop="resultDisplay" label="结果" width="100">
        </el-table-column>
        <el-table-column prop="examStartTime" label="考试开始时间" width="170">
          <span slot-scope="scope">{{
            scope.row.examStartTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="examEndTime" label="考试结束时间" width="170">
          <span slot-scope="scope">{{
            scope.row.examEndTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          width="160px"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              v-if="checkPrivilege('link', 'createPdf')"
              class="btn-primary"
              type="text"
              @click="toViewLog(scope.row)"
              >查看日志</el-button
            >
            <el-button
              v-if="
                checkPrivilege('link', 'createPdf') &&
                scope.row.status === 'FINISH'
              "
              class="btn-primary"
              type="text"
              :disabled="loading"
              @click="toResetCreatePdf(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>

    <el-dialog
      class="log-dialog"
      :visible.sync="modalIsShow"
      title="日志"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      top="10vh"
      width="800px"
    >
      <div style="min-height: 300px; overflow: auto">
        <p v-for="(cont, cidx) in logList" :key="cidx">{{ cont }}</p>
      </div>
    </el-dialog>
    <!-- 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 size="large" @click="rebuildPdf({ type: undefined })"
          >全部</el-button
        >
        <el-button
          v-for="item in pdfList"
          :key="item.name"
          type="primary"
          size="large"
          @click="rebuildPdf(item)"
          >{{ item.type | printPdfTypeFilter }}</el-button
        >
      </div>
      <div slot="footer"></div>
    </el-dialog>
  </div>
</template>

<script>
import { DATA_TASK_STATUS, DATA_TASK_RESULT } from "@/constants/enumerate";
import { pdfBuildListPage } from "../api";
import pickerOptions from "@/constants/datePickerOptions";
import { getPrintTaskPdf, rebuildPrintTaskPdf } from "@/modules/print/api";

export default {
  name: "pdf-build-manage",
  data() {
    return {
      filter: {
        semesterId: "",
        examId: "",
        printPlanId: "",
        courseId: "",
        paperNumber: "",
        status: "",
        result: "",
        examPlace: "",
        examRoom: "",
        examStartTime: "",
        examEndTime: "",
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      dataList: [],
      curRow: {},
      loading: false,
      DATA_TASK_STATUS,
      DATA_TASK_RESULT,
      // date-picker
      createTime: [],
      pickerOptions,
      // log dialog
      modalIsShow: false,
      logList: [],
      // view-pdf
      padViewDialogVisible: false,
      pdfList: [],
    };
  },
  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];
      }
      const data = await pdfBuildListPage(datas);
      this.dataList = data.records;
      this.total = data.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    toViewLog(row) {
      this.logList = (row.summary || "").split("\n");
      this.modalIsShow = true;
    },
    async toResetCreatePdf(row) {
      this.curRow = row;
      this.pdfList = [];
      let result = true;
      const data = await getPrintTaskPdf(row.id).catch(() => {
        result = false;
      });
      if (!result) return;
      //   if (!data || !data.length) {
      //     this.$message.error("当前任务pdf还未生成好，请稍后再试！");
      //     return;
      //   }
      if (data.length === 1) {
        this.rebuildPdf(data[0]);
      } else {
        this.pdfList = data;
        this.padViewDialogVisible = true;
      }
    },
    async rebuildPdf(item) {
      const action = await this.$confirm(
        `确定要重新生成该印刷任务PDF吗？`,
        "提示",
        {
          type: "warning",
        }
      ).catch(() => {});
      if (action !== "confirm") return;

      const res = await rebuildPrintTaskPdf(this.curRow.id, item.type).catch(
        () => {}
      );
      if (!res) return;
      this.$message.success("操作成功！");
      this.padViewDialogVisible = false;
      this.getList();
    },
  },
};
</script>
