<template>
  <div class="task-paper-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')">
          <secp-select v-model="filter" defaultSelectExam></secp-select>
          <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 label-width="0px">
          <el-button
            v-if="checkPrivilege('button', 'select')"
            type="primary"
            @click="toPage(1)"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="box-justify">
        <div></div>
        <div>
          <el-button
            v-if="checkPrivilege('button', 'BatchDownload')"
            icon="el-icon-download"
            type="primary"
            :loading="loading"
            @click="toBatchExport"
          >
            批量下载试卷题卡
          </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">
      <el-table ref="TableList" :data="papers">
        <el-table-column
          type="index"
          label="序号"
          width="70"
          :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="paperNumber"
          label="试卷编号"
          width="160"
        ></el-table-column>
        <el-table-column prop="courseName" label="课程（代码）" min-width="260">
          <template slot-scope="scope">
            {{ scope.row.courseName }}（{{ scope.row.courseCode }}）
          </template>
        </el-table-column>
        <el-table-column
          prop="openCollege"
          label="开课学院"
          min-width="160"
        ></el-table-column>
        <el-table-column prop="paperType" label="备用卷" width="80">
          <span slot-scope="scope">卷{{ scope.row.paperType }}</span>
        </el-table-column>
        <el-table-column prop="userName" label="命题老师" min-width="120">
          <span slot-scope="scope"
            >{{ scope.row.userName }}（{{ scope.row.loginName }}）</span
          >
        </el-table-column>
        <el-table-column prop="createTime" label="入库时间" width="170">
          <span slot-scope="scope">{{
            scope.row.createTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="exposedPaperType" label="已曝光" width="80">
          <template slot-scope="scope">
            <span v-if="scope.row.exposedPaperType"
              >卷{{ scope.row.exposedPaperType }}</span
            >
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="unexposedPaperType" label="未曝光" width="80">
          <template slot-scope="scope">
            <span v-if="scope.row.unexposedPaperType"
              >卷{{ scope.row.unexposedPaperType }}</span
            >
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="examTaskDetailEnable"
          label="启用/禁用"
          width="90"
        >
          <template slot-scope="scope">
            {{ scope.row.examTaskDetailEnable | enableFilter }}
          </template>
        </el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          width="140px"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              v-if="checkPrivilege('link', 'preview')"
              class="btn-primary"
              type="text"
              @click="toPreview(scope.row)"
              >预览</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'enable')"
              :class="
                scope.row.examTaskDetailEnable ? 'btn-danger' : 'btn-primary'
              "
              type="text"
              @click="toEnable(scope.row)"
              >{{ scope.row.examTaskDetailEnable ? "禁用" : "启用" }}</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'download')"
              class="btn-primary"
              type="text"
              :disabled="loading"
              @click="toDownload(scope.row)"
              >下载</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'publish')"
              class="btn-primary"
              type="text"
              @click="toPublishPrintTask(scope.row)"
              >发布印刷任务</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'cancel')"
              class="btn-danger"
              type="text"
              @click="toCancel(scope.row)"
              >作废</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'restart')"
              class="btn-danger"
              type="text"
              @click="toRestart(scope.row)"
              >打回</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          v-if="papers.length"
          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>

    <!-- PreviewTaskPaper -->
    <preview-task-paper
      v-if="checkPrivilege('link', 'preview')"
      ref="PreviewTaskPaper"
      :row-data="curPaper"
    ></preview-task-paper>
    <!-- PublishPrintTask -->
    <publish-print-task
      v-if="checkPrivilege('link', 'publish')"
      :instance="curPaper"
      ref="PublishPrintTask"
    ></publish-print-task>
    <!-- data-task-dialog -->
    <data-task-dialog
      v-if="checkPrivilege('button', 'BatchDownload')"
      ref="DataTaskDialog"
      task-type="PAPER_AND_CARD_PDF_DOWNLOAD"
    ></data-task-dialog>
  </div>
</template>

<script>
import {
  taskPaperListPage,
  ableTaskPaper,
  downloadPaper,
  paperAndCardBatchExport,
  cancelTaskPaper,
  restartTaskPaper,
} from "../api";
import pickerOptions from "@/constants/datePickerOptions";
import { downloadByApi } from "@/plugins/download";
import { CARD_SOURCE_TYPE } from "@/constants/enumerate";
import PreviewTaskPaper from "../components/PreviewTaskPaper.vue";
import PublishPrintTask from "../components/PublishPrintTask";

