<template>
  <div class="task-review-manage">
    <div class="mb-4 tab-btns">
      <el-button
        v-for="(val, key) in AUDITING_TYPE"
        :key="key"
        size="medium"
        :type="auditStatus == key ? 'primary' : 'default'"
        @click="selectMenu(key)"
        >{{ val }}</el-button
      >
    </div>
    <div class="part-box part-box-filter">
      <el-form ref="FilterForm" label-position="left" label-width="85px" inline>
        <template
          v-if="
            (AUDITED && checkPrivilege('condition', 'reviewCondition')) ||
            (!AUDITED && checkPrivilege('condition', 'notReviewCondition'))
          "
        >
          <secp-select v-model="filter" defaultSelectExam></secp-select>
          <el-form-item label="命题老师：">
            <question-teacher-select
              ref="QuestionTeacherSelect"
              v-model="filter.userId"
              :course-id="filter.courseId"
              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="申请时间：">
            <el-date-picker
              v-model="applyTime"
              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="
              (AUDITED && checkPrivilege('button', 'reviewSelect')) ||
              (!AUDITED && checkPrivilege('button', 'notReviewSelect'))
            "
            type="primary"
            @click="toPage(1)"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="box-justify" v-if="!AUDITED">
        <div>
          <el-button
            v-if="checkPrivilege('button', 'notReviewExport')"
            icon="el-icon-download"
            type="success"
            :disabled="loading"
            @click="toExport"
          >
            导出审核样本
          </el-button>
          <el-button
            v-if="checkPrivilege('button', 'notReviewExport')"
            type="primary"
            icon="el-icon-s-order"
            @click="toDataTask"
            >导出结果查询</el-button
          >
        </div>
        <div>
          <!-- <el-button
          v-if="checkPrivilege('button', 'notReviewBatchNotPass')"
          icon="el-icon-circle-close"
          type="danger"
          @click="toBatchAudit(0)"
        >
          批量不通过
        </el-button> -->
          <el-button
            v-if="checkPrivilege('button', 'notReviewBatchPass')"
            icon="el-icon-circle-check"
            type="primary"
            @click="toBatchAudit(1)"
          >
            批量通过
          </el-button>
        </div>
      </div>
    </div>

    <div class="part-box part-box-pad">
      <el-table
        ref="TableList"
        :data="examTasks"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          v-if="!AUDITED"
          type="selection"
          fixed="left"
          width="55"
          align="center"
          :selectable="checkAbleSelected"
        ></el-table-column>
        <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="createTime" label="申请时间" width="170">
          <template slot-scope="scope">
            {{ scope.row.createTime | timestampFilter }}
          </template>
        </el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          width="80px"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              v-if="AUDITED && checkPrivilege('link', 'reviewPreview')"
              class="btn-primary"
              type="text"
              @click="toPreview(scope.row)"
              >查看详情</el-button
            >
            <el-button
              v-if="
                !AUDITED &&
                checkPrivilege('link', 'notReviewEdit') &&
                scope.row.myself
              "
              class="btn-primary"
              type="text"
              @click="toEdit(scope.row)"
              >审核</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          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', 'notReviewEdit') ||
        checkPrivilege('link', 'reviewPreview')
      "
      ref="ModifyTaskApply"
      :type="editType"
      :row-data="curExamTask"
      @modified="taskModified"
    ></modify-task-apply>
    <!-- audit-dialog-->
    <el-dialog
      :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="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>
    <!-- data-task-dialog -->
    <data-task-dialog
      v-if="checkPrivilege('button', 'notReviewExport')"
      ref="DataTaskDialog"
      task-type="SAMPLE_EXPORT"
    ></data-task-dialog>
  </div>
</template>

<script>
import ModifyTaskApply from "../components/taskApply/ModifyTaskApply.vue";
import pickerOptions from "@/constants/datePickerOptions";
import {
  taskReviewAuditedListPage,
  taskReviewUnauditedListPage,
  batchUpdateTaskReview,
  reviewSampleDataExport,
} from "../api";

export default {
  name: "task-review-manage",
  components: {
    ModifyTaskApply,
  },
  data() {
    return {
      auditStatus: "NOT_AUDITED",
      filter: {
        semesterId: "",
        examId: "",
        openCollegeId: "",
        userId: "",
        cardRuleId: "",
        courseId: "",
        paperNumber: "",
        startTime: null,
        endTime: null,
        startCreateTime: null,
        endCreateTime: null,
        createName: "",
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      editType: "AUDIT",
      AUDITING_TYPE: {
        NOT_AUDITED: "未审核",
        AUDITED: "已审核",
      },
      caches: {},
      examTasks: [],
      curExamTask: {},
      multipleSelection: [],
      loading: false,
      curUserId: this.$ls.get("user", { id: "" }).id,
      // audit-dialog
      auditDialogShow: false,
      auditModal: { reason: "" },
      auditRules: {
        reason: [
          { required: true, message: "请输入审核意见", trigger: "change" },
        ],
      },
      // date-picker
      createTime: [],
      applyTime: [],
      pickerOptions,
    };
  },
  watch: {
    "filter.examId": {
      handler(val, oldval) {
        if (val && val !== oldval) this.toPage(1);
      },
      immediate: true,
    },
  },
  computed: {
    AUDITED() {
      return this.auditStatus === "AUDITED";
    },
  },
  methods: {
    async getList() {
      const valid =
        (this.AUDITED && this.checkPrivilege("list", "reviewList")) ||
        (!this.AUDITED && this.checkPrivilege("list", "notReviewList"));
      if (!valid) return;

      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size,
      };
      if (this.createTime) {
        datas.startTime = this.createTime[0];
        datas.endTime = this.createTime[1];
      }
      if (this.applyTime) {
        datas.startCreateTime = this.applyTime[0];
        datas.endCreateTime = this.applyTime[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);
    },
    checkAbleSelected(row) {
      return row.myself;
    },
    selectMenu(val) {
      if (this.auditStatus === val) return;

      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;
      }
      const actionName = isPass ? "通过" : "不通过";
      this.$confirm(`确定${actionName}这些申请吗？`, "提示", {
        type: "warning",
      })
        .then(() => {
          this.auditModal.reason = "";
          if (isPass) {
            this.auditApply("PASS", this.multipleSelection);
          } else {
            this.auditDialogShow = true;
          }
        })
        .catch(() => {});
    },
    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.multipleSelection.length) {
        this.$message.error("请选择要导出的记录！");
        return;
      }

      if (this.loading) return;

      this.loading = true;
      const res = await reviewSampleDataExport({
        ids: this.multipleSelection,
      }).catch(() => {});
      this.loading = false;

      if (res) {
        this.$message.success("导出任务已提交！");
      } else {
        this.$message.error("导出任务提交失败，请重新尝试！");
      }
    },
    toEdit(row) {
      this.curExamTask = { ...row, source: "REVIEW" };
      this.editType = "AUDIT";
      this.$refs.ModifyTaskApply.open();
    },
    toPreview(row) {
      this.curExamTask = { ...row, source: "REVIEW" };
      this.editType = "PREVIEW";
      this.$refs.ModifyTaskApply.open();
    },
    taskModified() {
      this.getList();
    },
    toDataTask() {
      this.$refs.DataTaskDialog.open();
    },
  },
};
</script>
