<template>
  <section class="select-question body-content">
    <div class="part-box">
      <div class="part-box-header">
        <h2 class="part-box-title">选择试题</h2>
        <div>
          <el-button
            type="primary"
            icon="icon icon-save-white"
            @click="submitQues()"
            >确定</el-button
          >
          <el-button type="danger" plain icon="icon icon-back" @click="back()"
            >返回</el-button
          >
        </div>
      </div>
      <el-form
        :inline="true"
        :model="formSearch"
        label-position="right"
        label-width="90px"
        class="part-filter-form"
      >
        <el-form-item label="课程">
          <el-select v-model="course" :disabled="true" placeholder="请选择">
            <el-option
              v-for="item in courseList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型">
          <el-select
            v-model="formSearch.questionType"
            placeholder="请选择题型"
            @change="searchQuestionPaper"
          >
            <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 label="题干">
          <el-input
            v-model="formSearch.quesBody"
            placeholder="请输入题干"
            @blur="searchQuestionPaper"
          >
          </el-input>
        </el-form-item>
        <el-form-item> </el-form-item>
      </el-form>
    </div>

    <!-- 正文信息 -->
    <div class="part-box">
      <!-- 页面列表 -->
      <el-table :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="45"> </el-table-column>
        <el-table-column label="课程">
          <template slot-scope="scope">
            <span v-if="scope.row.course != null">{{
              scope.row.course.name
            }}</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="题干">
          <template slot-scope="scope">
            <span class="small">
              <rich-text
                :text-json="scope.row.quesBody"
                @click="prevViewQues(scope.row)"
              >
              </rich-text>
            </span>
          </template>
        </el-table-column>
      </el-table>
      <!--分页栏-->
      <div class="part-page">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="total"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 试题预览 -->
    <question-preview
      ref="QuestionPreview"
      :ques-model="quesModel"
    ></question-preview>
  </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 {
  name: "SelectQuestion",
  components: { QuestionPreview },
  data() {
    return {
      formSearch: {
        questionType: "",
        quesBody: "",
      },
      course: "",
      paperId: "",
      paperDetailId: "",
      parentView: "",
      courseList: [],
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
      total: 10,
      courseName: "",
      quesModel: {},
      questionTypes: [],
      quesDialog: false,
      loading: false,
      dialogLoading: false,
      singleRightAnswer: "", //接收单选答案
      multipleRightAnswer: [], //接收多选答案
    };
  },
  computed: {
    ...mapState({ user: (state) => state.user }),
  },
  //钩子函数
  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.paperId = this.$route.params.id;
    this.courseName = this.$route.params.courseName;
    var courseNo = this.$route.params.courseNo;
    this.paperDetailId = this.$route.params.paperDetailId;
    this.parentView = this.$route.params.parentView;
    this.courseList.push({ name: this.courseName, value: courseNo });
    this.course = this.courseList[0].value;
    this.searchQuestionPaper();
  },
  mounted() {
    setTimeout(() => {
      this.$store.commit("UPDATE_CURRENT_PATHS", ["添加试题"]);
    }, 200);
  },
  methods: {
    //查询列表
    searchQuestionPaper() {
      this.loading = true;
      this.$http
        .get(
          QUESTION_API +
            "/paper/listQuestion/" +
            this.paperId +
            "/" +
            this.currentPage +
            "/" +
            this.pageSize +
            "?quesType=" +
            this.formSearch.questionType +
            "&quesBody=" +
            this.formSearch.quesBody
        )
        .then((response) => {
          this.tableData = response.data.content;
          this.total = response.data.totalElements;
          this.loading = false;
        });
    },
    //分页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.searchQuestionPaper();
    },
    openQuesDialog() {
      this.quesDialog = true;
    },
    closeQuesDialog() {
      this.quesDialog = false;
      this.quesModel = {};
    },
    //预览
    prevViewQues(row) {
      this.quesModel = row;
      this.disposeSelectAnswer();
      this.$refs.QuestionPreview.open();
    },
    //添加试题
    submitQues() {
      if (this.multipleSelection.length === 0) {
        this.$notify({
          type: "error",
          message: "请选择要添加的试题",
        });
      } else {
        this.$confirm("是否添加这些试题？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.$http
            .post(
              QUESTION_API +
                "/paper/selectQuestions/" +
                this.paperId +
                "/" +
                this.paperDetailId,
              this.multipleSelection
            )
            .then(() => {
              this.$notify({
                type: "success",
                message: "添加成功！",
              });
              this.$router.push({
                path: "/edit_paper/" + this.paperId + "/" + this.parentView,
              });
            })
            .catch(() => {
              this.$notify({
                type: "error",
                message: "添加失败！",
              });
            });
        });
      }
    },
    //返回
    back() {
      this.$router.push({
        path: "/edit_paper/" + this.paperId + "/" + this.parentView,
      });
    },
    //全选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /**
     * 处理选择题答案显示
     * 处理套题下选择题答案显示
     */
    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 k = 0; k < subQuestions.length; k++) {
          var subQuestion = subQuestions[k];
          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 z = 0; z < subQuestion.quesOptions.length; z++) {
              var option_k = subQuestion.quesOptions[z];
              var orderNum_k = String.fromCharCode(65 + z);
              if (option_k.isCorrect == 1) {
                subQuestionMultipleRightAnswer.push(orderNum_k);
              }
            }
            subQuestion["quesAnswer"] = subQuestionMultipleRightAnswer
              .sort()
              .toString();
          }
        }
      }
    },
  },
};
</script>
