<template>
  <div class="task-review-manage">
    <div class="mb-4">
      <el-button
        v-for="(val, key) in AUDITING_STATUS"
        :key="key"
        :type="auditStatus == key ? 'primary' : 'default'"
        @click="selectMenu(key)"
        >{{ val }}</el-button
      >
    </div>
    <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="题卡规则：">
          <card-rule-select
            ref="CardRuleSelect"
            v-model.trim="filter.cardRuleId"
            placeholder="请选择"
            clearable
          ></card-rule-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="命题老师：">
          <question-teacher-select
            ref="QuestionTeacherSelect"
            v-model="filter.userId"
            :course-code="filter.courseCode"
            placeholder="请选择"
          ></question-teacher-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="审核结果：" v-if="AUDITED">
          <el-select
            v-model="filter.reviewStatus"
            style="width: 142px;"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="(val, key) in AUDITING_RESULT"
              :key="key"
              :value="key"
              :label="val"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label-width="0px">
          <el-button type="primary" icon="icon icon-search" @click="toPage(1)"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="part-box-action" v-if="!AUDITED">
        <el-button
          icon="el-icon-download"
          type="primary"
          :disabled="loading"
          @click="toExport"
        >
          导出审核样本
        </el-button>
        <el-button
          icon="el-icon-coordinate"
          type="danger"
          @click="toBatchAudit(0)"
        >
          批量不通过
        </el-button>
        <el-button
          icon="el-icon-coordinate"
          type="primary"
          @click="toBatchAudit(1)"
        >
          批量通过
        </el-button>
      </div>
    </div>

    <div class="part-box">
      <el-table
        ref="TableList"
        :data="examTasks"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          v-if="!AUDITED"
          type="selection"
          width="55"
        ></el-table-column>
        <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="cardRuleName" label="题卡规则"></el-table-column>
        <el-table-column
          prop="userName"
          label="命题老师"
          width="100"
        ></el-table-column>
        <el-table-column prop="startTime" label="命题开始时间">
          <span slot-scope="scope">{{
            scope.row.startTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="endTime" label="命题结束时间">
          <span slot-scope="scope">{{
            scope.row.endTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="createTime" label="申请时间">
          <template slot-scope="scope">
            {{ scope.row.createTime | timestampFilter }}
          </template>
        </el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          align="center"
          width="80px"
        >
          <template slot-scope="scope">
            <el-button
              v-if="auditStatus === 'NOT_AUDITED'"
              class="btn-table-icon"
              type="text"
              icon="icon icon-edit"
              @click="toEdit(scope.row)"
              title="审核"
            ></el-button>
            <el-button
              v-else
              class="btn-table-icon"
              type="text"
              icon="icon icon-circle-right"
              @click="toPreview(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>

    <!-- ModifyTaskApply -->
    <modify-task-apply
      ref="ModifyTaskApply"
      :edit-type="editType"
      :instance="curExamTask"
      @modified="taskModified"
    ></modify-task-apply>
    <!-- audit-dialog-->
    <el-dialog
      class="modify-task-apply"
      :visible.sync="auditDialogShow"
      title="审核意见"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-form ref="AuditForm" :rules="auditRules" :model="auditModal">
        <el-form-item prop="reason">
          <el-input
            class="mb-2"
            v-model.trim="auditModal.reason"
            type="textarea"
            resize="none"
            :rows="5"
            :maxlength="1000"
            clearable
            show-word-limit
            placeholder="建议不超过1000个字"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="auditNotPass">确认</el-button>
        <el-button type="danger" @click="auditDialogShow = false" plain
          >取消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ModifyTaskApply from "../components/ModifyTaskApply";
import { AUDITING_RESULT, AUDITING_STATUS } from "@/constants/enumerate";
import pickerOptions from "@/constants/datePickerOptions";
import {
  taskReviewAuditedListPage,
  taskReviewUnauditedListPage,
  batchUpdateTaskReview
} from "../api";
import { download, randomCode } from "@/plugins/utils";
import { mapActions } from "vuex";

export default {
  name: "task-review-manage",
  components: {
    ModifyTaskApply
  },
  data() {
    return {
      auditStatus: "NOT_AUDITED",
      filter: {
        userId: "",
        cardRuleId: "",
        courseCode: "",
        paperNumber: "",
        startTime: null,
        endTime: null
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      editType: "APPLY",
      AUDITING_RESULT,
      AUDITING_STATUS,
      caches: {},
      examTasks: [],
      curExamTask: {},
      multipleSelection: [],
      loading: false,
      // audit-dialog
      auditDialogShow: false,
      auditModal: { reason: "" },
      auditRules: {
        reason: [
          { required: true, message: "请输入审核意见", trigger: "change" }
        ]
      },
      // date-picker
      createTime: [],
      pickerOptions
    };
  },
  computed: {
    AUDITED() {
      return this.auditStatus === "AUDITED";
    }
  },
  created() {
    this.toPage(1);
  },
  methods: {
    ...mapActions("exam", ["updateWaitTaskCount"]),
    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 func = this.AUDITED
        ? taskReviewAuditedListPage
        : taskReviewUnauditedListPage;
      const data = await func(datas);
      this.examTasks = data.records;
      this.total = data.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
      this.multipleSelection = [];
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.id);
      console.log(this.multipleSelection);
    },
    selectMenu(val) {
      this.caches[this.auditStatus] = {
        current: this.current,
        examTasks: this.examTasks,
        total: this.total
      };
      this.auditStatus = val;
      if (this.caches[val] && this.caches[val].examTasks) {
        this.current = this.caches[val].current;
        this.total = this.caches[val].total;
        this.examTasks = this.caches[val].examTasks;
      } else {
        this.toPage(1);
      }
    },
    toBatchAudit(isPass) {
      if (!this.multipleSelection.length) {
        this.$message.error("请选择要审核的记录！");
        return;
      }
      if (isPass) {
        this.auditApply("PASS", this.multipleSelection);
      } else {
        this.auditModal.reason = "";
        this.auditDialogShow = true;
      }
    },
    async auditNotPass() {
      const valid = await this.$refs.AuditForm.validate().catch(() => {});
      if (!valid) return;

      await this.auditApply("NOT_PASS", this.multipleSelection);
      this.auditDialogShow = false;
    },
    async auditApply(type, ids) {
      const data = await batchUpdateTaskReview({
        reviewStatus: type,
        examTaskIds: ids,
        reason: this.auditModal.reason
      }).catch(() => {});
      if (!data) return;
      this.$message.success("审核成功！");
      this.taskModified();
    },
    async toExport() {
      if (this.loading) return;

      if (!this.multipleSelection.length) {
        this.$message.error("请选择要导出的记录！");
        return;
      }

      this.loading = true;
      const res = await download({
        type: "post",
        url: this.GLOBAL.domain + "/api/admin/exam/task_review/export",
        data: {
          examTaskIds: this.multipleSelection
        },
        fileName: `${Date.now()}${randomCode()}.zip`,
        header: this.getHeadIds()
      }).catch(error => {
        this.$message.error(error + "文件下载失败，请重新尝试！");
      });
      this.loading = false;
      if (!res) return;
      this.$message.success("文件下载成功！");
    },
    toEdit(row) {
      this.curExamTask = row;
      this.editType = "AUDIT";
      this.$refs.ModifyTaskApply.open();
    },
    toPreview(row) {
      this.curExamTask = row;
      this.editType = "PREVIEW";
      this.$refs.ModifyTaskApply.open();
    },
    taskModified() {
      this.getList();
      this.updateWaitTaskCount();
    }
  }
};
</script>
