<template>
  <div
    class="el-dialog-wrapper"
    v-show="diaVisible"
    width="400"
    center
    @click.self="cancel"
  >
    <div class="el-dialog-content">
      <p class="title">
        设置答案 <i class="fa fa-exchange" @click="editType = !editType"></i>
        <!-- 设置答案 -->
        <i class="el-icon-close" @click="cancel"></i>
      </p>
      <div v-if="editType">
        <div v-for="(item, index) in FormQuestionList" :key="index">
          <template v-for="(subQuestions, indexs) in item.subQuestions">
            <div
              class="sub-questions"
              :key="indexs"
              v-if="subQuestions.correctAnswer"
            >
              <div class="qs-num">题{{ subQuestions.questionIndex }}</div>
              <div class="qs-options qs-options2">
                <p v-if="subQuestions.questionType == 4" class="answer-box">
                  <span
                    class="answer-s"
                    :class="subQuestions.correctAnswer == 1 ? 'active' : ''"
                    @click="subQuestions.correctAnswer = 1"
                    >✓</span
                  >
                  <span
                    class="answer-s"
                    :class="subQuestions.correctAnswer == 2 ? 'active' : ''"
                    @click="subQuestions.correctAnswer = 2"
                    >✗</span
                  >
                </p>
                <p v-if="subQuestions.questionType == 3" class="answer-box">
                  <span
                    class="answer-s"
                    v-for="option in subQuestions.answerOptions"
                    :class="
                      subQuestions.correctAnswer.includes(option)
                        ? 'active'
                        : ''
                    "
                    :key="option"
                    @click="changAnswer(subQuestions, option)"
                    >{{ option }}</span
                  >
                </p>
                <p v-if="subQuestions.questionType == 2" class="answer-box">
                  <span
                    class="answer-s"
                    v-for="option in subQuestions.answerOptions"
                    :class="
                      subQuestions.correctAnswer == option ? 'active' : ''
                    "
                    :key="option"
                    @click="subQuestions.correctAnswer = option"
                    >{{ option }}</span
                  >
                </p>
              </div>
            </div>
          </template>
        </div>
      </div>
      <div v-else>
        <p class="dia-tips">
          请点击选项按钮设置答案,多选题题目之间用“,”隔开，若添加5道题：“AC,AD,BD,AC,CD”
        </p>
        <div class="dia-question-box">
          <div v-for="(item, index) in FormQuestionList2" :key="index">
            <div class="set-questions">
              <div class="qs-num">
                <p class="txt">{{ item.name }}</p>
                <p class="num">共{{ item.list.length }}题</p>
              </div>
              <div class="qs-options">
                <p class="ipt">
                  <el-input
                    v-model="item.answerList"
                    @keydown.native="keydownAnswer($event)"
                  ></el-input>
                </p>
                <p class="answer-box">
                  <template v-if="item.list[0].questionType == 4">
                    <span
                      class="answer-s active"
                      @click="
                        item.answerList.length < item.list.length
                          ? (item.answerList += '✓')
                          : ''
                      "
                      >✓</span
                    >
                    <span
                      class="answer-s active"
                      @click="
                        item.answerList.length < item.list.length
                          ? (item.answerList += '✗')
                          : ''
                      "
                      >✗</span
                    >
                  </template>
                  <template v-if="item.list[0].questionType == 3">
                    <span
                      class="answer-s active"
                      v-for="option in item.list[0].answerOptions"
                      :key="option"
                      @click="setAnswer(item, option)"
                      >{{ option }}</span
                    >
                    <span
                      class="answer-s active"
                      @click="
                        item.answerList.split(',').length < item.list.length
                          ? (item.answerList += ',')
                          : ''
                      "
                      >,</span
                    >
                  </template>
                  <template
                    v-if="item.list[0].questionType == 2"
                    class="answer-box"
                  >
                    <span
                      class="answer-s active"
                      v-for="option in item.list[0].answerOptions"
                      :key="option"
                      @click="
                        item.answerList.length < item.list.length
                          ? (item.answerList += option)
                          : ''
                      "
                      >{{ option }}</span
                    >
                  </template>
                  <span
                    class="answer-s delButton"
                    @click="item.answerList = item.answerList.slice(0, -1)"
                    >x</span
                  >
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="footer-box">
        <el-button class="dia-btn" type="primary" @click="saveAnswer"
          >确 定</el-button
        >
        <el-button class="dia-btn" type="danger" @click="cancel"
          >取 消</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import { deepClone, checkAnswer } from "utils";
