<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"></i>
        <!-- 设置答案 -->
        <i class="el-icon-close" @click="cancel"></i>
      </p>
      <div class="dia-question-box">
        <p class="dia-tips">点击批量设置答案按钮，批量设置答案</p>
        <div v-for="(subQuestions, index) in FormQuestionList" :key="index">
          <p
            class="set-ans-btn"
            v-if="
              subQuestions.qusType &&
              subQuestions.subNum &&
              subQuestions.subNum > 4
            "
          >
            <el-button type="primary" @click="setFormAns(index)"
              >批量设置答案</el-button
            >
          </p>
          <div class="sub-questions" :key="index" v-else>
            <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.split(',')"
                  :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.split(',')"
                  :class="subQuestions.correctAnswer == option ? 'active' : ''"
                  :key="option"
                  @click="subQuestions.correctAnswer = option"
                  >{{ option }}</span
                >
              </p>
            </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>
    <el-dialog :close-on-click-modal="false"
      title="批量设置答案"
      :visible.sync="diaSetAns"
      width="400"
      :modal-append-to-body="false"
    >
      <div class="qs-options set-questions">
        <p>{{ setSubPro(formAns.qusType) }}：</p>
        <p class="ipt">
          <el-input
            ref="formAnsIpt"
            v-if="formAns.qusType == 2 || formAns.qusType == 3"
            v-model="formAns.answerList"
            @keydown.native="keydownAnswer($event, formAns.qusType)"
            @input="setAllAnswer($event, formAns.qusType)"
          ></el-input>
          <el-input
            v-if="formAns.qusType == 4"
            v-model="formAns.answerList"
            readonly=""
          ></el-input>
        </p>
        <p class="answer-box">
          <template v-if="formAns.qusType == 4">
            <span
              class="answer-s active"
              @click="
                formAns.answerList.length < formAns.subNum
                  ? (formAns.answerList += '✓')
                  : ''
              "
              >✓</span
            >
            <span
              class="answer-s active"
              @click="
                formAns.answerList.length < formAns.subNum
                  ? (formAns.answerList += '✗')
                  : ''
              "
              >✗</span
            >
          </template>
          <template v-if="formAns.qusType == 3">
            <span
              class="answer-s active"
              v-for="option in formAns.answerOptions.split(',')"
              :key="option"
              @click="setMultiple(formAns, option)"
              >{{ option }}</span
            >
            <span
              class="answer-s active"
              @click="setMultiple(formAns, ',')"
              >,</span
            >
          </template>
          <template v-if="formAns.qusType == 2">
            <span
              class="answer-s active"
              v-for="option in formAns.answerOptions.split(',')"
              :key="option"
              @click="
                formAns.answerList.length < formAns.subNum
                  ? (formAns.answerList += option)
                  : ''
              "
              >{{ option }}</span
            >
          </template>
          <span
            class="answer-s delButton"
            @click="formAns.answerList = formAns.answerList.slice(0, -1)"
            >x</span
          >
          <span class="answer-s ac" @click="formAns.answerList = ''">ac</span>
        </p>
      </div>
      <div class="dialog-footer" slot="footer">
        <el-button @click="saveFormAns">确 定</el-button>
        <el-button @click="diaSetAns = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deepClone, checkAnswer } from "utils";
