<template>
  <div v-loading="fullscreenLoading">
    <!-- 头信息 -->
    <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="submitForm('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-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>
        <!--
              <el-form-item label="分数">
                  <el-input placeholder="分数" v-model="quesModel.score" style="width:50px;"></el-input>
              </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.coursePropertyName || 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 + '(' + item.code + ')'"
                  :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 + '(' + item.code + ')'"
                  :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>
        <!-- end -->
      </el-form>
    </div>
    <div class="part-box">
      <el-form class="form-tight" label-width="100px">
        <el-form-item label="题干" prop="quesBody">
          <v-editor v-model="quesModel.quesBody"></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">
              <el-radio
                v-if="quesModel.questionType === 'SINGLE_ANSWER_QUESTION'"
                v-model="singleRightAnswer"
                :label="index | optionOrderWordFilter"
              ></el-radio>
              <el-checkbox
                v-if="quesModel.questionType === 'MULTIPLE_ANSWER_QUESTION'"
                v-model="multipleRightAnswer"
                :label="index | optionOrderWordFilter"
              ></el-checkbox>
            </div>
            <div class="option-body">
              <v-editor v-model="option.optionBody"></v-editor>
            </div>
            <div class="option-delete">
              <el-button
                size="mini"
                circle
                type="danger"
                icon="el-icon-delete"
                title="删除"
                @click.prevent="removeQuesOption(option)"
              ></el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="icon icon-plus-white"
            @click="addQuesOption"
            >新增选项</el-button
          >
        </el-form-item>
        <div class="line-seperator"></div>
        <el-form-item label="答案">
          <div v-html="answer"></div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { QUESTION_API } from "@/constants/constants";
import { isEmptyStr, QUESTION_TYPES } from "../constants/constants";
import { checkRichTextContentIsEmpty } from "@/plugins/utils";

