<template>
  <view>
    <view class="question_content">
      <view class="question_item">
        <view class="question_title">第&nbsp;{{ currentQuestionIndex + 1 }}&nbsp;题&nbsp;/&nbsp;共&nbsp;{{ question_Info.question_total }}&nbsp;题</view>
        <view class="question_content_text">{{ question_map.question_title }}</view>
        <view class="question_tip"> 请从以下选项中选出正确答案 </view>
        <view class="question_options">
          <view
            v-for="(option, cIndex) in question_map.answer_list"
            :key="cIndex"
            :class="[
              'question_answer',
              { active: question_map.selectAnswer == option.id },
              { error: question_map.checkAnswer && question_map.checkAnswer == option.id && question_map.checkAnswer !== question_map.answer_id },
            ]"
            @click="_selectAnswer(option.id)"
          >
            <view
              :class="[
                'question_index',
                { active: question_map.selectAnswer == option.id },
                { error: question_map.checkAnswer && question_map.checkAnswer == option.id && question_map.checkAnswer !== question_map.answer_id },
              ]"
              >{{ option.value.substring(0, 1) }}</view
            >
            {{ option.value.substring(2) }}
          </view>
        </view>
        <view class="question_result" v-if="question_map.checkAnswer">
          <icon :type="question_map.answer_id == question_map.checkAnswer ? 'success' : 'cancel'" size="24" />
          <view :class="['title', question_map.checkAnswer == question_map.answer_id ? 'green' : 'red']">{{
            question_map.answer_id == question_map.checkAnswer ? "恭喜您，答对啦!" : "很遗憾，答错了"
          }}</view>
          <view class="tip">本题的正确选项为：{{ answer_number[question_map.answer_index] }}</view>
        </view>
      </view>
    </view>
    <view class="bottom_btn" v-if="question_Info.question_list.length !== 0">
      <!-- <view class="answer_info"
        >已答&nbsp;<view style="color: #5045e6">{{ answeredCount }}</view
        >&nbsp;题，共&nbsp;{{ question_Info.question_total }}&nbsp;题</view
      > -->
      <!-- <view class="submit-btn" @click="_handleSubmit">交卷</view> -->
      <view
        :class="[
          'submit-btn',
          {
            disabled: !question_map.selectAnswer,
          },
        ]"
        @click="_handleSubmitAnswer"
        v-if="!question_map.checkAnswer"
      >
        提交
      </view>
      <view v-if="question_map.checkAnswer" style="display: flex; justify-content: space-between; width: 100%">
        <view class="prev_btn" @click="_prevQuestion">上一题</view>
        <view class="next_btn" @click="_nextQuestion">{{ currentQuestionIndex !== question_Info.question_list.length - 1 ? "下一题" : "查看报告" }}</view>
      </view>
    </view>
    <Empty v-if="question_Info.question_list.length == 0" text="----- 本课程还没有配置习题 -----" />
    <uni-popup ref="tipRef" type="center" @change="_changeTip">
      <view class="tip_content">
        <view code>&nbsp;{{ "<" }}&nbsp; &nbsp;{{ ">" }}&nbsp;</view>
        <view>左右滑动切换题目</view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import Empty from "@/components/Empty/Empty.vue";
