<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="请选择"
            @change="getCoursesProperty('')"
            @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.courseLevel"
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in levelList"
              :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.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 label="属性名">
          <el-select
            v-model="formSearch.coursePropertyId"
            :remote-method="getCoursesProperty"
            :loading="coursePropertyLoading"
            remote
            filterable
            clearablee
            :disabled="updatePorperty"
            placeholder="请选择"
            @change="searchFirst"
          >
            <el-option
              v-for="item in coursePropertyList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- created by wwh -->
        <el-form-item label="一级属性">
          <el-select
            v-model="formSearch.firstPropertyId"
            filterable
            clearable
            :disabled="updateFirst"
            placeholder="请选择"
            @change="searchSecond"
          >
            <el-option
              v-for="item in firstPropertyList"
              :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.secondPropertyId"
            filterable
            clearable
            :disabled="updateSecond"
            placeholder="请选择"
          >
            <el-option
              v-for="item in secondPropertyList"
              :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.publicity"
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in publicityList"
              :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-button type="danger" plain @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="part-box">
      <!-- 页面列表 -->
      <el-table v-loading="loading" :data="tableData">
        <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="100">
          <template slot-scope="scope">
            <span>{{ getLevel(scope.row.course.level) }}</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">
            <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="160">
          <template slot-scope="scope">
            <div class="operate_left">
              <el-button
                v-if="!isNested(scope.row.questionType)"
                size="mini"
                type="primary"
                plain
                @click="updateRow(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                size="mini"
                type="danger"
                plain
                @click="deleteRow(scope.row)"
              >
                删除
              </el-button>
            </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, LEVEL_TYPE } from "../constants/constants";
import { mapState } from "vuex";
import QuestionPreview from "./QuestionPreview";

