<template>
  <section class="content">
    <div class="part-box">
      <h2 class="part-box-title">题库待审</h2>

      <el-form class="part-filter-form" :inline="true" :model="formSearch">
        <el-form-item label="课程名称">
          <el-select
            v-model="formSearch.courseId"
            filterable
            :remote-method="getCourses"
            remote
            clearable
            placeholder="全部"
            @clear="getCourses('')"
          >
            <el-option
              v-for="item in courseInfoSelect"
              :key="item.courseId"
              :label="item.courseInfo"
              :value="item.courseId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="试卷名称">
          <el-input v-model="formSearch.name" placeholder="试卷名称"></el-input>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select
            v-model="formSearch.auditStatus"
            clearable
            placeholder="请选择"
          >
            <el-option label="初级待审" value="FIRST_PENDING_TRIAL">
            </el-option>
            <el-option label="中级待审" value="SECOND_PENDING_TRIAL">
            </el-option>
            <el-option label="高级待审" value="THIRD_PENDING_TRIAL">
            </el-option>
            <el-option label="已撤回" value="WITHDRAW"> </el-option>
            <el-option label="审核未通过" value="NOT_PASS"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="录入人">
          <el-input
            v-model="formSearch.creator"
            placeholder="录入人"
          ></el-input>
        </el-form-item>
        <el-form-item label="修改人">
          <el-input
            v-model="formSearch.lastModifyName"
            placeholder="修改人"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="searchFrom">查询</el-button>
          <el-button type="danger" plain @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="part-box-action">
        <div>
          <el-button
            :disabled="noBatchSelected"
            type="danger"
            plain
            icon="icon icon-delete"
            @click="deletePapers"
            >批量删除</el-button
          >
          <el-button
            :disabled="noBatchSelected"
            type="primary"
            plain
            icon="icon icon-save"
            @click="auditPapers('PASS')"
            >批量通过</el-button
          >
          <el-button
            :disabled="noBatchSelected"
            type="danger"
            plain
            icon="icon icon-delete"
            @click="auditPapers('NOT_PASS')"
            >批量不通过</el-button
          >
          <el-button
            :disabled="noBatchSelected"
            type="primary"
            plain
            icon="icon icon-cancel"
            @click="withdrawPapers()"
            >批量撤回</el-button
          >
          <el-button
            :disabled="noBatchSelected"
            type="primary"
            plain
            icon="icon icon-save"
            @click="submitPapers()"
            >批量提交</el-button
          >
        </div>
      </div>
    </div>
    <div class="part-box">
      <el-table
        v-loading="loading"
        element-loading-text="拼命加载中"
        :data="tableData"
        @selection-change="selectChange"
      >
        <el-table-column
          type="selection"
          width="50"
          align="center"
        ></el-table-column>
        <el-table-column label="课程名称" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.course.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="课程代码" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.course.code }}</span>
          </template>
        </el-table-column>
        <el-table-column label="试卷名称" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="试卷总分"
          width="103"
          sortable
          prop="totalScore"
        >
        </el-table-column>
        <el-table-column
          label="试卷难度"
          width="103"
          sortable
          prop="difficulty"
        >
        </el-table-column>
        <el-table-column
          label="大题数量"
          width="103"
          sortable
          prop="paperDetailCount"
        >
        </el-table-column>
        <el-table-column width="100" label="审核状态">
          <span slot-scope="scope">{{
            scope.row.auditStatus | paperAuditStatusFilter
          }}</span>
        </el-table-column>
        <el-table-column label="录入员" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.creator }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          width="153"
          sortable
          prop="creationTime"
        >
        </el-table-column>
        <el-table-column label="修改人" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.lastModifyName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="修改时间"
          width="153"
          sortable
          prop="updateTime"
        >
        </el-table-column>
        <el-table-column label="操作" min-width="170" fixed="right">
          <template slot-scope="scope">
            <div class="operate_left">
              <el-button
                size="mini"
                type="primary"
                plain
                @click="editImportPaper(scope.row)"
                >详情</el-button
              >
              <el-dropdown v-if="isShowAuditBtn(scope.row)">
                <el-button type="primary" size="mini" plain>
                  审核<i class="el-icon-more el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown" class="action-dropdown">
                  <el-dropdown-item>
                    <el-button
                      size="mini"
                      type="success"
                      plain
                      @click="auditPaper('PASS', scope.row.id)"
                    >
                      通过
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      size="mini"
                      type="danger"
                      plain
                      @click="auditPaper('NOT_PASS', scope.row.id)"
                    >
                      不通过
                    </el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-dropdown>
                <el-button type="primary" size="mini" plain>
                  更多 <i class="el-icon-more el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown" class="action-dropdown">
                  <el-dropdown-item>
                    <el-button
                      v-show="isShowDeleteBtn(scope.row)"
                      size="mini"
                      type="danger"
                      plain
                      @click="deletePaper(scope.row)"
                      >删除</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      v-show="isShowWithdrawBtn(scope.row)"
                      size="mini"
                      type="primary"
                      plain
                      @click="withdrawPaper(scope.row)"
                      >撤回</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      v-show="isShowSubmitBtn(scope.row)"
                      size="mini"
                      type="primary"
                      plain
                      @click="submitPaper(scope.row)"
                      >提交</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      size="mini"
                      type="primary"
                      plain
                      @click="exportPaper(scope.row)"
                      >下载</el-button
                    >
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100, 200, 300]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      title="审核试卷"
      width="500px"
      :visible.sync="auditPaperDialog"
      :modal="false"
      append-to-body
      custom-class="side-dialog"
    >
      <AuditPaper
        v-if="auditPaperDialog"
        :paper-ids="selectedPaperIds"
        :audit-result="auditResult"
        @afterAudit="afterAudit"
      ></AuditPaper>
    </el-dialog>
  </section>
