<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-select
            v-model="formSearch.basePaperId"
            filterable
            :remote-method="getPapers"
            remote
            clearable
            placeholder="请选择"
            @clear="getPapers('')"
          >
            <el-option
              v-for="item in paperList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型">
          <el-select
            v-model="formSearch.questionType"
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in questionTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="searchFrom">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="part-box-action">
        <div>
          <el-button
            type="primary"
            plain
            icon="icon icon-audit"
            @click="dispose"
            >快速审核</el-button
          >
          <el-button
            :disabled="noBatchSelected"
            type="danger"
            plain
            icon="icon icon-delete"
            @click="deleteQuestions"
            >批量删除</el-button
          >
          <el-button
            :disabled="noBatchSelected"
            type="primary"
            plain
            icon="icon icon-save"
            @click="retainQuestions"
            >批量保留</el-button
          >
        </div>
      </div>
    </div>
    <div class="part-box">
      <!-- 页面列表 -->
      <el-table
        v-loading="loading"
        :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="试卷名称">
          <template slot-scope="scope">
            <span>{{ scope.row.basePaperName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="题干" min-width="240">
          <template slot-scope="scope">
            <rich-text
              class="row-question-body"
              title="点击查看试题"
              :text-json="scope.row.quesBody"
              @click="prevViewQues(scope.row)"
            ></rich-text>
          </template>
        </el-table-column>
        <el-table-column label="题型大类" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.quesMainType | questionMainType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="题型小类" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.questionType | questionType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最高重复比率" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.maxRepetition }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.creationTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.creator }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="190" fixed="right">
          <template slot-scope="scope">
            <div class="operate_left">
              <el-button
                size="mini"
                type="primary"
                plain
                @click="info(scope.row)"
              >
                详情
              </el-button>
              <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
                      size="mini"
                      type="success"
                      plain
                      @click="retainQuestion(scope.row.id)"
                    >
                      保留
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      size="mini"
                      type="danger"
                      plain
                      @click="deleteQuestion(scope.row.id)"
                    >
                      删除
                    </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>

    <!-- 试题预览 -->
    <question-preview
      ref="QuestionPreview"
      :ques-model="quesModel"
    ></question-preview>

    <el-dialog title="提示" :visible.sync="deleteDialogVisible" append-to-body>
      <span>{{ deleteInfo }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="deleteDialogVisible = false"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </section>
</template>
<script>
import { QUESTION_API } from "@/constants/constants";
import { QUESTION_TYPES } from "../constants/constants";
import { mapState } from "vuex";
import QuestionPreview from "./QuestionPreview";

export default {
  components: { QuestionPreview },
  data() {
    return {
      selectedQuesIds: [],
      formSearch: {
        basePaperId: "",
        questionType: "",
        courseId: "",
        courseName: "",
      },
      paperList: [],
      courseList: [], //课程list
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 10,
      quesModel: {},
      questionTypes: [],
      quesDialog: false,
      loading: false,
      deleteDialogVisible: false,
      deleteInfo: "",
      singleRightAnswer: "", //接收单选答案
      multipleRightAnswer: [], //接收多选答案
      isClear: 0,
    };
  },
  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;
        courseList.push({ courseId: courseId, courseInfo: courseInfo });
      }
      return courseList;
    },
    answer() {
      if (this.quesModel.questionType == "SINGLE_ANSWER_QUESTION") {
        return this.singleRightAnswer;
      } else if (this.quesModel.questionType == "MULTIPLE_ANSWER_QUESTION") {
        var obj = this.multipleRightAnswer;
        return obj.sort().toString();
      } else {
        return this.quesModel.quesAnswer;
      }
    },
    noBatchSelected() {
      return this.selectedQuesIds.length === 0;
    },
  },
  watch: {
    $route: "initVue",
  },
  //钩子函数
  created() {
    var url =
      QUESTION_API +
      "/org/property/" +
      this.user.rootOrgId +
      "/ROOT_ORG_QUESTION_TYPES";
    this.$http.get(url).then((response) => {
      if (response.data && response.data.length > 0) {
        this.questionTypes = QUESTION_TYPES.filter((m) =>
          response.data.includes(m.value)
        );
      }
    });
    this.initVue();
  },
  methods: {
    dispose() {
      this.$router.push({
        name: "check_duplicate_info",
        query: {
          from: "list",
        },
      });
      sessionStorage.setItem("question", JSON.stringify(this.formSearch));
      sessionStorage.setItem("question_currentPage", this.currentPage);
    },
    deleteQuestions() {
      this.$confirm("确认删除吗?", "提示", {
        type: "warning",
      }).then(() => {
        this.$http
          .post(
            QUESTION_API + "/question/duplicate/delete",
            new URLSearchParams({ questionIds: this.selectedQuesIds })
          )
          .then(() => {
            this.$notify({
              message: "删除成功",
              type: "success",
            });
            this.searchQues();
          });
      });
    },
    retainQuestions() {
      this.$http
        .post(
          QUESTION_API + "/question/duplicate/retain",
          new URLSearchParams({ questionIds: this.selectedQuesIds })
        )
        .then(() => {
          this.$notify({
            message: "操作成功",
            type: "success",
          });
          this.searchQues();
        });
    },
    deleteQuestion(id) {
      this.$confirm("确认删除吗?", "提示", {
        type: "warning",
      }).then(() => {
        let quesIds = [];
        quesIds.push(id);
        this.$http
          .post(
            QUESTION_API + "/question/duplicate/delete",
            new URLSearchParams({ questionIds: quesIds })
          )
          .then(() => {
            this.$notify({
              message: "删除成功",
              type: "success",
            });
            this.searchQues();
          });
      });
    },
    retainQuestion(id) {
      let quesIds = [];
      quesIds.push(id);
      this.$http
        .post(
          QUESTION_API + "/question/duplicate/retain",
          new URLSearchParams({ questionIds: quesIds })
        )
        .then(() => {
          this.$notify({
            message: "操作成功",
            type: "success",
          });
          this.searchQues();
        });
    },
    selectChange(row) {
      this.selectedQuesIds = [];
      row.forEach((element) => {
        this.selectedQuesIds.push(element.id);
      });
    },
    //查询列表
    searchFrom() {
      this.currentPage = 1;
      this.searchQues();
    },
    searchQues() {
      var pageNo = this.currentPage || 1;
      this.currentPage = 1;
      this.tableData = [];
      var url =
        QUESTION_API +
        "/question/to_be_dispose/" +
        pageNo +
        "/" +
        this.pageSize;
      this.loading = true;
      this.$http.get(url, { params: this.formSearch }).then((response) => {
        this.tableData = response.data.content;
        this.currentPage = response.data.number;
        this.total = response.data.totalElements;
        this.loading = false;
      });
    },
    //分页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.searchQues();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.searchQues();
    },
    getCourseName(courseId) {
      for (let course of this.courseList) {
        if (course.courseId == courseId) {
          this.formSearch.courseName = course.name;
        }
      }
    },
    //修改
    info(row) {
      this.$router.push({
        name: "check_duplicate_info",
        query: {
          quesId: row.id,
          from: "question",
        },
      });
      sessionStorage.setItem("question", JSON.stringify(this.formSearch));
      sessionStorage.setItem("question_currentPage", this.currentPage);
    },
    //预览
    prevViewQues(row) {
      this.quesModel = row;
      this.disposeSelectAnswer();
      this.$refs.QuestionPreview.open();
    },
    //查询所有课程
    getCourses(query) {
      this.$http
        .get(QUESTION_API + "/course/query?name=" + query + "&enable=true")
        .then((response) => {
          this.courseList = response.data;
        });
    },
    getPapers(query) {
      this.$http
        .get(QUESTION_API + "/import_paper/to_be_dispose?name=" + query)
        .then((response) => {
          this.paperList = response.data;
        });
    },
    //重置查询表单
    resetSearchForm() {
      this.formSearch = {
        questionType: "",
        courseId: "",
      };
    },
    /*处理选择题答案显示，处理套题下选择题答案显示*/
    disposeSelectAnswer() {
      //处理选择题答案显示
      if (
        this.quesModel.questionType == "SINGLE_ANSWER_QUESTION" ||
        this.quesModel.questionType == "MULTIPLE_ANSWER_QUESTION"
      ) {
        let answers = [];
        this.quesModel.quesOptions.forEach((option, index) => {
          if (option.isCorrect) {
            answers.push(String.fromCharCode(65 + index));
          }
        });
        this.quesModel.quesAnswer = answers.sort().toString();
      }
      //处理套题下选择题答案显示
      if (this.quesModel.questionType == "NESTED_ANSWER_QUESTION") {
        var subQuestions = this.quesModel.subQuestions;
        for (var ii = 0; ii < subQuestions.length; ii++) {
          var subQuestion = subQuestions[ii];
          if (subQuestion.questionType == "SINGLE_ANSWER_QUESTION") {
            for (var j = 0; j < subQuestion.quesOptions.length; j++) {
              var option_j = subQuestion.quesOptions[j];
              var orderNum_j = String.fromCharCode(65 + j);
              if (option_j.isCorrect == 1) {
                subQuestion["quesAnswer"] = orderNum_j;
              }
            }
          }
          if (subQuestion.questionType == "MULTIPLE_ANSWER_QUESTION") {
            var subQuestionMultipleRightAnswer = [];
            for (var k = 0; k < subQuestion.quesOptions.length; k++) {
              var option2 = subQuestion.quesOptions[k];
              var orderNum2 = String.fromCharCode(65 + k);
              if (option2.isCorrect == 1) {
                subQuestionMultipleRightAnswer.push(orderNum2);
              }
            }
            subQuestion["quesAnswer"] = subQuestionMultipleRightAnswer
              .sort()
              .toString();
          }
        }
      }
    },
    initVue() {
      this.isClear = this.$route.params.isClear;
      if (this.isClear == 0 || !this.isClear) {
        sessionStorage.removeItem("question");
        sessionStorage.removeItem("question_currentPage");
        this.formSearch = {
          basePaperId: "",
          quesBodyText: "",
          questionType: "",
          courseId: "",
          courseLevel: "",
          courseName: "",
        };
        this.currentPage = 1;
      } else {
        this.formSearch = JSON.parse(sessionStorage.getItem("question"));
        this.currentPage = parseInt(
          sessionStorage.getItem("question_currentPage")
        );
      }
      if (this.formSearch && this.formSearch.courseName) {
        this.getCourses(this.formSearch.courseName);
      } else {
        this.formSearch = {
          basePaperId: "",
          quesBodyText: "",
          questionType: "",
          courseId: "",
          courseLevel: "",
          courseName: "",
        };
        this.getCourses("");
      }
      this.getPapers("");
      this.searchQues();
    },
  },
};
</script>
