<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>
        <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>
        <el-form-item label-width="0px">
          <el-button type="primary" icon="el-icon-search" @click="toPage(1)"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <div class="part-box">
      <el-table ref="TableList" :data="papers" border stripe>
        <el-table-column
          type="index"
          label="序号"
          width="70"
          align="center"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column
          prop="paperNumber"
          label="试卷编号"
          width="120"
        ></el-table-column>
        <el-table-column prop="courseName" label="课程（代码）">
          <template slot-scope="scope">
            {{ scope.row.courseName }}（{{ scope.row.courseCode }}）
          </template>
        </el-table-column>
        <el-table-column
          prop="specialty"
          label="适用专业（方向）"
        ></el-table-column>
        <el-table-column
          prop="paperType"
          label="卷型"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="userName"
          label="命题老师"
          width="100"
        ></el-table-column>
        <el-table-column prop="createTime" label="入库时间">
          <span slot-scope="scope">{{
            scope.row.createTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column
          prop="exposedPaperType"
          label="已曝光"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="unexposedPaperType"
          label="未曝光"
          width="100"
        ></el-table-column>
        <el-table-column prop="enable" label="启用/禁用" width="100">
          <template slot-scope="scope">
            {{ scope.row.enable | enableFilter }}
          </template>
        </el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          align="center"
          width="120px"
        >
          <template slot-scope="scope">
            <el-button
              class="btn-table-icon"
              type="text"
              :icon="
                scope.row.enable
                  ? 'icon icon-circle-stop'
                  : 'icon icon-circle-caret-right'
              "
              @click="toEnable(scope.row)"
              :title="scope.row.enable ? '禁用' : '启用'"
            ></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"
              :disabled="loading"
              @click="toDownload(scope.row)"
              title="下载"
            ></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>

    <!-- PreviewTaskPaper -->
    <preview-task-paper
      :instance="curPaper"
      ref="PreviewTaskPaper"
    ></preview-task-paper>
  </div>
</template>

<script>
import { taskPaperListPage, ableTaskPaper, downloadPaper } from "../api";
import pickerOptions from "@/constants/datePickerOptions";
import { downloadBlob } from "@/plugins/utils";
import PreviewTaskPaper from "../components/PreviewTaskPaper";

export default {
  name: "task-paper-manage",
  components: { PreviewTaskPaper },
  data() {
    return {
      filter: {
        courseCode: "",
        paperNumber: "",
        startTime: "",
        endTime: ""
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      papers: [],
      curPaper: {},
      loading: false,
      // date-picker
      createTime: [],
      pickerOptions
    };
  },
  created() {
    this.getList();
  },
  methods: {
    async getList() {
      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 = [
        [
          "命题任务取消后，有如下后果：",
          "1.命题老师将无法看到该命题任务；",
          "2.该任务无法审核和与考试计划关联；",
          "3.该任务已绑定的题卡将取消绑定。",
          "您确定要取消命题任务吗？"
        ],
        [
          "命题任务启用后：",
          "1.命题老师将重新看到该命题任务；",
          "2.该任务将允许继续审核及与考试计划关联；",
          "3.该任务需重新绑定题卡。",
          "您确定要启用命题任务吗？"
        ]
      ];
      const msg = row.enable ? msgs[0] : msgs[1];
      const msgHtml = msg
        .map(item => `<p class="text-left">${item}</p>`)
        .join("");
      this.$confirm(msgHtml, "提示", {
        cancelButtonClass: "el-button--danger is-plain",
        confirmButtonClass: "el-button--primary",
        dangerouslyUseHTMLString: true,
        type: "warning"
      })
        .then(async () => {
          const enable = !row.enable;
          await ableTaskPaper({
            id: row.id,
            enable
          });
          row.enable = enable;
          this.$message.success("操作成功！");
        })
        .catch(() => {});
    },
    toPreview(row) {
      this.curPaper = row;
      this.$refs.PreviewTaskPaper.open();
    },
    async toDownload(row) {
      if (this.loading) return;

      this.loading = true;
      const res = await downloadBlob(() => {
        return downloadPaper(row.id);
      }, `${row.paperNumber}-${Date.now()}.zip`).catch(() => {});

      this.loading = false;

      if (res) {
        this.$message.success("文件下载成功！");
      } else {
        this.$message.error("文件下载失败，请重新尝试！");
      }
    }
  }
};
</script>
