<!-- 编辑填空，问答，判断题 -->
<template>
  <section v-loading="fullscreenLoading" class="content edit-question">
    <div class="part-box">
      <div class="part-box-header">
        <h1 class="part-box-title">
          {{ quesModel.id ? "试题修改" : "试题新增" }}
        </h1>
        <div>
          <el-button
            type="primary"
            icon="icon icon-save-white"
            :disabled="saveDisabled"
            @click="saveQues('quesModel')"
            >保存</el-button
          >
          <el-button
            type="danger"
            plain
            icon="icon icon-back"
            @click="backToQuesList()"
            >返回
          </el-button>
        </div>
      </div>

      <el-form
        ref="quesModel"
        class="padding-tb-20 form-tight"
        :model="quesModel"
        :rules="rules"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="题型">
          <el-select
            v-model="quesModel.questionType"
            :disabled="true"
            placeholder="请输入题型"
          >
            <el-option
              v-for="item in questionTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- created by weiwenhai -->
        <el-form-item label="难度">
          <el-select v-model="quesModel.difficulty" placeholder="请输入难度">
            <el-option
              v-for="item in difficultyList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公开度">
          <el-select v-model="quesModel.publicity" 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
          v-if="quesModel.questionType == 'TEXT_ANSWER_QUESTION'"
          label="作答类型"
        >
          <el-select v-model="quesModel.answerType">
            <el-option
              v-for="item in answerTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="属性列表">
          <el-tooltip
            v-for="(content, index) in quesModel.quesProperties"
            :key="index"
            placement="top"
          >
            <div slot="content">
              <span v-if="content.firstProperty != null"
                >一级属性：{{ content.firstProperty.name }}({{
                  content.firstProperty.code
                }})</span
              ><br />
              <span v-if="content.secondProperty != null"
                >二级属性：{{ content.secondProperty.name }}({{
                  content.secondProperty.code
                }})</span
              >
            </div>
            <el-tag
              :key="content.id"
              style="margin-right: 5px"
              closable
              effect="dark"
              type="primary"
              @close="handleClose(content)"
            >
              {{ content.courseProperty.name }}
            </el-tag>
          </el-tooltip>
        </el-form-item>
        <el-row :gutter="10">
          <el-col :xs="6" :sm="6" :md="6" :lg="6">
            <el-form-item label="属性名">
              <el-select
                v-model="coursePropertyId"
                :remote-method="getCoursesProperty"
                :loading="coursePropertyLoading"
                remote
                filterable
                clearable
                placeholder="属性名"
                class="property_with"
                @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>
          </el-col>
          <el-col :xs="6" :sm="6" :md="6" :lg="6">
            <el-form-item label="一级">
              <el-select
                v-model="firstPropertyId"
                placeholder="一级"
                class="property_with"
                @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-col>
          <el-col :xs="6" :sm="6" :md="6" :lg="6">
            <el-form-item label="二级">
              <el-select
                v-model="secondPropertyId"
                placeholder="二级"
                class="property_with"
              >
                <el-option
                  v-for="item in secondPropertyList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="3" :sm="3" :md="3" :lg="3">
            <el-form-item label-width="0px">
              <el-button
                type="primary"
                icon="icon icon-plus-white"
                @click="insertProperty"
                >新增属性</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="part-box">
      <el-form class="form-tight" label-width="100px">
        <!-- end -->
        <el-form-item label="题干" prop="quesBody">
          <v-editor
            v-model="quesModel.quesBody"
            :enable-answer-point="enableAnswerPoint"
            @change="quesBodyChange"
          ></v-editor>
        </el-form-item>

        <el-form-item
          v-for="(option, index) in quesModel.quesOptions"
          :key="option.number"
        >
          <div class="question-edit-option">
            <div class="option-check">
              {{ index | optionOrderWordFilter }}
            </div>
            <div class="option-body">
              <v-editor v-model="option.quesBody"></v-editor>
            </div>
          </div>
        </el-form-item>

        <!-- <div class="line-seperator"></div> -->

        <!-- 非套题 -->
        <!-- <el-form-item
          v-if="
            quesModel.questionType !== 'NESTED_ANSWER_QUESTION' &&
            quesModel.questionType !== 'BOOL_ANSWER_QUESTION'
          "
          label="答案"
          prop="quesAnswer"
        >
          <v-editor v-model="quesModel.quesAnswer"></v-editor>
        </el-form-item> -->
        <el-form-item
          v-if="quesModel.questionType === 'FILL_BLANK_QUESTION'"
          label="答案"
          prop="quesAnswer"
        >
          <div v-if="quesAnswer" class="option-list">
            <div
              v-for="(opt, index) of quesAnswer"
              :key="index"
              class="option-item"
            >
              <div class="option-item-info">
                <span>（{{ index + 1 }}）</span>
              </div>
              <v-editor
                :value="opt"
                class="option-item-body"
                @change="(val) => updateAnswerPoint(index, val)"
              />
            </div>
          </div>
        </el-form-item>
        <!-- 问答题 -->
        <el-form-item
          v-if="quesModel.questionType === 'TEXT_ANSWER_QUESTION'"
          label="答案"
          prop="quesAnswer"
        >
          <v-editor v-model="quesAnswer" @change="textAnswerChange"></v-editor>
        </el-form-item>
        <!-- 判断题 -->
        <el-form-item
          v-if="quesModel.questionType == 'BOOL_ANSWER_QUESTION'"
          label="答案"
          prop="quesAnswer"
        >
          <el-select
            v-model="quesAnswer"
            placeholder="请选择"
            @change="boolAnswerChange"
          >
            <el-option
              v-for="op in options"
              :key="op.value"
              :label="op.label"
              :value="op.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
  </section>
