<template>
  <div class="task-apply-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')">
          <secp-select v-model="filter" defaultSelectExam></secp-select>
          <el-form-item label="审核状态：">
            <el-select
              v-model="filter.auditStatus"
              style="width: 142px"
              placeholder="审核状态"
              clearable
            >
              <el-option
                v-for="(val, key) in AUDITING_STATUS"
                :key="key"
                :value="key"
                :label="val"
              ></el-option>
            </el-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="命题时间：">
            <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', 'ExamTaskApplyManage')"
          icon="el-icon-circle-plus-outline"
          type="primary"
          @click="toAddExamAndPrintTask"
        >
          新建任务
        </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="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="userName"
          label="命题老师"
          min-width="120"
        ></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="auditStatus" label="审核状态" width="100">
          <template slot-scope="scope">
            {{ scope.row.auditStatus | auditStatusFilter }}
          </template>
        </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', 'preview')"
              class="btn-primary"
              type="text"
              @click="toPreview(scope.row)"
              >预览</el-button
            >
            <el-button
              v-if="
                ((!scope.row.review &&
                  scope.row.auditStatus === null &&
                  scope.row.status === 'STAGE') ||
                  (scope.row.review &&
                    (scope.row.auditStatus === 'START' ||
                      scope.row.auditStatus === 'REJECT' ||
                      scope.row.auditStatus === 'CANCEL'))) &&
                checkPrivilege('link', 'edit')
              "
              class="btn-primary"
              type="text"
              @click="toEdit(scope.row)"
              >立即申请</el-button
            >
            <el-button
              v-if="
                scope.row.auditStatus === 'AUDITING' &&
                scope.row.setup === 2 &&
                checkPrivilege('link', 'end')
              "
              class="btn-danger"
              type="text"
              @click="toCancel(scope.row)"
              >撤销申请</el-button
            >
            <el-button
              v-if="
                scope.row.approveFormStatus &&
                checkPrivilege('link', 'download')
              "
              class="btn-primary"
              type="text"
              @click="toDownloadForm(scope.row)"
              >下载审批表</el-button
            >
            <el-button
              v-if="checkPrivilege('link', 'delete')"
              class="btn-danger"
              type="text"
              @click="toDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          v-if="examTasks.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>

    <!-- ModifyTaskApply -->
    <modify-task-apply
      v-if="checkPrivilege('link', 'edit') || checkPrivilege('link', 'preview')"
      ref="ModifyTaskApply"
      :type="editType"
      :row-data="curExamTask"
      @modified="taskModified"
    ></modify-task-apply>
    <!-- CreateExamAndPrintTask -->
    <create-exam-and-print-task
      v-if="checkPrivilege('button', 'ExamTaskApplyManage')"
      ref="CreateExamAndPrintTask"
      @modified="taskModified"
    ></create-exam-and-print-task>
    <!-- PaperApproveTable -->
    <paper-approve-table
      :instance="curExamTask"
      ref="PaperApproveTable"
    ></paper-approve-table>
  </div>
</template>

<script>
import ModifyTaskApply from "../components/taskApply/ModifyTaskApply.vue";
import CreateExamAndPrintTask from "../components/createExamAndPrintTask/CreateExamAndPrintTask.vue";
import PaperApproveTable from "../components/PaperApproveTable.vue";
import { AUDITING_STATUS } from "@/constants/enumerate";
import pickerOptions from "@/constants/datePickerOptions";
import {
  taskApplyListPage,
  cancelOrRestartTaskApply,
  deleteTaskApply,
} from "../api";

export default {
  name: "task-apply-manage",
  components: {
    ModifyTaskApply,
    CreateExamAndPrintTask,
    PaperApproveTable,
  },
  data() {
    return {
      filter: {
        semesterId: "",
        examId: "",
        openCollegeId: "",
        auditStatus: "",
        reviewStatus: "",
        cardRuleId: "",
        courseId: "",
        userName: "",
        paperNumber: "",
        startTime: "",
        endTime: "",
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      editType: "APPLY",
      AUDITING_STATUS,
      examTasks: [],
      curExamTask: {},
      curUserId: this.$ls.get("user", { id: "" }).id,
      userRoles: this.$ls.get("user", { roleList: [] }).roleList,
      // date-picker
      createTime: [],
      pickerOptions,
    };
  },
  watch: {
    "filter.examId": {
      handler(val, oldval) {
        if (val && val !== oldval) this.toPage(1);
      },
      immediate: true,
    },
  },
  created() {
    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.examTasks.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 taskApplyListPage(datas);
      this.examTasks = data.records;
      this.total = data.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    toCancel(row) {
      this.$confirm("确定要撤销当前申请吗？", "提示", {
        type: "warning",
      })
        .then(async () => {
          const data = await cancelOrRestartTaskApply({
            id: row.id,
          }).catch(() => {});
          if (!data) return;
          this.$message.success("操作成功！");
          this.getList();
        })
        .catch(() => {});
    },
    toEdit(row) {
      this.curExamTask = row;
      this.editType = "APPLY";
      this.$refs.ModifyTaskApply.open();
    },
    toPreview(row) {
      this.curExamTask = row;
      this.editType = "PREVIEW";
      this.$refs.ModifyTaskApply.open();
    },
    taskModified() {
      this.getList();
    },
    toAddExamAndPrintTask() {
      this.$refs.CreateExamAndPrintTask.open();
    },
    toDownloadForm(row) {
      this.curExamTask = { ...row, examTaskId: row.id };
      this.$refs.PaperApproveTable.open();
    },
    async toDelete(row) {
      const result = await this.$confirm(`确定要删除入库申请吗?`, "提示", {
        type: "warning",
      }).catch(() => {});
      if (result !== "confirm") return;

      await deleteTaskApply(row.id);
      this.$message.success("操作成功！");
      this.deletePageLastItem();
    },
  },
  beforeRouteLeave(to, from, next) {
    if (to.name === "CardEdit") {
      this.$ls.set("cachePageInfo", {
        page: this.current,
        filter: this.filter,
        curRowId: this.curExamTask.id,
      });
    } else {
      this.$ls.remove("cachePageInfo");
    }
    next();
  },
};
</script>
