<template>
  <el-dialog
    class="answerLesson"
    title="开始答题"
    :visible.sync="visible"
    width="57.5%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="dialogCancel"
    @closed="closeFinished"
    destroy-on-close
  >
    <div ref="myBody" class="body" v-loading="loading">
      <div class="text">
        <div class="float">{{courseName}}</div>
      </div>
      <transition name="fade" mode="out-in">
        <div :key="goodJobShow">
          <template v-if="!goodJobShow">
            <transition name="fade" mode="out-in">
              <div class="question-wrapper" v-if="visible" :key="nowQuestion">
                <div v-for="(item, index) in list" :key="item.id">
                  <template v-if="item.topicType === 1 || item.topicType === 3">
                    <Question
                      v-if="index === nowQuestion"
                      :questionObj="item"
                      :index="index"
                      :nowQuestion="nowQuestion"
                      :selectLetter="selectLetter"
                      @changeLetter="changeLetter"
                    />
                  </template>
                  <template v-else>
                    <QuestionChoice
                      v-if="index === nowQuestion"
                      :questionObj="item"
                      :index="index"
                      :nowQuestion="nowQuestion"
                      :selectLetter="selectLetter"
                      @changeLetter="changeLetter"
                    />
                  </template>
                </div>
              </div>
            </transition>

            <div class="select flex">
              <div class="select-item flex">
                <div
                  class="item"
                  :class="{
                    active:
                      answerArr.findIndex(
                        (item) => item.questionNum === index + 1
                      ) >= 0 && activeBool(index),
                    activered:
                      answerArr.findIndex(
                        (item) => item.questionNum === index + 1
                      ) >= 0 && !activeBool(index),
                    now: index === nowQuestion,
                  }"
                  v-for="(item, index) in list"
                  :key="item.id + 'a' + index"
                  @click="questionNumClick(index)"
                >
                  {{ index + 1 }}
                </div>
                <div @click="nextBtnClick" class="btn">下一题</div>
              </div>
            </div>
          </template>

          <template v-else>
            <div :style="{ height: startHeight }">
              <GoodJob :goodJobData="goodJobData" />
            </div>
          </template>
        </div>
      </transition>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="closeFinished" v-if="goodJobShow"
        >重新考试</el-button
      >
      <el-button type="primary" @click="dialogSubmitForm" v-else
        >交卷</el-button
      >
      <el-button @click="dialogCancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import Question from "./Question";
