<template>
  <el-dialog
    class="answerLesson"
    title="开始答题"
    :visible.sync="visible"
    width="87.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">访客和供应商培训管理</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">
                  <!-- <Question
                    style="width: 89%"
                    v-if="index === nowQuestion"
                    :questionObj="item"
                    :index="index"
                    :nowQuestion="nowQuestion"
                    :selectLetter="selectLetter"
                    @changeLetter="changeLetter"
                  /> -->
                  <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,
                    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="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 "../Trainingmaterials/components/Question";
import QuestionChoice from "../Trainingmaterials/components/QuestionChoice";
import GoodJob from "./components/GoodJob.vue";
import {
  userQuestionList,
  setAnswer,
} from "@/api/educationPlanExam/lessonsProgram";
import { listTopic, setEsult } from "@/api/contractTrain/contractTrainTopic";
export default {
  name: "AnswerLesson",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    userCourseId: {
      type: [Number, String],
    },
    courseId: {
      type: [Number, String],
    },
  },
  from: {
    answers: {},
  },
  components: {
    Question,
    QuestionChoice,
    GoodJob,
  },
  data() {
    return {
      nowQuestion: 0,
      startHeight: "0px",
      goodJobShow: false,
      goodJobData: {},
      loading: false,
      from: {},
      list: [
        {
          id: 19,
          text: "j9",
          question: ["adsf", "dfgsdfg", "adsfadsf", "dfasdfadsf"],
        },
      ],
      answerArr: [],
      // 题目是否被答过,如果答过,就把值传回去,如果没有答过,就是空
      selectLetter: [],
    };
  },
  // watch: {
  //   visible(newValue) {
  //     if (newValue) {
  //       this.$nextTick(() => {
  //         this.saveBody();
  //       });
  //     }
  //   },
  // },
  created() {
    listTopic().then((res) => {
      console.log(res);
      this.list = res.rows.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() {
      // console.log(JSON.parse(this.$route.query.params));
      // this.answerClear();
      // this.$emit("update:visible", false);
      this.saveBody();
      // const answers = this.answerArr.map((item) => item.answer).join(",");

      const json = JSON.stringify(this.answerArr.map((item) => item.answer));
      const answers = json.slice(1, json.length - 1);

      this.form = JSON.parse(this.$route.query.params);
      // this.form={
      //   beyondUnit:'1111',
      //   name:'zzz',
      //   sex:1,
      //   phoneNum:13012341234
      // }
      this.loading = true;
      this.form.answers = answers;
      this.loading = true;
      setEsult(this.form)
        .then((res) => {
          if (res.code == 200) {
            this.goodJobData = res.data;
            this.goodJobShow = true;
          }
        })
        .finally(() => {
          this.loading = false;
          // 是否作对
          this.$emit("jj", this.goodJobData);
        });
    },
    dialogCancel() {
      this.$emit("update:visible", false);
    },
    // 关闭之后
    closeFinished() {
      const routeData = this.$router.resolve({
        path: "/enterInformation", //跳转目标窗口的地址
        query: {},
      });
      window.open(routeData.href, "_search");
      // 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);
      console.log(this.$route.query); // 输出为:{params:"message"}
      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);
    },
  },
};
</script>
<style lang="scss" scoped>
.body {
  width: 100%;
  height: 100%;
  padding-right: 40px;
  padding-left: 20px;
  .question-wrapper {
  }
  .text {
    margin-bottom: 16px;
    .float {
      padding-right: 70%;
      width: 106%;
      height: 28px;
      background: #1d84ff;
      line-height: 28px;
      color: #ffffff;
      font-size: 10px;
      text-align: right;
      float: right;
    }
    &:after {
      content: "";
      display: block;
      clear: both;
    }
  }
  .select {
    .select-item {
      padding-top: 30px;
      flex-wrap: wrap;
      > div {
        margin-bottom: 10px;
      }
      .item {
        width: 38px;
        height: 28px;
        border: 1px solid #bbbbbb;
        line-height: 28px;
        font-size: 14px;
        text-align: center;
        margin-right: 18px;
        cursor: pointer;
        &.active {
          background: #e9e9e9;
        }
        &.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>