export default {
  components: { Empty },
  data() {
    return {
      currentQuestionIndex: 0,
      course_id: null,
      question_Info: {},
      question_map: {}, // 初始化 question_map
      answer_number: ["A", "B", "C", "D", "E", "F"],
    };
  },
  onLoad(param) {
    this.course_id = param.id;
    if (!uni.getStorageSync("isShowExamTip")) {
      this.$refs.tipRef.open("center");
    }

    uni.enableAlertBeforeUnload({
      message: "您确定要退出答题吗?",
      success: function (res) {
        console.log("方法注册成功：", res);
      },
      fail: function (errMsg) {
        console.log("方法注册失败：", errMsg);
      },
    });
  },
  onShow() {
    this._getDetail();
  },
  computed: {
    answeredCount() {
      if (!this.question_Info.question_list) return 0;
      return this.question_Info.question_list.filter((item) => item.checkAnswer).length;
    },
  },
  methods: {
    _changeTip() {
      uni.setStorageSync("isShowExamTip", true);
    },
    _getDetail() {
      this.$http
        .request("api/video_exam_question/get_list", {
          course_id: this.course_id,
        })
        .then((re) => {
          if (re.code == "success") {
            re.data.question_list.map((item) => {
              item.answer_index = item.answer_list.findIndex((answer) => answer.is_answer == 1);
              item.answer_id = item.answer_list.find((answer) => answer.is_answer == 1).id;
              item.selectAnswer = null; // 初始化 selectAnswer 属性
            });
            console.log(re.data);
            this.question_Info = re.data;
            this.question_map = re.data.question_list[this.currentQuestionIndex];
          }
        });
    },
    _selectAnswer(id) {
      //已经回答的题目不能再答了
      if (this.question_map.checkAnswer) {
        return;
      }
      // this.question_map.selectAnswer = id;
      this.$set(this.question_map, "selectAnswer", id);
      console.log(this.question_map);
    },
    _handleSubmitAnswer() {
      if (!this.question_map.selectAnswer) {
        return;
      }
      this.question_map.checkAnswer = this.question_map.selectAnswer;
    },
    _handleSubmit() {
      if (this.answeredCount !== this.question_Info.question_total) {
        uni.showModal({
          title: "温馨提示",
          content: "还有未完成的题目，是否交卷",
          confirmText: "继续交卷",
          cancelText: "继续答题",
          success: (res) => {
            if (res.confirm) {
              this._handleIn();
            }
          },
        });
      } else {
        this._handleIn();
      }
    },
    _handleIn() {
      const _this = this;
      const question_list = this.question_Info.question_list.filter((item) => item.checkAnswer);
      const answer_list = question_list.map((item) => {
        return { question_id: item.question_id, answer_id: item.checkAnswer };
      });
      this.$http
        .request(
          "api/video_exam_record/hand_in",
          {
            record_id: this.question_Info.record_id,
            answer_list: JSON.stringify(answer_list),
          },
          "POST"
        )
        .then((re) => {
          if (re.code == "success") {
            uni.redirectTo({
              url: `/pages/video/record?type=exam&record_id=${_this.question_Info.record_id}`,
            });
            // uni.showModal({
            //   title: "完成测评",
            //   content: "恭喜您完成测评，是否查看报告",
            //   confirmText: "查看报告",
            //   cancelText: "返回列表",
            //   success(res) {
            //     if (res.confirm) {
            //       uni.redirectTo({
            //         url: `/pages/video/record?type=exam&record_id=${_this.question_Info.record_id}`,
            //       });
            //     } else {
            //       uni.redirectTo({
            //         url: `/pages/video/index`,
            //       });
            //     }
            //   },
            // });
          }
        });
    },
    _prevQuestion() {
      if (this.currentQuestionIndex === 0) {
        uni.showToast({
          title: "已是第一题啦！",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      this.currentQuestionIndex--;
      this.question_map = this.question_Info.question_list[this.currentQuestionIndex];
    },
    _nextQuestion() {
      try {
        if (this.currentQuestionIndex == this.question_Info.question_list.length - 1) {
          this._handleIn();
          return;
        }
        this.question_Info.question_list[this.currentQuestionIndex] = this.question_map;
        this.currentQuestionIndex++;
        this.question_map = this.question_Info.question_list[this.currentQuestionIndex];
        console.clear();
        console.log(this.currentQuestionIndex, "currentQuestionIndex");
        console.log(this.question_map, "question_map");
        console.log(this.question_Info.question_list, "this.question_Info.question_list");
      } catch (error) {
        console.log(error);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.tip_content {
  font-size: 64rpx;
  font-weight: bold;
  color: #fff;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 20rpx;
}
.question_content {
  height: calc(100vh - 200rpx);
  background-color: #f2f2f2;
  width: 100%;
  box-sizing: border-box;
  padding: 30rpx 20rpx;
  background-color: #f9fbfc;
  .question_item {
    width: 100%;
    padding: 30rpx 20rpx;
    box-sizing: border-box;
    // border: 2rpx solid #ddd;
    border-radius: 8rpx;
    // background-color: #fff;
    .question_title {
      color: #999;
      margin-bottom: 40rpx;
    }
    .question_tip {
      color: #999999;
      margin-bottom: 40rpx;
    }
    .question_content_text {
      font-size: 32rpx;
      margin-bottom: 40rpx;
      font-weight: bold;
    }
    .question_options {
      display: flex;
      flex-direction: column;
      gap: 40rpx;
      width: 100%;

      .question_index {
        border: 2rpx solid #ddd;
        border-radius: 50%;
        width: 50rpx;
        height: 50rpx;
        text-align: center;
        line-height: 50rpx;
        margin-right: 20rpx;
        &.active {
          border-color: #5045e6;
          background-color: #5045e6;
          color: #fff;
        }
        &.error {
          background-color: #ef4444;
          border-color: #ef4444;
        }
      }
      .question_answer {
        height: 80rpx;
        width: 100%;
        border-radius: 20rpx;
        display: flex;
        align-items: center;
        border: 2rpx solid #ddd;
        box-sizing: border-box;
        padding: 20rpx 20rpx;
        &.active {
          color: #5045e6;
          border-color: #5045e6;
        }
        &.error {
          border-color: #ef4444;
          background-color: #fef2f2;
          color: #ef4444;
        }
      }
    }
    .question_result {
      display: flex;
      flex-direction: column;
      gap: 20rpx;
      width: 100%;
      justify-content: center;
      align-items: center;
      border: 2rpx solid #ddd;
      margin-top: 40rpx;
      padding: 36rpx;
      box-sizing: border-box;
      border-radius: 20rpx;
      .red {
        color: red;
      }
      .green {
        color: green;
      }
    }
  }
}
.bottom_btn {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 200rpx;
  border-top: 4rpx solid #ddd;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 40rpx;
  box-sizing: border-box;
  .prev_btn {
    background-color: #fff;
    color: #333;
    font-size: 28rpx;
    width: 45%;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 8rpx;
    box-shadow: 2rpx 2rpx 8rpx rgba(0, 0, 0, 0.1);
    text-align: center;
  }
  .next_btn {
    background-color: #5045e6;
    color: #fff;
    font-size: 28rpx;
    width: 45%;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 8rpx;
    box-shadow: 2rpx 2rpx 8rpx rgba(0, 0, 0, 0.1);
    text-align: center;
  }
  .answer_info {
    display: flex;
    align-items: baseline;
  }
  .submit-btn {
    background-color: #5045e6;
    color: #fff;
    font-size: 28rpx;
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 8rpx;
    box-shadow: 2rpx 2rpx 8rpx rgba(0, 0, 0, 0.1);
    text-align: center;
    &.disabled {
      background-color: #ccc;
      color: #999;
      cursor: not-allowed;
    }
  }
}
</style>