export default {
  name: "EditSelectApp",
  data() {
    return {
      coursePropertyLoading: false,
      questionTypes: QUESTION_TYPES,
      fullscreenLoading: false,
      paperId: "",
      paperDetailId: "",
      questionId: "",
      quesModel: {
        quesBody: "",
        quesOptions: [],
        quesAnswer: "",
        questionType: "",
        courseId: "",
        difficulty: "易",
        difficultyDegree: 0.5,
        publicity: true,
        answerType: "",
        quesProperties: [],
        score: 1,
      },
      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: {
        // quesBody: [
        //     { required: true, message: '请输入题干', trigger: 'blur'}
        // ]
      },
      singleRightAnswer: "", //接收单选答案
      multipleRightAnswer: [], //接收多选答案
    };
  },
  computed: {
    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();
      }
      return this.quesModel.quesAnswer;
    },
    saveDisabled() {
      if (!this.questionId && this.quesModel.quesOptions.length == 0) {
        return true;
      }
      return false;
    },
  },
  created() {
    let questionId = this.$route.params.id;
    if (questionId) {
      this.questionId = questionId;
      this.quesModel["id"] = questionId;
      this.findQuestionById(questionId);
    }
    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;
    }
    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;
        });
    },
    findQuestionById(questionId) {
      this.$http
        .get(QUESTION_API + "/question/" + questionId)
        .then((response) => {
          this.quesModel = response.data;
          this.courseId = this.quesModel.course.id;
          if (this.quesModel.quesOptions) {
            for (var i = 0; i < this.quesModel.quesOptions.length; i++) {
              var option = this.quesModel.quesOptions[i];
              if (
                this.quesModel.questionType == "SINGLE_ANSWER_QUESTION" &&
                option.isCorrect == 1
              ) {
                this.singleRightAnswer = String.fromCharCode(65 + i);
              }
              if (
                this.quesModel.questionType == "MULTIPLE_ANSWER_QUESTION" &&
                option.isCorrect == 1
              ) {
                this.multipleRightAnswer.push(String.fromCharCode(65 + i));
              }
            }
          }

          if (isEmptyStr(this.quesModel.answerType)) {
            this.quesModel.answerType = "DIVERSIFIED_TEXT";
          }

          this.getCoursesProperty("");
        });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.quesModel.quesOptions.length > 20) {
            this.$notify({
              message: "选项最多20个",
              type: "error",
            });
            return;
          }

          if (
            this.quesModel.quesOptions.length &&
            this.quesModel.quesOptions.some((item) =>
              checkRichTextContentIsEmpty(item.optionBody)
            )
          ) {
            this.$notify({
              message: "有选项内容为空",
              type: "error",
            });
            return;
          }

          this.setRightAnswer();
          if (!this.hasAnswer()) {
            this.$notify({
              message: "请选择答案",
              type: "error",
            });
            return false;
          }

          if (this.questionId) {
            this.editQuestion();
          } else {
            this.saveNewQuestion();
          }
        } else {
          return false;
        }
      });
    },
    //修改试题
    editQuestion() {
      if (this.quesModel.quesOptions.length == 0) {
        this.$confirm("无选项将删除该试题, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.fullscreenLoading = true;
            this.$http
              .delete(
                QUESTION_API + "/paper/deleteQuestion/" + this.quesModel.id
              )
              .then((response) => {
                if (response.data.length > 0) {
                  this.deleteInfo =
                    "该试题被试卷：" +
                    response.data.join(" , ") +
                    "使用,不能删除";
                  this.deleteDialogVisible = true;
                } else {
                  this.$notify({
                    message: "删除成功",
                    type: "success",
                  });
                  this.$router.push({ path: "/questions/question_list/0" });
                }
              });
          })
          .catch(() => {});
      } else {
        this.fullscreenLoading = true;
        this.$http.put(QUESTION_API + "/question", this.quesModel).then(() => {
          this.$notify({
            message: "保存成功",
            type: "success",
          });
          this.fullscreenLoading = false;
        });
      }
    },
    //新增试题
    saveNewQuestion() {
      if (!this.quesModel.difficulty) {
        this.$notify({
          message: "请选择试题难度",
          type: "error",
        });
        return false;
      }
      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;
        });
    },
    //新增选项
    addQuesOption() {
      if (this.quesModel.quesOptions.length >= 20) {
        this.$notify({
          message: "选项最多20个",
          type: "error",
        });
        return;
      }
      this.quesModel.quesOptions.push({
        number: "",
        optionBody: "",
        isCorrect: "",
      });
      for (var i = 0; i < this.quesModel.quesOptions.length; i++) {
        this.quesModel.quesOptions[i]["number"] = i + 1;
      }
    },
    //删除选项
    removeQuesOption(option) {
      this.singleRightAnswer = "";
      this.multipleRightAnswer = [];
      let index = this.quesModel.quesOptions.indexOf(option);
      if (index !== -1) {
        this.quesModel.quesOptions.splice(index, 1);
      }
      if (this.quesModel.quesOptions.length > 0) {
        for (var i = 0; i < this.quesModel.quesOptions.length; i++) {
          var quesOption = this.quesModel.quesOptions[i];
          quesOption["number"] = i + 1;
          if (quesOption.isCorrect == 1) {
            var answerOrderNum = String.fromCharCode(65 + i);
            if (this.quesModel.questionType == "SINGLE_ANSWER_QUESTION") {
              this.singleRightAnswer = answerOrderNum;
            }
            if (this.quesModel.questionType == "MULTIPLE_ANSWER_QUESTION") {
              this.multipleRightAnswer.push(answerOrderNum);
            }
          }
        }
      }
    },
    //在正确的option上设置isCorrect=1
    setRightAnswer() {
      if (this.quesModel.quesOptions.length == 0) {
        return false;
      }
      let quesAnswer = [];
      for (var i = 0; i < this.quesModel.quesOptions.length; i++) {
        var option = this.quesModel.quesOptions[i];
        var answerOrderNum = String.fromCharCode(65 + i);
        if (this.quesModel.questionType == "SINGLE_ANSWER_QUESTION") {
          option["isCorrect"] =
            answerOrderNum == this.singleRightAnswer ? 1 : 0;
        }
        if (this.quesModel.questionType == "MULTIPLE_ANSWER_QUESTION") {
          option["isCorrect"] =
            this.multipleRightAnswer.indexOf(answerOrderNum) > -1 ? 1 : 0;
        }
        if (option["isCorrect"]) quesAnswer.push(i + 1);
      }
      this.quesModel.quesAnswer = JSON.stringify(quesAnswer);
    },
    hasAnswer() {
      if (this.quesModel.questionType == "SINGLE_ANSWER_QUESTION") {
        if (!this.singleRightAnswer || this.singleRightAnswer == "") {
          return false;
        } else {
          return true;
        }
      }
      if (this.quesModel.questionType == "MULTIPLE_ANSWER_QUESTION") {
        if (!this.multipleRightAnswer || this.multipleRightAnswer == "") {
          return false;
        } else {
          return true;
        }
      }
    },
    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 = "";
      if (this.firstPropertyId) {
        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>