export default {
  name: "SetAnswer",
  props: {
    diaVisible: false, //修改答案
    paperId: "",
    questionList: Array,
  },
  data() {
    return {
      editType: true, //修改答案模式
      FormQuestionList: [],
      FormQuestionList2: [],
    };
  },
  watch: {
    questionList: {
      handler: function () {
        this.FormQuestionList = deepClone(this.questionList);
        this.FormQuestionList2 = [];
        console.log(this.questionList);
        // 组合每道大题中的相同题目
        let questionList = deepClone(this.questionList);
        let jsons = {};
        let answerOptions = [];
        for (let i = 0; i < questionList.length; i++) {
          questionList[i].subQuestions.map((items) => {
            let txt = this.setSubPro(items.questionType);
            if (jsons[txt]) {
              jsons[txt].push(items);
            } else {
              jsons[txt] = [items];
            }
            if (items.questionType == 2 || items.questionType == 3) {
              if (items.answerOptions.length > answerOptions.length) {
                answerOptions = items.answerOptions;
              }
              jsons[txt][0].answerOptions = answerOptions;
            }
          });
          console.log(jsons);
        }
        this.FormQuestionList2 = Object.keys(jsons).map((item) => {
          let answerList = "";
          jsons[item].map((items, index) => {
            if (items.questionType == 2) {
              answerList += items.correctAnswer;
            } else if (items.questionType == 3) {
              answerList +=
                items.correctAnswer +
                (jsons[item].length - 1 != index ? "," : "");
            } else if (items.questionType == 4) {
              answerList += items.correctAnswer == 1 ? "✓" : "✗";
            }
          });
          return {
            name: item,
            list: jsons[item],
            answerList: answerList,
          };
        });
      },
      deep: true,
    },
  },
  methods: {
    setSubPro(type) {
      let tit;
      switch (type) {
        case 2:
          tit = "单选题";
          break;
        case 3:
          tit = "多选题";
          break;
        case 4:
          tit = "判断题";
          break;
        case 5:
          tit = "主观题";
          break;
      }
      return tit;
    },
    keydownAnswer(event) {
      //快速答案设置禁止输入
      if (
        event.key == "Meta" ||
        event.key == "CapsLock" ||
        event.key == "Shift" ||
        event.key == "Enter" ||
        event.key == "Alt" ||
        event.key == "Backspace" ||
        event.key == "Delete" ||
        event.key == "ArrowUp" ||
        event.key == "ArrowDown" ||
        event.key == "ArrowLeft" ||
        event.key == "v" ||
        event.key == "V" ||
        event.key == "ArrowRight"
      ) {
        return;
      } else {
        event.returnValue = "";
      }
    },
    setAnswer(obj, answer) {
      //多选答案设置
      obj.answerList += answer;
      let str = obj.answerList;
      let str2 = checkAnswer(
        str,
        3,
        obj.list[0].answerOptions,
        obj.list.length
      );
      obj.answerList = str2;
    },
    changAnswer(sub, option) {
      //设置多选答案
      let str = new RegExp(option, "g");
      if (sub.correctAnswer?.includes(option)) {
        sub.correctAnswer = sub.correctAnswer.replace(str, "");
      } else {
        let arrs = (sub.correctAnswer && sub.correctAnswer.split("")) || [];
        arrs.push(option);
        sub.correctAnswer = arrs.sort().join("");
      }
    },
    async saveAnswer() {
      let questionList = [],
        questionList2 = [];
      if (this.editType) {
        questionList = [...this.FormQuestionList];
      } else {
        this.FormQuestionList2.map((item) => {
          item.list.map((items, index) => {
            if (items.questionType == 2 ) {
              items.correctAnswer = item.answerList.split("")[index];
            } else if (items.questionType == 3) {
              items.correctAnswer = item.answerList.split(",")[index];
            }else if (items.questionType == 4) {
              items.correctAnswer = item.answerList[index] == "✓" ? 1 : 2;
            }
            questionList2.push(items);
          });
        });
        questionList = this.FormQuestionList.map((item) => {
          let subQuestions = item.subQuestions.map((items) => {
            items.correctAnswer = questionList2.find((question) => {
              return question.questionIndex == items.questionIndex;
            })?.correctAnswer;
            return items;
          });
          return {
            ...item,
            subQuestions: [...subQuestions],
          };
        });
      }
      console.log(questionList);
      const { data, status, message } = await this.$request.modifyPaper({
        paperId: this.paperId,
        questionList: questionList,
      });
      if (status == 0) {
        this.$emit("saveSuccess");
      } else {
        this.$message.error(message);
      }
    },
    cancel() {
      this.$emit("cancel");
    },
  },
};
</script>

