<template>
  <view class="box" @touchstart="touchStart" @touchend="touchEnd">
    <nav-bar :title="navTitle"> </nav-bar>
    <view style="text-align: center">
      <van-count-down :time="time"></van-count-down>
    </view>
    <view class="divider"></view>
    <m-do-topic
      :hiddenFunction="true"
      :trueNum.sync="trueNum"
      :falseNum.sync="falseNum"
      :query="query"
      :problemListIndex="problemListIndex"
    ></m-do-topic>
    <!-- #ifdef MP-WEIXIN -->
    <van-tabbar>
      <van-tabbar-item @click="goBeforeTopics"
        ><van-icon
          slot="icon"
          custom-style="transform: rotate(90deg);"
          custom-class="last-subject"
          name="down"
          size="18px"
        />上一题
      </van-tabbar-item>
      <van-tabbar-item
        ><van-icon slot="icon" size="18px" name="description" />{{
          problemListIndex + 1
        }}/{{ problemListTotal }}
      </van-tabbar-item>
      <van-tabbar-item @click="submitExam"
        ><van-icon slot="icon" size="18px" name="records" />交卷
      </van-tabbar-item>
      <van-tabbar-item @click="goNextTopics"
        ><van-icon
          slot="icon"
          custom-style="transform: rotate(-90deg);"
          custom-class="last-subject"
          name="down"
          size="18px"
        />下一题
      </van-tabbar-item>
    </van-tabbar>
    <!-- #endif -->
    <!-- #ifdef MP-TOUTIAO -->
    <tabbar height="35px">
      <view @click="goBeforeTopics" class="flex-all-center h-full">
        <van-icon
          slot="icon"
          custom-style="transform: rotate(90deg);"
          custom-class="last-subject"
          name="down"
          size="18px"
        /><text> 上一题 </text>
      </view>

      <view class="flex-all-center h-full">
        <van-icon size="18px" name="description" />{{ problemListIndex + 1 }}/{{
          problemListTotal
        }}
      </view>
      <view @click="submitExam" class="flex-all-center h-full">
        <van-icon slot="icon" size="18px" name="records" />交卷
      </view>

      <view @click="goNextTopics" class="flex-all-center h-full">
        下一题
        <van-icon
          custom-style="transform: rotate(-90deg);"
          custom-class="last-subject"
          name="down"
          size="18px"
        />
      </view>
    </tabbar>
    <!-- #endif -->
  </view>
</template>

