<template>
  <view class="content">
    <view class="top">
      <image src="/static/images/study/bgimg1.png" />
      <view class="suject">
        <text class="line-2">考试科目：{{ info.examname }}</text>
      </view>
      <view class="questions">
        <text>当前试题{{ current + 1 }}/{{ options.length }}</text>
      </view>
      <view class="time">
        <text>考试剩余时间：</text>
        <u-count-down
            :time="info.answersheettime * 60 * 1000"
            format="HH 时 mm 分 ss 秒"
            @finish="fnCountDownFinish"
        />
      </view>
    </view>

    <view class="topic">
      <view class="title">
        <text>
          <text class="tag_title">
            {{ handleCalcQuestType(options[current].questiontype) }}
          </text>
          {{ current + 1 }}.{{ options[current].questiondry }}
        </text>
      </view>
      <view v-show="options[current].questiontype === '1'" class="options">
        <view class="item" :class="{ 'active': options[current].checked === 'A' }" @click="fnChooseTopic('radio', 'A')">
          <text class="option">A</text>
          <text class="text">{{ options[current].optiona }}</text>
        </view>
        <view class="item" :class="{ 'active': options[current].checked === 'B' }" @click="fnChooseTopic('radio', 'B')">
          <text class="option">B</text>
          <text class="text">{{ options[current].optionb }}</text>
        </view>
        <view class="item" :class="{ 'active': options[current].checked === 'C' }" @click="fnChooseTopic('radio', 'C')">
          <text class="option">C</text>
          <text class="text">{{ options[current].optionc }}</text>
        </view>
        <view class="item" :class="{ 'active': options[current].checked === 'D' }" @click="fnChooseTopic('radio', 'D')">
          <text class="option">D</text>
          <text class="text">{{ options[current].optiond }}</text>
        </view>
      </view>
      <view v-show="options[current].questiontype === '2'" class="options">
        <view
            class="item"
            :class="{
						'active': options[current].checked && options[current].checked.indexOf('A') !== -1
					}"
            @click="fnChooseTopic('multiple', 'A')"
        >
          <text class="option">A</text>
          <text class="text">{{ options[current].optiona }}</text>
        </view>
        <view
            class="item"
            :class="{
						'active': options[current].checked && options[current].checked.indexOf('B') !== -1
					}"
            @click="fnChooseTopic('multiple', 'B')"
        >
          <text class="option">B</text>
          <text class="text">{{ options[current].optionb }}</text>
        </view>
        <view
            class="item"
            :class="{
						'active': options[current].checked && options[current].checked.indexOf('C') !== -1
					}"
            @click="fnChooseTopic('multiple', 'C')"
        >
          <text class="option">C</text>
          <text class="text">{{ options[current].optionc }}</text>
        </view>
        <view
            class="item"
            :class="{
						'active': options[current].checked && options[current].checked.indexOf('D') !== -1
					}"
            @click="fnChooseTopic('multiple', 'D')"
        >
          <text class="option">D</text>
          <text class="text">{{ options[current].optiond }}</text>
        </view>
      </view>
      <view v-show="options[current].questiontype === '3'" class="options">
        <view class="item" :class="{ 'active': options[current].checked === 'A' }" @click="fnChooseTopic('judge', 'A')">
          <text class="option">{{ options[current].optiona }}</text>
          <text class="text"></text>
        </view>
        <view class="item" :class="{ 'active': options[current].checked === 'B' }" @click="fnChooseTopic('judge', 'B')">
          <text class="option">{{ options[current].optionb }}</text>
          <text class="text"></text>
        </view>
      </view>
      <view v-show="options[current].questiontype === '4'" class="options">
        <view class="item">
          <u-textarea v-model="options[current].checked" auto-height count/>
        </view>
      </view>
    </view>
    <view class="footer">
      <u-button v-show="current !== 0" :style="{ width: '45%' }" text="上一题" @click="fnPreviousQuestion"/>
      <u-button v-show="current !== options.length - 1" type="primary"
                :style="{ width: current === 0 ? '100%' : '45%' }" text="下一题" @click="fnNextQuestion"/>
      <u-button v-show="current === options.length - 1" type="primary" :style="{ width: '45%' }" text="交卷"
                @click="fnHandInThePaper"/>
    </view>

    <u-toast ref="uToast"/>
  </view>
</template>

<script>
import {
  getExamExercises,
  // getStrengthenExam,
  setTestPaperSubmission,
} from '@/api';

