<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>
        <template
          v-if="
            (AUDITED && checkPrivilege('condition', 'reviewCondition')) ||
              (!AUDITED && checkPrivilege('condition', 'notReviewCondition'))
          "
        >
          <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-input
              v-model="filter.createName"
              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>
          <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>
          <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>
        </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="part-box-action" v-if="!AUDITED">
        <el-button
          v-if="checkPrivilege('button', 'notReviewExport')"
          icon="el-icon-download"
          type="primary"
          :disabled="loading"
          @click="toExport"
        >
          导出审核样本
        </el-button>
        <!-- <el-button
          v-if="checkPrivilege('button', 'notReviewBatchNotPass')"
          icon="el-icon-coordinate"
          type="danger"
          @click="toBatchAudit(0)"
        >
          批量不通过
        </el-button> -->
        <el-button
          v-if="checkPrivilege('button', 'notReviewBatchPass')"
          icon="el-icon-coordinate"
          type="primary"
          @click="toBatchAudit(1)"
        >
          批量通过
        </el-button>
      </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"
          width="55"
          :selectable="checkAbleSelected"
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="70"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column prop="paperNumber" label="试卷编号"></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="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 prop="createName" label="创建人"></el-table-column>
        <el-table-column class-name="action-column" label="操作" width="80px">
          <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,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
      :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>
  </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,
  reviewSampleDataExport
} from "../api";
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,
        startCreateTime: null,
        endCreateTime: null,
        createName: ""
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      editType: "APPLY",
      AUDITING_RESULT,
      AUDITING_STATUS,
      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
    };
  },
  computed: {
    AUDITED() {
      return this.auditStatus === "AUDITED";
    }
  },
  mounted() {
    this.toPage(1);
  },
  methods: {
    ...mapActions("exam", ["updateWaitTaskCount"]),
    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.createId === this.curUserId;
    },
    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();
      this.updateWaitTaskCount();
    }
  }
};
</script>