</template>
<script>
import { QUESTION_API } from "@/constants/constants";
import { isEmptyStr, QUESTION_TYPES } from "../constants/constants";

export default {
  name: "EditOtherApp",
  data() {
    return {
      coursePropertyLoading: false,
      fullscreenLoading: false,
      questionTypes: QUESTION_TYPES,
      courseName: "",
      courseId: "",
      paperDetailId: "",
      paperId: "",
      quesModel: {
        courseId: "",
        quesAnswer: "",
        quesBody: "",
        questionType: "",
        difficulty: "易",
        difficultyDegree: 0.5,
        publicity: true,
        answerType: "",
        quesProperties: [],
        score: 0,
      },
      quesAnswer: null,
      prevAnswerPointCount: 0,
      options: [
        {
          value: 0,
          label: "错误",
        },
        {
          value: 1,
          label: "正确",
        },
      ],
      difficultyList: [
        { label: "难", value: "难" },
        { label: "中", value: "中" },
        { label: "易", value: "易" },
      ],
      publicityList: [
        { label: "公开", value: true },
        { label: "非公开", value: false },
      ],
      answerTypes: [
        { label: "文本", value: "DIVERSIFIED_TEXT" },
        { label: "音频", value: "SINGLE_AUDIO" },
      ],
      coursePropertyList: [],
      coursePropertyId: "", //课程属性
      firstPropertyList: [], //一级属性集合
      firstPropertyId: "", //一级属性id
      secondPropertyList: [], //二级属性集合
      secondPropertyId: "", //二级属性id
      //验证
      rules: {
        quesAnswer: [
          { required: true, message: "请输入答案", trigger: "change" },
        ],
      },
    };
  },
  computed: {
    saveDisabled() {
      if (
        !this.questionId &&
        this.quesModel.quesOptions &&
        this.quesModel.quesOptions.length == 0
      ) {
        return true;
      }
      return false;
    },
    enableAnswerPoint() {
      return this.quesModel.questionType === "FILL_BLANK_QUESTION";
    },
  },
  created() {
    this.paperId = this.$route.params.paperId;
    this.paperDetailId = this.$route.params.paperDetailId;
    this.courseId = this.$route.params.courseId;
    let questionType = this.$route.params.questionType;
    if (questionType) {
      this.quesModel.questionType = questionType;
    }
    this.questionId = this.$route.params.id;
    if (this.questionId) {
      this.quesModel["id"] = this.questionId;
      this.getQues(this.questionId);
    } else if (this.courseId) {
      this.getCoursesProperty("");
    }

    if (isEmptyStr(this.quesModel.answerType)) {
      this.quesModel.answerType = "DIVERSIFIED_TEXT";
    }
  },
  mounted() {
    setTimeout(() => {
      if (this.quesModel.id) {
        this.$store.commit("UPDATE_CURRENT_PATHS", ["试题管理", "试题修改"]);
      } else {
        this.$store.commit("UPDATE_CURRENT_PATHS", ["试题管理", "试题新增"]);
      }
    }, 200);
  },
  methods: {
    getQuesPropertyKey(quesProp) {
      if (!quesProp) {
        return "";
      } else if (quesProp.secondProperty.id) {
        return (
          quesProp.courseProperty.id +
          "-" +
          quesProp.firstProperty.id +
          "-" +
          quesProp.secondProperty.id
        );
      } else {
        return quesProp.courseProperty.id + "-" + quesProp.firstProperty.id;
      }
    },
    getCoursesProperty(name) {
      this.coursePropertyLoading = true;
      this.$httpWithMsg
        .get(
          QUESTION_API +
            "/courseProperty/enable?courseId=" +
            this.courseId +
            "&name=" +
            name
        )
        .then((response) => {
          this.coursePropertyList = response.data;
          this.coursePropertyLoading = false;
        });
    },
    boolAnswerChange(val) {
      this.quesModel.quesAnswer = val ? "true" : "false";
    },
    textAnswerChange(val) {
      this.quesModel.quesAnswer = JSON.stringify([val]);
    },
    resetNumberAndSaveAnswerPoints(answer) {
      this.quesAnswer = answer.map((element, index) => {
        element.index = index + 1;
        return element;
      });
      this.quesModel.quesAnswer = JSON.stringify(this.quesAnswer);
    },
    updateAnswerPoint(index, value) {
      // console.log(index, this.question.answer[index]);
      this.quesAnswer[index] = { ...value };
      this.resetNumberAndSaveAnswerPoints(this.quesAnswer);
    },
    getAnswerPointCount(bodyJson) {
      let count = 0;
      bodyJson.sections.forEach((section) => {
        section.blocks.forEach((block) => {
          if (block.type === "cloze") count++;
        });
      });
      return count;
    },
    quesBodyChange(quesBodyJson) {
      this.quesModel.quesBody = quesBodyJson;

      let curPonitCount = this.getAnswerPointCount(quesBodyJson);
      if (curPonitCount === this.prevAnswerPointCount) return;
      this.prevAnswerPointCount = curPonitCount;

      let newAnswer = [];
      for (let i = 0; i < curPonitCount; i++) {
        newAnswer.push(
          (this.quesAnswer && this.quesAnswer[i]) || { sections: [] }
        );
      }

      this.resetNumberAndSaveAnswerPoints(newAnswer);
    },
    saveQues(formName) {
      if (!this.quesModel.difficulty) {
        this.$notify({
          message: "请选择试题难度",
          type: "error",
        });
        return;
      }

      if (this.quesModel.questionType === "FILL_BLANK_QUESTION") {
        const pointCount = this.getAnswerPointCount(this.quesModel.quesBody);
        if (!pointCount) {
          this.$notify({
            message: "请插入答题点",
            type: "error",
          });
          return;
        }
      }

      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.questionId) {
            this.fullscreenLoading = true;
            //修改逻辑
            this.$http
              .put(QUESTION_API + "/question", this.quesModel)
              .then(() => {
                this.$notify({
                  message: "保存成功",
                  type: "success",
                });
                this.fullscreenLoading = false;
              });
          } else {
            //新增逻辑
            this.quesModel.courseId = this.courseId;
            this.fullscreenLoading = true;
            this.$http
              .post(
                QUESTION_API +
                  "/paper/addQuestion/" +
                  this.paperId +
                  "/" +
                  this.paperDetailId,
                this.quesModel
              )
              .then(() => {
                this.fullscreenLoading = false;
                this.$notify({
                  type: "success",
                  message: `保存成功`,
                });
                this.$router.push({ path: "/questions/question_list/0" });
              })
              .catch(() => {
                this.fullscreenLoading = false;
              });
          }
        } else {
          return false;
        }
      });
    },
    getQues(id) {
      this.$http.get(QUESTION_API + "/question/" + id).then((response) => {
        this.quesModel = response.data;
        this.courseId = this.quesModel.course.id;
        if (isEmptyStr(this.quesModel.answerType)) {
          this.quesModel.answerType = "DIVERSIFIED_TEXT";
        }

        if (this.quesModel.questionType === "BOOL_ANSWER_QUESTION") {
          this.quesAnswer = this.quesModel.quesAnswer === "true" ? 1 : 0;
        } else if (this.quesModel.questionType === "TEXT_ANSWER_QUESTION") {
          const answer = JSON.parse(this.quesModel.quesAnswer);
          this.quesAnswer = answer[0];
        } else if (this.quesModel.questionType === "FILL_BLANK_QUESTION") {
          const answer = JSON.parse(this.quesModel.quesAnswer);
          this.quesAnswer = answer;
          this.prevAnswerPointCount = this.getAnswerPointCount(
            this.quesModel.quesBody
          );
        } else {
          this.quesAnswer = null;
        }
        this.getCoursesProperty("");
      });
    },
    backToQuesList() {
      this.$router.push({
        path: "/questions/question_list/1",
      });
    },
    //查询一级属性
    searchFirst() {
      this.firstPropertyId = "";
      this.secondPropertyId = "";
      this.secondPropertyList = [];
      this.$http
        .get(QUESTION_API + "/property/first/" + this.coursePropertyId)
        .then((response) => {
          this.firstPropertyList = response.data;
        });
    },
    //查询二级属性
    searchSecond() {
      this.secondPropertyId = "";
      this.$http
        .get(QUESTION_API + "/property/second/" + this.firstPropertyId)
        .then((response) => {
          this.secondPropertyList = response.data;
        });
    },
    //新增属性
    insertProperty() {
      if (!this.checkInsertPro()) {
        return false;
      }
      var quesProperty = {
        key: "",
        courseProperty: {},
        firstProperty: {},
        secondProperty: {},
      };
      if (
        this.quesModel.quesProperties === undefined ||
        this.quesModel.quesProperties === null ||
        this.quesModel.quesProperties.length == 0
      ) {
        this.quesModel.quesProperties = [];
      }
      let quesPropertyKey =
        this.coursePropertyId +
        "-" +
        this.firstPropertyId +
        "-" +
        this.secondPropertyId;
      for (let quesPro of this.quesModel.quesProperties) {
        if (quesPro.key == quesPropertyKey) {
          this.$notify({
            message: "该属性已存在，请重新选择",
            type: "error",
          });
          return false;
        }
      }
      for (let property of this.coursePropertyList) {
        if (property.id == this.coursePropertyId) {
          quesProperty.courseProperty = property;
        }
      }
      //取到一级属性对象
      for (let property of this.firstPropertyList) {
        if (property.id == this.firstPropertyId) {
          quesProperty.firstProperty = property;
        }
      }
      //判断是否有二级属性
      if (
        this.secondPropertyList != undefined &&
        this.secondPropertyList.length > 0
      ) {
        if (!this.secondPropertyId) {
          this.$notify({
            message: "请选择二级属性",
            type: "error",
          });
          return false;
        }
      }
      //取到二级属性对象
      for (let property of this.secondPropertyList) {
        if (property.id == this.secondPropertyId) {
          quesProperty.secondProperty = property;
        }
      }
      quesProperty.key = this.getQuesPropertyKey(quesProperty);
      this.quesModel.quesProperties.push(quesProperty);
      this.quesModel = Object.assign({}, this.quesModel);
      //清空下拉框
      this.coursePropertyId = "";
      this.firstPropertyId = "";
      this.secondPropertyId = "";
      this.firstPropertyList = [];
      this.secondPropertyList = [];
    },
    //删除属性
    handleClose(tag) {
      this.quesModel.quesProperties.splice(
        this.quesModel.quesProperties.indexOf(tag),
        1
      );
      this.quesModel = Object.assign({}, this.quesModel);
    },
    //新增属性验证
    checkInsertPro() {
      if (!this.coursePropertyId) {
        this.$notify({
          message: "请选择属性",
          type: "error",
        });
        return false;
      }
      if (!this.firstPropertyId) {
        this.$notify({
          message: "请选择一级属性",
          type: "error",
        });
        return false;
      }
      return true;
    },
  },
};
</script>
