<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" class="part-filter-form">
        <el-form-item label="课程">
          <el-select v-model="courseId" :disabled="true" placeholder="请选择">
            <el-option
              v-for="item in courseList"
              :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"
            placeholder="请选择题型"
            clearable
            @change="quesTypeChange"
          >
            <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-select
            v-model="formSearch.quesName"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in quesNameList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="难度" style="width: 160px">
          <el-select
            v-model="formSearch.difficult"
            placeholder="选择难度"
            clearable
          >
            <el-option
              v-for="(val, key) in DIFFICULTY_LEVEL_ENUM"
              :key="key"
              :value="key"
              :label="val"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="属性">
          <el-popover
            placement="bottom"
            width="400"
            trigger="hover"
            popper-class="property-popover"
            visible-arrow
          >
            <el-input
              slot="reference"
              v-model="propertyNames"
              placeholder="选择属性"
              readonly
            ></el-input>
            <el-tree
              ref="PropertyTreeRef"
              :data="propertyTree"
              show-checkbox
              default-expand-all
              node-key="questionPropertyId"
              :props="defaultProps"
              check-on-click-node
              :expand-on-click-node="false"
              @check-change="checkChange"
            >
            </el-tree>
          </el-popover>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchQuestionPaper"
            >查询</el-button
          >
        </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="课程" width="120">
          <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-column
          prop="difficulty"
          label="难度"
          width="80"
        ></el-table-column>
        <el-table-column prop="propertyInfo" label="属性"></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, DIFFICULTY_LEVEL_ENUM } 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: "",
        quesName: "",
        difficult: "",
        propertyIdList: [],
      },
      DIFFICULTY_LEVEL_ENUM,
      propertyTree: [],
      propertyNames: "",
      defaultProps: {
        label: "questionPropertyName",
        children: "childrenProperty",
      },
      course: "",
      paperId: "",
      paperDetailId: "",
      parentView: "",
      courseList: [],
      tableData: [],
      multipleSelection: [],
      quesNameList: [], // 来源大题
      currentPage: 1,
      pageSize: 10,
      total: 10,
      courseId: "",
      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;
    this.courseId = parseInt(this.$route.params.courseId);
    this.paperDetailId = this.$route.params.paperDetailId;
    this.parentView = this.$route.params.parentView;
    this.$http
      .get(QUESTION_API + "/course/" + this.courseId)
      .then((response) => {
        this.courseList.push(response.data);
      });
    this.searchQuestionPaper();
    this.getQuesNames();
    this.getPropertyTree();
  },
  mounted() {
    setTimeout(() => {
      this.$store.commit("UPDATE_CURRENT_PATHS", ["添加试题"]);
    }, 200);
  },
  methods: {
    // 查询来源大题
    async getQuesNames() {
      const url = QUESTION_API + "/paperStruct/quesNames";

      let params = {
        courseId: this.courseId,
        quesType: this.formSearch.questionType,
      };
      const res = await this.$http.get(url, {
        params,
      });

      this.quesNameList = res.data || [];
    },
    async getPropertyTree() {
      const url = QUESTION_API + "/courseProperty/tree";
      const res = await this.$http.post(
        url,
        {},
        {
          params: {
            courseId: this.courseId,
          },
        }
      );

      const resData = res.data || [];
      this.propertyTree = resData.map((item) => {
        let nitem = {};
        nitem.questionPropertyId = `c${item.coursePropertyId}`;
        nitem.questionPropertyName = item.coursePropertyName;
        nitem.childrenProperty = item.questionPropertyTrees;
        nitem.isCourse = true;
        return nitem;
      });
    },
    checkChange() {
      const validNodes = this.$refs.PropertyTreeRef.getCheckedNodes().filter(
        (item) => !item.isCourse
      );
      this.formSearch.propertyIdList = validNodes.map(
        (item) => item.questionPropertyId
      );
      this.propertyNames = validNodes
        .map((item) => item.questionPropertyName)
        .join("；");
    },
    quesTypeChange() {
      this.formSearch.quesName = "";
      this.getQuesNames();
    },
    //查询列表
    searchQuestionPaper() {
      this.loading = true;
      const url = `${QUESTION_API}/paper/listQuestion/${this.paperId}/${this.currentPage}/${this.pageSize}`;
      this.$http
        .post(
          url,
          {},
          {
            params: {
              quesType: this.formSearch.questionType,
              quesBody: this.formSearch.quesBody,
              quesName: this.formSearch.quesName,
              difficult: this.formSearch.difficult,
              propertyIdList: this.formSearch.propertyIdList.join(),
            },
          }
        )
        .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: "添加成功！",
              });
              if ("exam_paper_pending_trial" == this.parentView) {
                this.$router.push({
                  path:
                    "/edit_paper_pending_trial/" +
                    this.paperId +
                    "/" +
                    this.parentView,
                });
              } else {
                this.$router.push({
                  path: "/edit_paper/" + this.paperId + "/" + this.parentView,
                });
              }
            })
            .catch(() => {
              this.$notify({
                type: "error",
                message: "添加失败！",
              });
            });
        });
      }
    },
    //返回
    back() {
      if ("exam_paper_pending_trial" == this.parentView) {
        this.$router.push({
          path:
            "/edit_paper_pending_trial/" + this.paperId + "/" + this.parentView,
        });
      } else {
        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>
