<template>
  <div class="exam-task-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="命题状态：">
            <el-select
              v-model="filter.status"
              style="width: 142px;"
              placeholder="命题状态"
              clearable
            >
              <el-option
                v-for="(val, key) in EXAM_TASK_STATUS"
                :key="key"
                :value="key"
                :label="val"
              ></el-option>
            </el-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="命题老师：">
            <el-input
              v-model="filter.userName"
              placeholder="命题老师"
              clearable
            ></el-input>
          </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="启用/禁用：" label-width="90px">
            <el-select
              v-model="filter.enable"
              style="width: 120px;"
              placeholder="启用/禁用"
              clearable
            >
              <el-option
                v-for="(val, key) in ABLE_TYPE"
                :key="key"
                :value="key * 1"
                :label="val"
              ></el-option>
            </el-select>
          </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', 'BatchAdd')"
          icon="el-icon-circle-plus-outline"
          type="info"
          @click="toBatchAdd"
        >
          批量新建命题任务
        </el-button>
        <el-button
          v-if="checkPrivilege('button', 'add')"
          icon="el-icon-circle-plus-outline"
          type="primary"
          @click="toAdd"
        >
          新建命题任务
        </el-button>
      </div>
    </div>

    <div class="part-box part-box-pad">
      <el-table ref="TableList" :data="examTasks">
        <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="sequence" label="序号"></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="userName"
          label="命题老师"
          min-width="100"
        ></el-table-column>
        <el-table-column prop="startTime" label="命题开始时间" width="170">
          <span slot-scope="scope">{{
            scope.row.startTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="endTime" label="命题结束时间" width="170">
          <span slot-scope="scope">{{
            scope.row.endTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="status" label="命题状态" width="100">
          <template slot-scope="scope">
            {{ scope.row.status | examTaskStatusFilter }}
          </template>
        </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 prop="createTime" label="创建时间" width="170">
          <span slot-scope="scope">{{
            scope.row.createTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          width="120px"
          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="
                ((scope.row.status === 'STAGE' && !scope.row.enable) ||
                  scope.row.status === 'DRAFT') &&
                  scope.row.createId === curUserId &&
                  checkPrivilege('link', 'edit')
              "
              class="btn-primary"
              type="text"
              @click="toEdit(scope.row)"
              >{{ scope.row.status === "DRAFT" ? "指派" : "更改" }}</el-button
            >
            <el-button
              v-if="
                scope.row.status !== 'FINISH' &&
                  scope.row.createId === curUserId &&
                  checkPrivilege('link', 'cancel')
              "
              :class="scope.row.enable ? 'btn-danger' : 'btn-primary'"
              type="text"
              @click="toEnable(scope.row)"
              >{{ scope.row.enable ? "禁用" : "启用" }}</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>

    <!-- ModifyExamTask -->
    <modify-exam-task
      ref="ModifyExamTask"
      :instance="curExamTask"
      :edit-type="editType"
      @modified="taskModified"
    ></modify-exam-task>
    <!-- BatchAddExamTask -->
    <batch-add-exam-task
      ref="BatchAddExamTask"
      @modified="taskModified"
    ></batch-add-exam-task>
  </div>
</template>

<script>
import ModifyExamTask from "../components/ModifyExamTask";
import BatchAddExamTask from "../components/BatchAddExamTask";
import { ABLE_TYPE, EXAM_TASK_STATUS } from "@/constants/enumerate";
import pickerOptions from "@/constants/datePickerOptions";
import { examTaskListPage, ableExamTask } from "../api";
import { mapActions } from "vuex";

export default {
  name: "exam-task-manage",
  components: {
    ModifyExamTask,
    BatchAddExamTask
  },
  data() {
    return {
      filter: {
        semesterId: "",
        examId: "",
        status: "",
        cardRuleId: "",
        courseCode: "",
        paperNumber: "",
        userName: "",
        createName: "",
        startTime: null,
        endTime: null,
        enable: null
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      editType: "ADD",
      ABLE_TYPE,
      EXAM_TASK_STATUS,
      examTasks: [],
      curExamTask: {},
      curUserId: this.$ls.get("user", { id: "" }).id,
      // date-picker
      createTime: [],
      pickerOptions
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    ...mapActions("exam", ["updateWaitTaskCount"]),
    async getList() {
      if (!this.checkPrivilege("list", "list")) return;

      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size
      };
      if (datas.enable !== null && datas.enable !== "")
        datas.enable = !!datas.enable;
      if (this.createTime) {
        datas.startTime = this.createTime[0];
        datas.endTime = this.createTime[1];
      }
      const data = await examTaskListPage(datas);
      this.examTasks = 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, "提示", {
        dangerouslyUseHTMLString: true,
        type: "warning"
      })
        .then(async () => {
          const enable = !row.enable;
          await ableExamTask({
            id: row.id,
            enable
          });
          row.enable = enable;
          this.$message.success("操作成功！");
          // 启用之后，更新列表。
          // 因为禁用时会解绑题卡，影响命题任务状态。
          if (enable) this.getList();
        })
        .catch(() => {});
    },
    toBatchAdd() {
      this.$refs.BatchAddExamTask.open();
    },
    toAdd() {
      this.curExamTask = {};
      this.editType = "ADD";
      this.$refs.ModifyExamTask.open();
    },
    toEdit(row) {
      this.curExamTask = row;
      this.editType = "EDIT";
      this.$refs.ModifyExamTask.open();
    },
    toPreview(row) {
      this.curExamTask = row;
      this.editType = "PREVIEW";
      this.$refs.ModifyExamTask.open();
    },
    taskModified() {
      this.getList();
      this.updateWaitTaskCount();
    }
  }
};
</script>