export default {
  name: "QuestionList",
  components: { QuestionPreview },
  data() {
    return {
      coursePropertyLoading: false,
      formSearch: {
        questionType: "",
        courseId: null,
        courseLevel: "",
        publicity: "",
        coursePropertyId: null,
        firstPropertyId: null,
        secondPropertyId: null,
      },
      courseList: [], //课程list
      levelList: LEVEL_TYPE, //层次list
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 10,
      quesModel: {},
      questionTypes: [],
      quesDialog: false,
      loading: false,
      deleteDialogVisible: false,
      deleteInfo: "",
      singleRightAnswer: "", //接收单选答案
      multipleRightAnswer: [], //接收多选答案
      publicityList: [
        { label: "公开", value: true },
        { label: "非公开", value: false },
      ],
      coursePropertyList: [], //课程属性集合
      firstPropertyList: [], //一级属性集合
      secondPropertyList: [], //二级属性集合
      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;
      }
    },
    updateFirst() {
      if (this.formSearch.coursePropertyId) {
        return false;
      }
      return true;
    },
    updateSecond() {
      if (this.formSearch.firstPropertyId) {
        return false;
      }
      return true;
    },
    updatePorperty() {
      if (this.formSearch.courseId) {
        return false;
      }
      return true;
    },
  },
  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: {
    getCoursesProperty(name) {
      this.coursePropertyLoading = true;
      this.formSearch.coursePropertyId = "";
      this.formSearch.firstPropertyId = "";
      this.formSearch.secondPropertyId = "";
      this.$httpWithMsg
        .get(
          QUESTION_API +
            "/courseProperty/enable?courseId=" +
            this.formSearch.courseId +
            "&name=" +
            name
        )
        .then((response) => {
          this.coursePropertyList = response.data;
          this.coursePropertyLoading = false;
        });
    },
    isMatchingQuestion(questionType) {
      if (
        questionType == "PARAGRAPH_MATCHING" ||
        questionType == "BANKED_CLOZE"
      ) {
        return true;
      } else {
        return false;
      }
    },
    isNested(questionType) {
      if (
        questionType == "PARAGRAPH_MATCHING" ||
        questionType == "BANKED_CLOZE" ||
        questionType == "CLOZE" ||
        questionType == "READING_COMPREHENSION" ||
        questionType == "LISTENING_QUESTION"
      ) {
        return true;
      } else {
        return false;
      }
    },
    resetForm() {
      this.formSearch = {
        questionType: "",
        courseId: null,
        courseLevel: "",
        publicity: "",
        coursePropertyId: null,
        firstPropertyId: "",
        secondPropertyId: "",
      };
    },
    getLevel(level) {
      if (level == "ZSB") {
        return "专升本";
      } else if (level == "GQZ") {
        return "高起专";
      } else if (level == "GQB") {
        return "高起本";
      } else if (level == "ALL") {
        return "不限";
      } else {
        return "";
      }
    },
    //查询列表
    searchFrom() {
      this.currentPage = 1;
      this.searchQues();
    },
    searchQues() {
      var pageNo = this.currentPage || 1;
      this.currentPage = 1;
      this.tableData = [];
      var url = QUESTION_API + "/question/" + pageNo + "/" + this.pageSize;
      this.loading = true;
      this.$http.get(url, { params: this.formSearch }).then((response) => {
        this.tableData = response.data.content;
        this.total = response.data.totalElements;
        this.currentPage = pageNo;
        this.loading = false;
      });
    },
    //分页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.searchQues();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.searchQues();
    },
    //修改
    updateRow(row) {
      //选择题：单选、多选
      if (
        row.questionType === "SINGLE_ANSWER_QUESTION" ||
        row.questionType === "MULTIPLE_ANSWER_QUESTION"
      ) {
        this.$router.push({
          path: "/questions/edit_select_question/" + row.id,
        });
      }
      //判断、填空、问答
      if (
        row.questionType === "BOOL_ANSWER_QUESTION" ||
        row.questionType === "FILL_BLANK_QUESTION" ||
        row.questionType === "TEXT_ANSWER_QUESTION"
      ) {
        this.$router.push({
          path: "/questions/edit_other_question/" + row.id,
        });
      }
      sessionStorage.setItem("question", JSON.stringify(this.formSearch));
      sessionStorage.setItem("question_currentPage", this.currentPage);
    },
    //删除
    deleteRow(row) {
      this.$confirm("确认删除试题吗?", "提示", {
        type: "warning",
      }).then(() => {
        this.loading = true;
        this.$http
          .delete(QUESTION_API + "/paper/deleteQuestion/" + row.id)
          .then(
            (response) => {
              if (response.data.length > 0) {
                this.loading = false;
                this.deleteInfo =
                  "该试题被试卷：" +
                  response.data.join(" , ") +
                  "使用,不能删除";
                this.deleteDialogVisible = true;
              } else {
                this.$notify({
                  message: "删除成功",
                  type: "success",
                });
                this.searchQues();
              }
            },
            () => {
              this.$notify({
                message: "删除失败",
                type: "error",
              });
              this.loading = false;
            }
          );
      });
    },
    //预览
    prevViewQues(row) {
      this.quesModel = row;
      this.disposeSelectAnswer();
      this.$refs.QuestionPreview.open();
    },
    getCourseById(cid) {
      this.$http.get(QUESTION_API + "/course/" + cid).then((response) => {
        this.courseList.push(response.data);
      });
    },
    //查询所有课程
    getCourses(query) {
      this.$http
        .get(QUESTION_API + "/course/query?name=" + query + "&enable=true")
        .then((response) => {
          this.courseList = response.data;
          this.coursePropertyList = [];
          this.firstPropertyList = [];
          this.secondPropertyList = [];
        });
    },
    //重置查询表单
    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();
          }
        }
      }
    },
    //查询一级属性
    searchFirst() {
      if (this.formSearch.coursePropertyId) {
        this.formSearch.firstPropertyId = "";
        this.formSearch.secondPropertyId = "";
        this.$http
          .get(
            QUESTION_API + "/property/first/" + this.formSearch.coursePropertyId
          )
          .then((response) => {
            this.firstPropertyList = response.data;
          });
      }
    },
    //查询二级属性
    searchSecond() {
      if (this.formSearch.firstPropertyId) {
        this.formSearch.secondPropertyId = "";
        this.$http
          .get(
            QUESTION_API + "/property/second/" + this.formSearch.firstPropertyId
          )
          .then((response) => {
            this.secondPropertyList = response.data;
          });
      }
    },
    getFirst() {
      if (this.formSearch.firstPropertyId) {
        this.$http
          .get(
            QUESTION_API +
              "/property/find?id=" +
              this.formSearch.firstPropertyId
          )
          .then((response) => {
            this.firstPropertyList.push(response.data);
            //查询二级
            this.getSecond();
          });
      }
    },
    getSecond() {
      if (this.formSearch.secondPropertyId) {
        this.$http
          .get(
            QUESTION_API +
              "/property/find?id=" +
              this.formSearch.secondPropertyId
          )
          .then((response) => {
            this.secondPropertyList.push(response.data);
          });
      }
    },
    initVue() {
      this.isClear = this.$route.params.isClear;
      if (this.isClear == 0 || !this.isClear) {
        sessionStorage.removeItem("question");
        sessionStorage.removeItem("question_currentPage");
        this.formSearch = {
          questionType: "",
          courseId: "",
          courseLevel: "",
          publicity: "",
          coursePropertyId: "",
          firstPropertyId: "",
          secondPropertyId: "",
        };
        this.currentPage = 1;
        this.getCourses("");
      } else {
        const formSearch = JSON.parse(sessionStorage.getItem("question"));
        this.currentPage = parseInt(
          sessionStorage.getItem("question_currentPage")
        );
        this.formSearch = { ...formSearch };
        if (this.formSearch && this.formSearch.courseId) {
          this.getCourseById(this.formSearch.courseId);
          this.getCoursesProperty("");
          this.formSearch.coursePropertyId = formSearch.coursePropertyId;
          if (this.formSearch.coursePropertyId) {
            this.searchFirst();
            this.formSearch.firstPropertyId = formSearch.firstPropertyId;
          }
          if (this.formSearch.firstPropertyId) {
            this.searchSecond();
            this.formSearch.secondPropertyId = formSearch.secondPropertyId;
          }
        } else {
          this.getCourses("");
        }
      }
      this.searchQues();
    },
  },
};
</script>