import QuestionChoice from "./QuestionChoice";
import GoodJob from "./GoodJob.vue";
import {
  userQuestionList,
  setAnswer,
} from "@/api/train/lessonsProgram";
export default {
  name: "AnswerLesson",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    userCourseId: {
      type: [Number, String],
    },
    courseName:{
      type: [String,String]
    },
    courseId: {
      type: [Number, String],
    },
  },
  components: {
    Question,
    QuestionChoice,
    GoodJob,
  },

  data() {
    return {
      nowQuestion: 0,
      startHeight: "0px",
      goodJobShow: false,
      goodJobData: {},
      loading: false,
      list: [
        {
          id: 19,
          text: "j9",
          question: ["adsf", "dfgsdfg", "adsfadsf", "dfasdfadsf"],
        },
      ],
      answerArr: [],
      // 题目是否被答过，如果答过，就把值传回去，如果没有答过，就是空
      selectLetter: [],
    };
  },

  // watch: {
  //   visible(newValue) {
  //     if (newValue) {
  //       this.$nextTick(() => {
  //         this.saveBody();
  //       });
  //     }
  //   },
  // },
  created() {
    userQuestionList({ courseId: this.courseId }).then((res) => {
      console.log(res.data);
      this.list = res.data.map((item) => {
        return {
          id: item.topicId,
          text: item.topicTitle,
          topicType: item.topicType,
          question: JSON.parse(item.topicOption).map((item) => item.value),
        };
      });
    });
  },
  methods: {
    saveBody() {
      this.startHeight = this.$refs.myBody.offsetHeight - 55 + "px";
    },
    dialogSubmitForm() {
      // this.answerClear();
      // this.$emit("update:visible", false);
      this.saveBody();
      const json = JSON.stringify(this.answerArr.map((item) => item.answer));
      const answers = json.slice(1,json.length-1);
      console.log(answers);
      this.loading = true;
      setAnswer({
        userCourseId: this.userCourseId,
        answers,
      })
        .then((res) => {
          if (res.code == 200) {
            console.log(res.data)
            this.goodJobData = res.data;
            this.goodJobShow = true;
          }
        })
        .finally(() => {
          this.loading = false;
          // 是否作对
          this.$emit("jj", this.goodJobData);
        });
    },
    dialogCancel() {
      this.$emit("update:visible", false);
    },
    // 关闭之后
    closeFinished() {
      this.answerClear();
      this.goodJobShow = false;
    },
    answerClear() {
      this.answerArr = [];
      this.nowQuestion = 0;
    },
    // 点题目时
    questionNumClick(index) {
      // 是否是回答过的,数组中存在它，那它就是回答过的
      const bool =
        this.answerArr.findIndex((item) => item.questionNum === index + 1) >= 0;
      // 或者下一题与当前题目是紧挨着的并且当前题目是答完的，相差为1就算是紧挨着的
      const nowQuestionAnswerBool = this.nextQuestion(index);
      if (bool || nowQuestionAnswerBool) {
        this.nowQuestion = index;
      }
      // 赋值，如果答过的，就传回去，如果没答过，就是空 变成字符串是因为0位false
      this.selectLetter = this.answerArr[this.nowQuestion]?.answer || [];
    },
    nextBtnClick() {
      // 到头了，打完了
      if (this.nowQuestion + 1 == this.list.length) return;
      this.questionNumClick(this.nowQuestion + 1);
    },
    // 紧挨着且当前题目是打完的
    nextQuestion(index) {
      // 下一题相差1
      // const nextIndexBool = index - this.nowQuestion == 1;
      // 答案数组的长度，就是档当前达到了第几题，长度-1是因为题目是从0开始记录
      const nextIndexBool = index - (this.answerArr.length - 1) == 1;
      // 当前题已经回答过
      const nowQuestionAnswerBool =
        this.answerArr.findIndex(
          (item) => item.questionNum === this.nowQuestion + 1
        ) >= 0;
      return nextIndexBool && nowQuestionAnswerBool;
    },
    changeLetter(letter) {
      console.log(letter);
      const obj = {};
      obj.questionNum = this.nowQuestion + 1;
      obj.answer = letter;
      // 数组中是否存在这个题目
      const index = this.answerArr.findIndex(
        (item) => item.questionNum === this.nowQuestion + 1
      );
      if (index < 0) {
        // 如果不存在
        // 推入
        this.answerArr.push(obj);
      } else {
        // 如果存在
        // 替换
        this.answerArr.splice(index, 1, obj);
      }
      console.log(this.answerArr);
    },
    activeBool(index) {
      return this.answerArr[index]?.answer.length > 0;
    },
  },
};
</script>
<style lang="scss" scoped>
.body {
  width: 100%;
  height: 100%;
  padding-right: 50px;
  padding-left: 60px;
  .question-wrapper {
  }
  .text {
    margin-bottom: 27px;
    .float {
      padding-right: 7px;
      width: 411px;
      height: 28px;
      background: #1d84ff;
      line-height: 28px;
      color: #ffffff;
      font-size: 14px;
      text-align: right;
      float: right;
    }
    &:after {
      content: "";
      display: block;
      clear: both;
    }
  }
  .select {
    .select-item {
      padding-top: 20px;
      flex-wrap: wrap;
      > div {
        margin-bottom: 10px;
      }
      .item {
        width: 28px;
        height: 28px;
        border: 1px solid #bbbbbb;
        line-height: 28px;
        font-size: 14px;
        text-align: center;
        margin-right: 18px;
        box-sizing: border-box;
        cursor: pointer;
        &.active {
          background: #afe8ab87;
          border:none;
        }
        &.activered {
          background: #b9112633;
          border:none;

        }
        &.now {
          background: #a3d3ff;
          border: none;
        }
      }
      .btn {
        width: 84px;
        height: 28px;
        background: #e8f4ff;
        border: 1px solid #a3d3ff;
        color: #1d84ff;
        text-align: center;
        line-height: 28px;
        font-size: 14px;
        cursor: pointer;
        &:hover {
          background: rgba(29, 132, 255, 0.5);
          color: #ffffff;
        }
      }
    }
  }
}
</style>