</template>

<script>
import { QUESTION_API } from "@/constants/constants";
import { LEVEL_TYPE } from "../constants/constants";
import { mapState } from "vuex";
import AuditPaper from "./AuditPaper.vue";

export default {
  components: { AuditPaper },
  data() {
    return {
      auditPaperDialog: false,
      auditResult: "",
      publicityDis: false,
      difficultyDegreeDis: false,
      quesLoading: false,
      quesPropertyDialog: false,
      difficultyDegree: 0.1,
      publicity: true,
      isClear: 0,
      courseLoading: false,
      formSearch: {
        courseId: "",
        courseName: "",
        creator: "",
        lastModifyName: "",
        auditStatus: "",
        name: "",
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      courseList: [],
      levelList: LEVEL_TYPE,
      dialogVisible: false,
      selectedPaperIds: [],
      fileList: [],
      uploadAction: "",
      formUpload: {
        paperName: "",
      },
      uploadData: {},
      fileLoading: false,
      exportDialog: false,
      exportModel: {
        id: "",
        courseCode: "",
        courseName: "",
        exportContentList: [],
        seqMode: "MODE1",
      },
      isShow: true,
      dialogModel: false,
      rowIds: [],
      isShowPrintExamPackage: false,
      isShowPrintExamPackagePassword: false,
      printExamPackagePassword: "",
      printFrom: {
        examId: "",
      },
      rules: {
        examId: [{ required: true, message: "请输入名称", trigger: "change" }],
      },
    };
  },
  computed: {
    ...mapState({
      user: (state) => state.user,
    }),
    courseInfoSelect() {
      var courseList = [];
      for (let course of this.courseList) {
        var courseInfo = course.name + "(" + course.code + ")";
        var courseId = course.id;
        var courseName = course.name;
        courseList.push({
          courseId: courseId,
          courseInfo: courseInfo,
          courseName: courseName,
        });
      }
      return courseList;
    },
    noBatchSelected() {
      return this.selectedPaperIds.length === 0;
    },
  },
  watch: {
    $route: "initVue",
  },
  created() {
    this.initVue();
  },
  methods: {
    getCourseName(courseId) {
      for (let course of this.courseList) {
        if (course.courseId == courseId) {
          this.formSearch.courseName = course.name;
        }
      }
    },
    editImportPaper(row) {
      //缓存查询对象
      this.getCourseName(this.formSearch.courseId);
      sessionStorage.setItem("paper", JSON.stringify(this.formSearch));
      sessionStorage.setItem("paper_currentPage", this.currentPage);
      sessionStorage.setItem("question_back", "false");
      this.$router.push({
        path: "/edit_paper_pending_trial/" + row.id + "/paper_pending_trial",
      });
    },
    afterAudit() {
      this.auditPaperDialog = false;
      this.searchPaper();
    },
    auditPapers(pass) {
      this.auditResult = pass;
      this.auditPaperDialog = true;
    },
    auditPaper(pass, id) {
      this.auditResult = pass;
      this.selectedPaperIds = [];
      this.selectedPaperIds.push(id);
      this.auditPaperDialog = true;
    },
    isShowAuditBtn(row) {
      if (
        row.auditStatus != "WITHDRAW" &&
        row.auditStatus != "NOT_PASS" &&
        this.isMyAudit(row)
      ) {
        return true;
      } else {
        return false;
      }
    },
    isMyAudit(row) {
      if (
        row.auditStatus == "FIRST_PENDING_TRIAL" &&
        this.user.auditAuthority == "FIRST"
      ) {
        return true;
      }
      if (
        row.auditStatus == "SECOND_PENDING_TRIAL" &&
        this.user.auditAuthority == "SECOND"
      ) {
        return true;
      }
      if (
        row.auditStatus == "THIRD_PENDING_TRIAL" &&
        this.user.auditAuthority == "THIRD"
      ) {
        return true;
      }
      return false;
    },
    exportPaper(row) {
      var key = this.user.key;
      var token = this.user.token;
      window.open(
        QUESTION_API +
          "/originalPaper/export/" +
          row.id +
          "?$key=" +
          key +
          "&$token=" +
          token
      );
    },
    submitPapers() {
      this.$confirm("确认提交试卷吗?", "提示", {
        type: "warning",
      }).then(() => {
        this.loading = true;
        this.$http
          .post(
            QUESTION_API + "/paper/submit",
            new URLSearchParams({ paperIds: this.selectedPaperIds })
          )
          .then(
            () => {
              this.$notify({
                message: "提交成功",
                type: "success",
              });
              this.searchPaper();
            },
            (error) => {
              this.$notify({
                message: error.response.data.desc,
                type: "error",
              });
              this.loading = false;
              this.searchPaper();
            }
          );
      });
    },
    submitPaper(row) {
      this.$confirm("确认提交试卷吗?", "提示", {
        type: "warning",
      }).then(() => {
        this.selectedPaperIds = [];
        this.selectedPaperIds.push(row.id);
        this.loading = true;
        this.$http
          .post(
            QUESTION_API + "/paper/submit",
            new URLSearchParams({ paperIds: this.selectedPaperIds })
          )
          .then(
            () => {
              this.$notify({
                message: "提交成功",
                type: "success",
              });
              this.searchPaper();
            },
            (error) => {
              this.$notify({
                message: error.response.data.desc,
                type: "error",
              });
              this.loading = false;
            }
          );
      });
    },
    isShowSubmitBtn(row) {
      if (
        row.creationBy == this.user.userId &&
        (row.auditStatus == "WITHDRAW" || row.auditStatus == "NOT_PASS")
      ) {
        return true;
      } else {
        return false;
      }
    },
    isShowWithdrawBtn(row) {
      if (
        row.creationBy == this.user.userId &&
        row.auditStatus != "WITHDRAW" &&
        row.auditStatus != "NOT_PASS"
      ) {
        return true;
      } else {
        return false;
      }
    },
    withdrawPapers() {
      this.$confirm("确认撤回试卷吗?", "提示", {
        type: "warning",
      }).then(() => {
        this.loading = true;
        this.$http
          .post(
            QUESTION_API + "/paper/withdraw",
            new URLSearchParams({ paperIds: this.selectedPaperIds })
          )
          .then(
            () => {
              this.$notify({
                message: "撤回成功",
                type: "success",
              });
              this.searchPaper();
            },
            (error) => {
              this.$notify({
                message: error.response.data.desc,
                type: "error",
              });
              this.loading = false;
              this.searchPaper();
            }
          );
      });
    },
    withdrawPaper(row) {
      this.$confirm("确认撤回试卷吗?", "提示", {
        type: "warning",
      }).then(() => {
        this.loading = true;
        this.selectedPaperIds = [];
        this.selectedPaperIds.push(row.id);
        this.$http
          .post(
            QUESTION_API + "/paper/withdraw",
            new URLSearchParams({ paperIds: this.selectedPaperIds })
          )
          .then(
            () => {
              this.$notify({
                message: "撤回成功",
                type: "success",
              });
              this.searchPaper();
            },
            (error) => {
              this.$notify({
                message: error.response.data.desc,
                type: "error",
              });
              this.loading = false;
            }
          );
      });
    },
    isShowDeleteBtn(row) {
      if (row.creationBy == this.user.userId && row.auditStatus == "WITHDRAW") {
        return true;
      } else {
        return false;
      }
    },
    deletePapers() {
      this.$confirm("确认删除试卷吗?", "提示", {
        type: "warning",
      }).then(() => {
        this.loading = true;

        this.$http
          .post(
            QUESTION_API + "/paper/audit/delete",
            new URLSearchParams({ paperIds: this.selectedPaperIds })
          )
          .then(
            () => {
              this.$notify({
                message: "删除成功",
                type: "success",
              });
              this.searchPaper();
            },
            (error) => {
              this.$notify({
                message: error.response.data.desc,
                type: "error",
              });
              this.loading = false;
              this.searchPaper();
            }
          );
      });
    },
    deletePaper(row) {
      this.$confirm("确认删除试卷吗?", "提示", {
        type: "warning",
      }).then(() => {
        this.loading = true;
        this.selectedPaperIds = [];
        this.selectedPaperIds.push(row.id);
        this.$http
          .post(
            QUESTION_API + "/paper/audit/delete",
            new URLSearchParams({ paperIds: this.selectedPaperIds })
          )
          .then(
            () => {
              this.$notify({
                message: "删除成功",
                type: "success",
              });
              this.searchPaper();
            },
            (error) => {
              this.$notify({
                message: error.response.data.desc,
                type: "error",
              });
              this.loading = false;
            }
          );
      });
    },
    resetForm() {
      this.formSearch = {
        courseId: "",
        courseName: "",
        level: "",
        name: "",
      };
    },
    //查询
    searchFrom() {
      this.currentPage = 1;
      this.searchPaper();
    },
    searchPaper() {
      this.selectedPaperIds = [];
      var pageNo = this.currentPage;
      this.currentPage = 1;
      this.loading = true;
      var url =
        QUESTION_API + "/pending_trial_paper/" + pageNo + "/" + this.pageSize;
      this.$http.get(url, { params: this.formSearch }).then((response) => {
        this.tableData = response.data.content;
        this.total = response.data.totalElements;
        this.currentPage = Number(pageNo);
      });
      this.loading = false;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.searchPaper();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.searchPaper();
    },
    selectChange(row) {
      this.selectedPaperIds = [];
      row.forEach((element) => {
        this.selectedPaperIds.push(element.id);
      });
    },
    //查询所有课程
    getCourses(query) {
      if (query) {
        query = query.trim();
      }
      this.courseLoading = true;
      this.$http
        .get(QUESTION_API + "/course/query?name=" + query + "&enable=true")
        .then((response) => {
          this.courseList = response.data;
          this.courseLoading = false;
        });
    },
    removeItem() {
      sessionStorage.removeItem("paper");
      sessionStorage.removeItem("paper_currentPage");
    },
    cancel(formData) {
      this.resetForm2(formData);
      this.dialogModel = false;
    },
    resetForm2(formData) {
      this.printFrom.examId = "";
      this.$refs[formData].clearValidate();
    },
    initVue() {
      this.isClear = this.$route.params.isClear;
      if (this.isClear == 0 || !this.isClear) {
        this.removeItem();
        this.formSearch = {
          courseId: "",
          courseName: "",
          level: "",
          name: "",
        };
        this.currentPage = 1;
      } else {
        this.formSearch = JSON.parse(sessionStorage.getItem("paper"));
        this.currentPage =
          sessionStorage.getItem("paper_currentPage") == null
            ? 1
            : parseInt(sessionStorage.getItem("paper_currentPage"));
      }
      this.getCourses(this.formSearch.courseName);
      this.searchPaper();
    },
  },
};
</script>