<script>
import navBar from "./components/navBar.vue";
import api from "@/api/index";
import utils from "@/utils/index";
import tabbar from "./components/tabbar.vue";
import mRadio from "@/components/m-radio/m-radio.vue";
import mRadioGroup from "@/components/m-radio-group/m-radio-group.vue";
import mCheckbox from "@/components/m-checkbox/m-checkbox.vue";
import mCheckboxGroup from "@/components/m-checkbox-group/m-checkbox-group.vue";
export default {
  data() {
    return {
      query: {
        cert: "",
        vehicle: "",
        subject: "",
        title: "",
      },
      gsMap: {
        xc: "小车",
        hc: "货车",
        mtc: "摩托车",
        kc: "客车",
      },
      examTimer: 0,
      examTimeUse: 0,
      time: 45 * 60 * 1000,
      problemListTotal: 1,
      problemList: [
        {
          answer: "×",
          answerkeyword: "",
          answermp3:
            "https://t1-1305573081.file.myqcloud.com/kt/answer_mp3/answer1389.mp3",
          classIssue: "54",
          classIssueName: "车内开关/装置",
          classSort: 16,
          createTime: "2022-04-21 13:33:46",
          excellIssue: "23",
          excellIssueName: "必学题三",
          excellSort: 4,
          explainGif:
            "https://t1-1305573081.file.myqcloud.com/kt/explain_gif/explain1389.gif",
          explainJq:
            "看图答题：红色圆圈套在杆子中间.答对；不在中间或没有圆圈的.答错。",
          explainJs:
            "图中所示为左右转向灯开关转向灯操作：上提是右转向灯亮起，下压是左转向灯。",
          explainMp3:
            "https://t1-1305573081.file.myqcloud.com/kt/explain_mp3/explain1389.mp3",
          explainjsmp3:
            "https://t1-1305573081.file.myqcloud.com/kt/explain_js_mp3/explainJS1389.mp3",
          id: 831,
          idKt: 1389,
          idYdt: 950,
          image:
            "https://t1-1305573081.file.myqcloud.com/kt/image/image1389.png",
          imageYdt:
            "https://t1-1305573081.file.myqcloud.com/kt/image_ydt/5eb4d75agw1e291vmniovj.jpg",
          issue: "将转向灯开关向上提，左转向灯亮。",
          issuemp3:
            "https://t1-1305573081.file.myqcloud.com/kt/issue_mp3/issue1389.mp3",
          liceBus: "1",
          liceCar: "1",
          liceMoto: null,
          liceTruck: "1",
          number: 831,
          opts: "√-×",
          optsArr: ["√", "×"],
          placeIssue: null,
          placeIssueName: null,
          placeSort: null,
          questionType: 1,
          sequeIssue: "7",
          sequeIssueName: "机械仪表",
          sequeSort: 25,
          skillkeyword: "没有圆圈-答错",
          subject: 1,
          titlekeyword: "",
          updateTime: "2022-04-22 13:43:07",
          userAnswer: [],
        },
      ],
      touchx: 0,
      touchy: 0,
      problemListIndex: 0,
    };
  },
  filters: {
    questionType: function (value) {
      let question = "";
      switch (value) {
        case 1:
        case "1":
          question = "判断题";
          break;
        case 2:
        case "2":
          question = "单选题";
          break;
        case 3:
        case "3":
          question = "多选题";
          break;
      }
      return question;
    },
  },
  methods: {
    confirmMult() {
      this.$set(this.problemList[this.problemListIndex], "isCompleted", true);
      if (
        JSON.stringify(
          this.problemList[this.problemListIndex].answer.split("-").sort()
        ) ===
        JSON.stringify(
          this.problemList[this.problemListIndex].userAnswer.sort()
        )
      ) {
        this.trueNum++;
      } else {
        this.falseNum++;
        api.exam.studentQuestionWrong({
          questionId: this.problemList[this.problemListIndex].id,
          carType: this.gsMap[this.query.gs],
          km: this.query.subject === "4" ? "科目四" : "科目一",
        });
      }
    },
    touchStart(e) {
      var that = this;

      (this.touchx = e.changedTouches[0].clientX),
        (this.touchy = e.changedTouches[0].clientY);
    },
    touchEnd(e) {
      console.log(e);
      var that = this;
      let x = e.changedTouches[0].clientX;
      let y = e.changedTouches[0].clientY;
      let turn = "";
      if (x - that.touchx > 50 && Math.abs(y - that.touchy) < 50) {
        //右滑
        turn = "right";
        this.problemListIndex <= 0
          ? uni.showToast({
              title: "到底了",
              icon: "none",
            })
          : this.problemListIndex--;
      } else if (x - that.touchx < -50 && Math.abs(y - that.touchy) < 50) {
        //左滑
        turn = "left";
        this.problemListIndex >= this.problemList.length - 1
          ? uni.showToast({
              title: "到底了",
              icon: "none",
            })
          : this.problemListIndex++;
      }
      if (y - that.touchy > 50 && Math.abs(x - that.touchx) < 50) {
        //下滑
        turn = "down";
      } else if (y - that.touchy < -50 && Math.abs(x - that.touchx) < 50) {
        //上滑
        turn = "up";
      }
      //根据方向进行操作
      if (turn == "down") {
        //下滑触发操作
      }
      console.log(turn);
    },
    submitExam(e) {
      let score = 0;
      let query = this.query;
      let that = this;
      let scorePerQuestion = 0;
      query.subject === "4" ? (scorePerQuestion = 2) : (scorePerQuestion = 1);
      score = this.trueNum*scorePerQuestion
      uni.showModal({
        title: "是否交卷",
        content: "交卷后不可再修改了",
        success(res) {
          if (res.confirm) {
            let useTime = "";
            let useTimer = new Date(that.examTimeUse);
            clearInterval(that.examTimer);
            useTime = `${useTimer.getMinutes()}:${useTimer.getSeconds()}`;
            uni.navigateTo({
              url:
                "/otherPages/mockExamEnd/index?" +
                utils.mapToUrlQuery({
                  score,
                  useTime,
                  ...that.query,
                }),
            });
          }
        },
        fail() {},
      });
    },
    goBeforeTopics() {
      if (this.problemListIndex <= 0) {
        uni.showToast({
          title: "到底了",
          icon: "none",
        });
        return;
      }
      this.problemListIndex = this.problemListIndex - 1;
    },
    goNextTopics() {
      if (this.problemListIndex >= this.problemList.length - 1) {
        uni.showToast({
          title: "到底了",
          icon: "none",
        });
        return;
      }
      this.problemListIndex = this.problemListIndex + 1;
    },
    readQuestion(e) {
      let globalAudio = utils.wxUtils.getGlobAudio();
      if (globalAudio) {
        globalAudio.src = e;
        globalAudio.stop();
        globalAudio.play();
      }
    },
    changeRadioGroup(e) {
      this.$set(
        this.problemList[this.problemListIndex],
        "userAnswer",
        e.detail
      );
      //错题
      if (e.detail !== this.problemList[this.problemListIndex].answer) {
        api.exam.studentQuestionWrong({
          questionId: this.problemList[this.problemListIndex].id,
          carType: this.gsMap[this.query.gs],
          km: this.query.subject === "4" ? "科目四" : "科目一",
        });
      }

      this.problemList[this.problemListIndex].optsArr.forEach((item, index) => {
        if (e.detail === item.value) {
          item.selected = true;
          this.$set(
            this.problemList[this.problemListIndex].optsArr[index],
            "selected",
            true
          );
        } else {
          item.selected = false;
          this.$set(
            this.problemList[this.problemListIndex].optsArr[index],
            "selected",
            false
          );
        }
      });
      this.$set(this.problemList[this.problemListIndex], "isCompleted", true);
      // this.problemList[this.problemListIndex].optsArr.forEach((item) => {
      //   if (e.detail.value === item.value) {
      //     item.selected = true;
      //   } else {
      //     item.selected = false;
      //   }
      // });
    },
    changeCheckboxGroup(e) {
      this.$set(
        this.problemList[this.problemListIndex],
        "userAnswer",
        e.detail
      );

      this.problemList[this.problemListIndex].optsArr.forEach((item, index) => {
        if (e.detail.includes(item.value)) {
          item.selected = true;
          this.$set(
            this.problemList[this.problemListIndex].optsArr[index],
            "selected",
            true
          );
        } else {
          item.selected = false;
          this.$set(
            this.problemList[this.problemListIndex].optsArr[index],
            "selected",
            false
          );
        }
      });
    },
    changeGroup(e) {
      console.log(e);
      this.$set(
        this.problemList[this.problemListIndex],
        "userAnswer",
        e.detail
      );
    },
    changeCheckbox(e) {
      console.log(e);
    },
    numberToLetter(index) {
      index = Number(index);
      return String.fromCharCode(index + 65);
    },
  },
  onLoad(query) {
    let that = this;
    this.query = query;
    api.open
      .questionInfoSelectTestK14QuestionInfoList({
        ...this.query,
      })
      .then((res) => {
        res.rows.forEach((element) => {
          element.optsArr = [];
          element.opts.split("-").forEach((item, index) => {
            if (element.questionType == 3) {
              element.optsArr.push({
                selected: false,
                value: item,
                index: index,
                isAnswer: element.answer.split("-").includes(item),
              });
            } else {
              element.optsArr.push({
                selected: false,
                value: item,
                index: index,
                isAnswer: item === element.answer,
              });
            }
          });
          element.isCompleted = false;
          element.userAnswer = [];
        });
        that.problemListTotal = res.total;
        that.problemList = res.rows;
      });
    this.examTimer = setInterval(() => {
      this.examTimeUse = this.examTimeUse + 1000;
      if (this.examTimeUse > this.time) {
        this.submitExam();
        clearInterval(this.examTimer);
      }
    }, 1000);
  },
  computed: {
    //liceCar=1&liceTruck=&liceBus=&liceMoto=&name=科目一&cert=C1/C2/C3&vehicle=轿车&subject=1&title=顺序练习&sort=3
    navTitle() {
      let subjectName = this.query.subject == 1 ? "科目一" : "科目四";
      return `(${this.query.cert})/${subjectName}/${this.query.title}`;
    },
  },
  onUnload() {
    clearInterval(this.examTimer);
  },

  components: {
    navBar,
    tabbar,
    mRadio,
    mRadioGroup,
    mCheckbox,
    mCheckboxGroup,
  },
};
</script>