<style lang="scss" scoped>
.el-dialog-wrapper {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: auto;
  margin: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2022;
  .el-dialog-content {
    width: 600px;
    background: #fff;
    border-radius: 10px;
    padding: 16px 20px 20px;
  }
  .title {
    font-size: 18px;
    position: relative;
    margin-bottom: 20px;
    .el-icon-close {
      position: absolute;
      top: 0;
      right: 12px;
      padding: 2px;
      font-size: 16px;
      cursor: pointer;
      &:hover {
        color: #667ffa;
      }
    }
    .fa-exchange {
      color: #999;
      cursor: pointer;
      &:hover {
        color: #667ffa;
      }
    }
  }
}
.footer-box {
  text-align: center;
  padding-top: 20px;
}
.sub-questions {
  width: 100%;
  display: flex;
  &:hover {
    background: #f8f8f8;
  }
  & > div {
    min-height: 40px;
    padding: 5px;
    flex-shrink: 0;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .qs-num {
    width: 80px;
    font-size: 16px;
    color: #333;
    font-weight: 500;
  }
  .qs-options {
    flex: 1;
  }
  .qs-options2 {
    text-align: left;
    justify-content: flex-start;
    padding-left: 20px;
    .answer-s {
      cursor: pointer;
      border-color: #667ffd;
      color: #667ffd;
      margin: 0 15px;
      &.active {
        color: #fff;
      }
    }
  }
  :deep(.el-select) {
    .el-input__inner {
      border-radius: 20px;
      border-color: #667ffd;
      width: 150px;
      height: 32px;
      line-height: 32px;
      background: rgba($color: #667ffd, $alpha: 0.05);
    }
    .el-input__icon {
      line-height: 32px;
    }
  }
}
.dia-tips {
  line-height: 18px;
  padding-bottom: 10px;
}
.set-questions {
  display: flex;
  padding-right: 20px;
  margin-bottom: 20px;
  .qs-num {
    width: 80px;
    padding-top: 6px;
    .txt {
      font-size: 16px;
      line-height: 18px;
      margin-bottom: 6px;
    }
  }
  .qs-options {
    flex: 1;
    .ipt {
      margin-bottom: 5px;
    }
    .answer-box {
      .answer-s {
        cursor: pointer;
        user-select: none;
        &:first-of-type {
          margin-left: 0;
        }
      }
    }
  }
  .delButton {
    border-color: #ff6868;
    background: #ff6868 url("../assets/images/arrow.png") no-repeat center;
    background-size: 19px;
    color: transparent;
  }
  .ac {
    border-color: #ff6868;
    background: #ff6868;
    color: #fff;
  }
}
</style>