<template>
  <div class="task-paper-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="filter.semesterId"></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="课程（代码）：" label-width="110px">
            <course-select
              ref="CourseSelect"
              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="入库时间：">
            <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="part-box-action">
        <el-button
          v-if="checkPrivilege('button', 'BatchDownload')"
          icon="el-icon-download"
          type="primary"
          :loading="loading"
          @click="toBatchExport"
        >
          批量下载试卷题卡
        </el-button>
      </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="160"
        ></el-table-column>
        <el-table-column
          prop="examName"
          label="考试"
          min-width="160"
        ></el-table-column>
        <el-table-column
          prop="paperNumber"
          label="试卷编号"
          min-width="160"
        ></el-table-column>
        <el-table-column prop="courseName" label="课程（代码）" min-width="200">
          <template slot-scope="scope">
            {{ scope.row.courseName }}（{{ scope.row.courseCode }}）
          </template>
        </el-table-column>
        <el-table-column
          prop="paperType"
          label="卷型"
          width="80"
        ></el-table-column>
        <el-table-column
          prop="userName"
          label="命题老师"
          min-width="100"
        ></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">
          <span slot-scope="scope">{{
            scope.row.exposedPaperType | defaultFieldFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="unexposedPaperType" label="未曝光" width="80">
          <span slot-scope="scope">{{
            scope.row.unexposedPaperType | defaultFieldFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="enable" label="启用/禁用" width="80">
          <template slot-scope="scope">
            {{ scope.row.enable | enableFilter }}
          </template>
        </el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          width="180px"
          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', 'edit')"
              class="btn-primary"
              type="text"
              @click="toEdit(scope.row)"
              >修改</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'enable')"
              :class="scope.row.enable ? 'btn-danger' : 'btn-primary'"
              type="text"
              @click="toEnable(scope.row)"
              >{{ scope.row.enable ? "禁用" : "启用" }}</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
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          v-if="papers.length"
          background
          layout="total,prev, pager, next"
          :current-page="current"
          :total="total"
          :page-size="size"
          @current-change="toPage"
        >
        </el-pagination>
      </div>
    </div>

    <!-- ModifyTaskPaper -->
    <modify-task-paper
      v-if="checkPrivilege('link', 'edit') || checkPrivilege('link', 'preview')"
      :instance="curPaper"
      :edit-type="editType"
      ref="ModifyTaskPaper"
      @modified="getList"
    ></modify-task-paper>
    <!-- PublishPrintTask -->
    <publish-print-task
      v-if="checkPrivilege('link', 'publish')"
      :instance="curPaper"
      ref="PublishPrintTask"
    ></publish-print-task>
  </div>
</template>

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

export default {
  name: "task-paper-manage",
  components: { ModifyTaskPaper, PublishPrintTask },
  data() {
    return {
      filter: {
        semesterId: "",
        examId: "",
        courseCode: "",
        paperNumber: "",
        cardRuleId: "",
        makeMethod: "",
        startTime: "",
        endTime: ""
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      papers: [],
      curPaper: {},
      loading: false,
      editType: "EDIT",
      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"),
      // date-picker
      createTime: [],
      pickerOptions
    };
  },
  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.enable ? 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 enable = !row.enable;
          await ableTaskPaper({
            id: row.id,
            enable
          });
          row.enable = enable;
          this.$message.success("操作成功！");
        })
        .catch(() => {});
    },
    toEdit(row) {
      this.curPaper = row;
      this.editType = "EDIT";
      this.$refs.ModifyTaskPaper.open();
    },
    toPreview(row) {
      this.curPaper = row;
      this.editType = "PREVIEW";
      this.$refs.ModifyTaskPaper.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);
      }, `${row.paperNumber}-${Date.now()}.zip`).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("导出任务提交失败，请重新尝试！");
      }
    }
  },
  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>