<style lang="scss" scoped>
.flex-all-center {
  display: flex;
  align-content: center;
  align-items: center;
}
.divider {
  width: 100%;
  height: 24rpx;
  background-color: #f2f3f5;
}

.box {
  width: 100%;
  height: 100vh;
  background: #fff;
  .last-subject {
    transform: rotate(90deg);
  }
  .function-list {
    width: 100%;
    font-size: 13px;
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
    padding: 15px;
    box-sizing: border-box;
    .function-item {
      margin-bottom: 20px;
      width: 30%;
      display: flex;
      flex-direction: column;
      align-items: center;
      font-size: 13px;
      font-weight: 400;
      color: #8a9099;
      span {
        margin-top: 5px;
      }
    }
  }
  .problem-box {
    padding: 15rpx;
    background: #fff;
    /deep/ .van-checkbox {
      padding-bottom: 15rpx;
    }
    /deep/ .van-radio {
      padding-bottom: 15rpx;
    }
    .problem-issue {
      font-size: 42rpx;
    }
    .problem-select {
      display: flex;
      align-content: center;
      align-items: center;
      margin-top: 15rpx;
      padding-left: 30rpx;
    }
    .problem-type {
      padding-left: 10rpx;
      padding-right: 10rpx;
      padding-top: 4rpx;
      padding-bottom: 4rpx;
      font-size: 24rpx;
      border-radius: 16rpx 16rpx 0 16rpx;
      background: #498ef5;
      margin-right: 10rpx;
      color: #fff;
      font-size: 32rpx;
    }
    .problem-ops {
      margin-top: 30rpx;
      padding-left: 30rpx;
      .problem-checkbox {
        height: 100rpx;
      }
    }
    .problem-op {
      width: 75rpx;
      height: 75rpx;
      line-height: 75rpx;
      border-radius: 50%;
      text-align: center;
      overflow: hidden;
      background: #fff;
      box-shadow: 0px 4rpx 12rpx rgba(0, 0, 0, 0.16);
    }
    .problem-op_green {
      width: 75rpx;
      height: 75rpx;
      line-height: 75rpx;
      border-radius: 50%;
      text-align: center;
      overflow: hidden;
      background: #01c18d;

      box-shadow: 0px 4rpx 12rpx rgba(0, 0, 0, 0.16);
    }
    .problem-op_selected {
      background: #498ef5;
    }
    .problem-img {
      width: 100%;
      margin-top: 20rpx;
      display: flex;
      justify-content: center;
      image {
        margin: 0 auto;
      }
    }
  }
}
</style>