export default {
  name: "SetAnswer",
  props: {
    diaVisible: false, //修改答案
    paperId: "",
    questionList: Array,
  },
  data() {
    return {
      diaSetAns: false,
      editType: true, //修改答案模式
      FormQuestionList: [],
      FormQuestionList: [],
      formAns: {
        endIndex: 0, //相同题目最后一位题目的questionIndex
        index:0,
        qusType: "", //题目类型
        subNum: 0, //数量
        answerOptions: [], //答案选项
        answerList: "", //答案列表-字符串
      },
    };
  },
  watch: {
    questionList: {
      handler: function (val) {
        const questions = deepClone(val).sort((a, b) => {
          return a.questionIndex - b.questionIndex;
        });
        this.FormQuestionList = deepClone(questions);
        let types = [{}];
        let addndex = 0;
        this.FormQuestionList?.map((sub, index) => {
          if (!!sub.questionType) {
            if (sub.questionType == types[addndex].qusType && sub.questionType != 5) {
              //同类型批量答案+1
              types[addndex].subNum += 1;
              if (
                types[addndex].answerOptions.length < sub.answerOptions.length
              ) {
                types[addndex].answerOptions = sub.answerOptions;
              }
              types[addndex].answerList += this.setAnswer(
                sub.questionType,
                sub.correctAnswer
              );
              if (index == this.questionList.length - 1) {
                //循环最后类型数量大于等于5，保存批量答案
                if (types[addndex].subNum && types[addndex].subNum >= 5) {
                  types[addndex].endIndex = sub.questionIndex;
                  types[addndex].index = index;
                }
              }
            } else {
              if (types[addndex].subNum && types[addndex].subNum >= 5) {
                //不同类型时如果原有类型数量大于等于5，保存批量答案
                types[addndex].endIndex =
                  this.questionList[index - 1].questionIndex;
                types[addndex].index = index - 1;
                addndex += 1;
                types[addndex] = {};
              }
              //不同类型初始化批量答案
              types[addndex].qusType = sub.questionType;
              types[addndex].subNum = 1;
              types[addndex].answerOptions = sub.answerOptions;
              types[addndex].answerList = this.setAnswer(
                sub.questionType,
                sub.correctAnswer
              );
            }
          }
        });
        for (let i = 0; i < types.length; i++) {
          if (types[i].qusType == 3) {
            types[i].answerList = types[i].answerList.slice(0, -1);
          }
          if (types[i].subNum >= 5) {
            item.subQuestions.splice(
              types[i].index + i + 1,
              0,
              deepClone(types[i])
            );
          }
        }
      },
      deep: true,
    },
  },
  methods: {
    setFormAns(indexs) {
      //初始化要修改的答案
      this.formAns = { ...this.FormQuestionList[indexs] };
      let startIndex = (this.formAns.index+1) - this.formAns.subNum;//批量设置大难开始位置
      let answerList = "";
      this.FormQuestionList[index].map((item, subIdx) => {
        if (subIdx >= startIndex) {
          answerList += this.setAnswer(item.questionType, item.correctAnswer);
          if (subIdx != indexs) {
            if (!!item.qusType) {
              answerList = "";
            }
          } else {
            if (item.qusType == 3) {
              answerList = answerList.slice(0, -1);
            }
            this.formAns.answerList = answerList;
          }
        }
      });
      this.diaSetAns = true;
    },
    saveFormAns() {
      //批量修改答案
      let EndIndex;
      let subNum = this.formAns.subNum - 1;
      this.FormQuestionList.some((item, index) => {
        if (this.formAns.endIndex == item.questionIndex) {
          EndIndex = index;
          return;
        }
      });
      for (let i = 0; i <= subNum; i++) {
        let correctAnswer = "";
        if (this.formAns.qusType == 2) {
          correctAnswer = this.formAns.answerList[subNum - i] || "";
        } else if (this.formAns.qusType == 3) {
          correctAnswer = this.formAns.answerList.split(",")[subNum - i] || "";
        } else if (this.formAns.qusType == 4) {
          correctAnswer =
            this.formAns.answerList[subNum - i] == "✓"
              ? 1
              : this.formAns.answerList[subNum - i] == "✗"
              ? 2
              : "";
        }
        this.questionList[EndIndex - i].correctAnswer = correctAnswer;
      }
      this.diaSetAns = false;
    },
    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 = "";
    //   }
    // },
    keydownAnswer(event, type) {
      let answerA = "ABCDEFG";
      let answer_a = "abcdefg";
      answerA = answerA.substring(0, this.formAns.subNum);
      answer_a = answer_a.substring(0, this.formAns.subNum);
      answerA += answer_a;
      answerA = type == 2 ? answerA : answerA + ",";
      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;
      if (!answerA.includes(event.key)) {
        event.returnValue = "";
      }
    },
    setAllAnswer(event, type) {
      let str = this.formAns.answerList;
      let str2 = checkAnswer(
        str,
        type,
        this.formAns.answerOptions.split(",").length,
        this.formAns.subNum
      );
      this.formAns.answerList = str2;
    },
    setAnswer(type, ans) {
      let txt = "";
      if (type == 2) {
        txt = ans;
      } else if (type == 3) {
        txt = ans + ",";
      } else if (type == 4) {
        txt = ans == 1 ? "✓" : ans == 2 ? "✗" : "";
      }
      return txt;
    },
    insertTxtAndSetcursor(answerList, str) {
      let element = this.$refs.formAnsIpt.$el.children[0]; // 获取到指定标签
      let startPos = element.selectionStart; // 获取光标开始的位置
      if (startPos === undefined) {
        // 如果没有光标位置 不操作
        return answerList;
      } else {
        return {
          text:
            answerList.substring(0, startPos) +
            str +
            answerList.substring(startPos), // 将文本插入
          startPos: startPos + str.length,
        };
      }
    },
    setMultiple(obj, answer) {
      //多选答案设置
      let resault = this.insertTxtAndSetcursor(obj.answerList || "", answer);
      obj.answerList = resault.text;
      let str = obj.answerList;
      let str2 = checkAnswer(
        str,
        3,
        obj.answerOptions.split(",").length,
        obj.subNum
      );
      obj.answerList = str2;
      this.$refs.formAnsIpt.$el.children[0].focus();
      this.$refs.formAnsIpt.$el.children[0].selectionStart = resault.startPos;
    },
    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 = [...this.FormQuestionList];
      for (let i = 0; i < questionList.length; i++) {
        if (questionList[i].qusType) {
          questionList.splice(i, 1);
          i--;
        }
      }
      const { data, status, message } = await this.$request.setPeriodAnswer({
        periodId: 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>