export default {
  name: "task-paper-manage",
  components: { PreviewTaskPaper, PublishPrintTask },
  data() {
    return {
      filter: {
        semesterId: "",
        examId: "",
        openCollegeId: "",
        courseId: "",
        paperNumber: "",
        cardRuleId: "",
        makeMethod: "",
        startTime: "",
        endTime: "",
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      papers: [],
      curPaper: {},
      loading: false,
      CARD_SOURCE_TYPE,
      IS_QUESTION_TEACHER: this.$ls
        .get("user", { roleList: [] })
        .roleList.includes("QUESTION_TEACHER"),
      IS_EXAM_TEACHER: this.$ls
        .get("user", { roleList: [] })
        .roleList.includes("EXAM_TEACHER"),
      cancelRemark: "",
      // date-picker
      createTime: [],
      pickerOptions,
    };
  },
  watch: {
    "filter.examId": {
      handler(val, oldval) {
        if (val && val !== oldval) this.toPage(1);
      },
      immediate: true,
    },
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() {
      const cachePageInfo = this.$ls.get("cachePageInfo");
      if (cachePageInfo) {
        this.filter = this.$objAssign(this.filter, cachePageInfo.filter);
        if (this.filter.startTime && this.filter.endTime)
          this.createTime = [this.filter.startTime, this.filter.endTime];
        this.current = cachePageInfo.page;
        await this.getList();

        this.$nextTick(() => {
          const curRow = this.papers.find(
            (item) => item.id === cachePageInfo.curRowId
          );
          if (!curRow) return;
          this.toEdit(curRow);
        });
      } else {
        // this.toPage(1);
      }
      this.$ls.remove("cachePageInfo");
    },
    async getList() {
      if (!this.checkPrivilege("list", "list")) return;

      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size,
      };
      if (this.createTime) {
        datas.startTime = this.createTime[0];
        datas.endTime = this.createTime[1];
      }
      const data = await taskPaperListPage(datas);
      this.papers = data.records;
      this.total = data.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    async toEnable(row) {
      const msgs = [
        ["命题任务禁用后，会触发试卷关联解除，您确定要禁用命题任务吗？"],
        [
          "命题任务启用后，触发试卷关联校验，若能匹配则自动关联试卷，您确定要启用命题任务吗？",
        ],
      ];
      const msg = row.examTaskDetailEnable ? msgs[0] : msgs[1];
      const msgHtml = msg
        .map((item) => `<p class="text-left">${item}</p>`)
        .join("");
      this.$confirm(msgHtml, "提示", {
        dangerouslyUseHTMLString: true,
        type: "warning",
      })
        .then(async () => {
          const examTaskDetailEnable = !row.examTaskDetailEnable;
          await ableTaskPaper({
            id: row.id,
            examTaskDetailEnable,
          });
          row.examTaskDetailEnable = examTaskDetailEnable;
          this.$message.success("操作成功！");
        })
        .catch(() => {});
    },
    async toCancel(row) {
      const res = await this.$prompt("确定要作废选中的命题任务吗", "提示", {
        type: "warning",
        showInput: true,
        inputPlaceholder: "请输入作废理由",
        inputValue: this.cancelRemark,
        inputValidator: (val) => {
          if (!val) return "请输入作废理由";
          if (val.length > 100) return "作废理由不得超过100个字符！";
          return true;
        },
      }).catch(() => {});
      if (!res || res.action !== "confirm") {
        return;
      }
      this.cancelRemark = res.value;
      const result = await cancelTaskPaper({
        id: row.id,
        cancelRemark: this.cancelRemark,
      }).catch(() => {});
      this.cancelRemark = "";

      if (!result) return;
      this.$message.success("操作成功！");
      this.getList();
    },
    async toRestart(row) {
      const res = await this.$confirm("确定要打回当前命题任务吗", "提示", {
        type: "warning",
      }).catch(() => {});
      if (res !== "confirm") return;

      const result = await restartTaskPaper({
        examTaskId: row.id,
        paperType: row.paperType,
      }).catch(() => {});

      if (!result) return;
      this.$message.success("操作成功！");
      this.getList();
    },
    toPreview(row) {
      this.curPaper = row;
      this.$refs.PreviewTaskPaper.open();
    },
    toPublishPrintTask(row) {
      this.curPaper = row;
      this.$refs.PublishPrintTask.open();
    },
    async toDownload(row) {
      if (this.loading) return;

      this.loading = true;
      const res = await downloadByApi(() => {
        return downloadPaper(row.id);
      }, "").catch((e) => {
        this.$message.error(e || "下载失败，请重新尝试！");
      });
      this.loading = false;

      if (!res) return;
      this.$message.success("下载成功！");
    },
    async toBatchExport() {
      // 异步导出
      if (this.loading) return;

      this.loading = true;
      let datas = {
        ...this.filter,
      };
      if (this.createTime) {
        datas.startTime = this.createTime[0];
        datas.endTime = this.createTime[1];
      }
      const res = await paperAndCardBatchExport(datas).catch(() => {});
      this.loading = false;

      if (res) {
        this.$message.success("导出任务已提交！");
      } else {
        this.$message.error("导出任务提交失败，请重新尝试！");
      }
    },
    toDataTask() {
      this.$refs.DataTaskDialog.open();
    },
  },
  beforeRouteLeave(to, from, next) {
    if (to.name === "CardEdit") {
      this.$ls.set("cachePageInfo", {
        page: this.current,
        filter: this.filter,
        curRowId: this.curPaper.id,
      });
    } else {
      this.$ls.remove("cachePageInfo");
    }
    next();
  },
};
</script>