export default {
  data() {
    return {
      routeQuery: {},
      entrySite: '',
      info: {},
      options: [{}],
      current: 0,
      questionTypeMap: {
        1: '单选',
        2: '多选',
        3: '判断',
        4: '填空'
      },
      studentId:''
    }
  },
  onLoad(query) {
    this.routeQuery = query
    // this.STAGEEXAMPAPER_ID = query.STAGEEXAMPAPER_ID;
    // this.entrySite = query.entrySite;
    this.fnGetData()
  },
  onBackPress(event) {
    if (event.from === 'backbutton') {
      uni.$u.toast('考试过程中不允许退出')
      return true
    }
    return false
  },
  methods: {
    async fnGetData() {
      const {stageexampaperinputId, classId, } = this.routeQuery
      const resData = await getExamExercises({
        stageexampaperinputId: stageexampaperinputId,
        classId: classId,
      })
      this.info = resData.info
      this.options = resData.inputQue
      this.studentId = resData.student.studentId
      if (resData.numberofexams > 0) {
        uni.showModal({
          title: "温馨提示",
          content: `您还可以考试${resData.numberofexams}次！`,
          showCancel: false,
        });
      }
    },
    fnChooseTopic(type, checked) {
      if (!this.options[this.current].checked) {
        this.$set(this.options[this.current], 'checked', '')
      }
      if (type === 'judge' || type === 'radio') {
        if (this.options[this.current].checked === checked) {
          this.options[this.current].checked = ''
        } else {
          this.options[this.current].checked = checked
        }
      }
      if (type === 'multiple') {
        if (this.options[this.current].checked) {
          const checkedArr = this.options[this.current].checked.split(',')
          if (checkedArr.indexOf(checked) !== -1) {
            checkedArr.splice(checkedArr.indexOf(checked), 1)
            this.options[this.current].checked = checkedArr.join(',')
          } else {
            checkedArr.push(checked)
            checkedArr.sort()
            this.options[this.current].checked = checkedArr.join(',')
          }
        } else {
          this.options[this.current].checked = checked
        }
      }
    },
    handleCalcQuestType(type) {
      return `(${this.questionTypeMap[type]})`
    },
    fnIsFinish() {
      if (!this.options[this.current].checked) {
        uni.showModal({
          title: '温馨提示',
          content: '请对本题进行作答。',
          showCancel: false
        })
        return false
      }
      return true
    },
    /**
     * 下一题按钮点击事件
     */
    fnNextQuestion() {
      if (!this.fnIsFinish()) return
      this.current++
    },
    /**
     * 上一题按钮点击事件
     */
    fnPreviousQuestion() {
      this.current--
    },
    /**
     * 交卷按钮点击事件
     */
    fnHandInThePaper() {
      if (!this.fnIsFinish()) return
      uni.showModal({
        title: '温馨提示',
        content: `题目已全部做完，确认交卷吗？`,
        success: (res) => {
          if (res.confirm) {
            this.fnSubmit()
          }
        }
      })
    },
    fnCountDownFinish() {
      uni.$u.toast('考试时间已结束')
      for (let i = 0; i < this.options.length; i++) {
        if (!this.options[i].checked) {
          this.options[i].checked = ''
        }
      }
      this.fnSubmit()
    },
    async fnSubmit() {
      const {stageexampaperinputId, classId,  } = this.routeQuery
      for (let i = 0; i < this.options.length; i++) {
        if (this.options[i].questiontype === "2") {
          this.options[i].checked = this.options[i].checked.replace(/,/g, "");
        }
      }
      const resData = await setTestPaperSubmission({
        stageexampaperinputId: stageexampaperinputId,
        classId: classId,
        studentId: this.studentId,
        passscore: this.info.passscore,
        options: JSON.stringify(this.options),
      });
      if (resData.examResult === "0") {
        uni.showModal({
          title: "温馨提示",
          content: `您的成绩为${resData.examScore}分，很遗憾您没有通过本次考试，请再接再厉！`,
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              uni.navigateBack({delta: 2});
            }
          },
        });
      } else {
        uni.showModal({
          title: "温馨提示",
          content: `您的成绩为${resData.examScore}分，恭喜您通过本次考试，请继续保持！`,
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              uni.navigateBack({delta: 2});
            }
          },
        });
      }
    }
  }
}
</script>

<style scoped lang="scss">
.content {
  .top {
    margin: 20rpx;
    border-radius: 20rpx;
    padding: 40rpx;
    text-align: center;
    box-sizing: border-box;
    position: relative;

    image {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
    }

    .suject {
      color: #fff;
      font-weight: bold;
      font-size: 32rpx;
      position: relative;
      z-index: 1;
    }

    .questions {
      color: #eeecec;
      font-size: 30rpx;
      padding-top: 20rpx;
      position: relative;
      z-index: 1;
    }

    .time {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      color: #eeecec;
      font-size: 28rpx;
      padding-top: 20rpx;
      position: relative;
      z-index: 1;

      ::v-deep {
        .u-count-down__text {
          color: #eeecec;
          font-size: 28rpx;
          line-height: normal;
        }
      }
    }
  }

  .topic {
    margin: 20rpx;
    padding: 20rpx 20rpx 150rpx;
    box-sizing: border-box;

    .title {
      font-size: 32rpx;
      font-weight: 600;

      .question-type {
        border-radius: 40rpx;
        padding: 4rpx 14rpx;
        border: 1rpx solid #3c9cff;
        font-size: 24rpx;
        color: #3c9cff;
      }

      .tag_title {
        font-size: 28rpx;
        background-color: #b3b3b3;
        color: #fff;
        border-radius: 8rpx;
        padding: 2rpx 10rpx;
        margin-right: 10rpx;
      }
    }

    .options {
      margin-top: 40rpx;

      .item {
        position: relative;
        margin-top: 40rpx;
        color: #696868;

        &.active {
          color: #3c9cff;

          .option {
            background-color: #3c9cff;
            color: #fff;
          }
        }

        .option {
          background-color: #eee;
          border-radius: 80rpx;
          width: 65rpx;
          height: 65rpx;
          line-height: 65rpx;
          text-align: center;
          font-size: 30rpx;
          display: inline-block;
        }

        .text {
          margin-left: 30rpx;
          height: 60rpx;
          line-height: 60rpx;
        }
      }
    }
  }

  .footer {
    display: flex;
    position: fixed;
    bottom: 0;
    justify-content: space-between;
    width: 100%;
    left: 0;
    padding: 20rpx;
    box-sizing: border-box;
    background: #fff;

    button {
      border-radius: 10rpx;
    }
  }
}
</style>
