<template>
  <view class="ml40 p10lr hp100 bc-f5" style="overflow-y: auto;">
    <view class="flex" style="align-items: stretch;">
      <view class="left hp100">
        <view class="fl1 flex" style="align-items: stretch;">
          <view class="info">
            <view class="flex ai-c jc-c mr10 fs16" style="border: 1px solid #999;height: 32px;">
              第01考台
            </view>
            <view class="mt10 p10tb" style="background-color: rgb(177, 222, 255);">
              <view style="margin: 0 auto;width: 64px;">
                <u-avatar :size="64" mp-avatar shape="circle"></u-avatar>
              </view>
            </view>
            <view class="p10" style="background-color: rgb(235, 235, 235);">
              <view class="flex ai-c">
                <text class="fs12 cor-333">姓名</text>
                <view class="fl1 info-box">{{ user.userName }}{{ user.userId }}</view>
              </view>
              <view class="flex ai-c mt5">
                <text class="fs12 cor-333">类型</text>
                <view class="fl1 info-box">小车</view>
              </view>
              <view class="flex ai-c mt5">
                <text class="fs12 cor-333">科目</text>
                <view class="fl1 info-box">科目一</view>
              </view>
            </view>
          </view>
          <view class="fl1 question-box">
            <view class="fs14 cor-000">
              {{questionIndex}} {{question.question}}
            </view>
            <view v-if="question.type != 1" v-for="(item, idx) in question.optionList" :key="idx"
              class="mt5 fs14 cor-000">
              {{item.op}}: {{item.opDesc}}
            </view>
          </view>
        </view>
        <view class="ans-box">
          <view class="flex ai-c">
            <view class="time">
              <!-- <text class="mt7">45:00</text> -->
              <u-count-down ref="countDown" :time="timeCount" format="mm:ss" @change="e=>this.time=e"
                @finish="timeFinish"></u-count-down>
            </view>
            <view class="ml20 fs16 cor-333 fwb">
              您的答案：
            </view>
          </view>
          <view v-if="question.type==1" class="flex">
            <button class="btn" :class="{ done: question.yourAnswer==1 }" @tap="handleAnswer(1)">√</button>
            <button class="btn" :class="{ done: question.yourAnswer==2 }" @tap="handleAnswer(2)">×</button>
          </view>
          <view v-else class="flex">
            <template v-for="(item,index) in question.optionList" :key="index">
              <button class="btn" :class="{ done: question.yourAnswer.includes(index+1) }"
                @tap="handleAnswer(index+1)">{{['A','B','C','D','E','F','G'][index]}}</button>
            </template>
          </view>
        </view>
      </view>
      <view class="right" style="border: 1px solid #999;;">
        <u-grid border :col="subject==1?10:5">
          <u-grid-item v-for="(listItem,listIndex) in list" :key="listIndex" style="box-sizing: border-box;">
            <view class="q-item" :class="{ 'current-question': questionIndex==listIndex+1, done: listItem.yourAnswer }"
              @tap="questionIndex=listIndex+1">{{listIndex+1}}</view>
          </u-grid-item>
        </u-grid>
      </view>
    </view>
    <view class="operate-box">
      <view class="fl1">
        <view class="fs16" style="height: 20px;line-height: 20px;color: rgb(232, 72, 75);">
          操作提示：{{['','判断题','单选题','多选题'][question.type]}}
        </view>
        <view class="fs14 cor-333" style="height: 20px;line-height: 20px;">
          本题是{{getDesc(question.type)}}
        </view>
      </view>
      <view class="flex">
        <button :disabled="questionIndex==1" class="btn" @tap="questionIndex--">上一题</button>
        <button :disabled="questionIndex==list.length" class="btn" @tap="questionIndex++">下一题</button>
        <button class="btn" @tap="handleConfirm">交卷</button>
      </view>
    </view>
    <view class="img-box">
      <image style="height: 100%;" mode="heightFix" :src="question.imageUrl"></image>
    </view>
  </view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from 'pinia' //引入映射函数
	import useQuestionStore from '@/jtools/store/question' //引入store
  import useUserStore from '@/jtools/store/user'
  import {
    getTestQuestion,
    submitTest
  } from '@/jtools/api/question';
  import storage from '@/jtools/storage';
  export default {
    data() {
      return {
        subject:'1',
        questionIndex: 1,
        list: [],
        mutiAns: []
      }
    },
    computed: {
			...mapState(useQuestionStore, ["orderQuestion_subject1", "orderQuestion_subject4", "version"]), //映射函数，取出tagslis
      user() {
        return useUserStore().userInfo
      },
      question() {
        if (this.questionIndex != 0 && this.list.length) {
          return this.list[this.questionIndex - 1]
        } else {
          return {}
        }
      },
      timeCount() {
        return this.subject == 1 ? 60 * 60 * 1000 : 45 * 60 * 1000
      }
    },
    onShow() {
      this.fz()
    },
    onLoad(option) {
      this.subject = option.subject || 1
      if(option.questionIdList){
				const idList=JSON.parse(option.questionIdList)
			  let	arr = this[`orderQuestion_subject${this.subject}`].filter(qItem=>idList.includes(qItem.questionId))
				this.list = arr.map(it => ({
				  ...it,
				  yourAnswer: ''
				}))
			}
    },
    methods: {
      fz() {
        wx.setPageOrientation({
          orientation: 'landscape'
        });
      },
      // _getList() {
      //   getTestQuestion({
      //     carTypeId: storage.get('carType') || '1001',
      //     subject: this.subject
      //   }).then(resp => {
      //     if (resp.code === '0000') {
      //       this.list = resp.data.map(it => ({
      //         ...it,
      //         yourAnswer: ''
      //       }))
      //     }
      //   })
      // },
      handleAnswer(index) {
        // 如果是多选
        let q = this.list[this.questionIndex - 1]
        if (q.type == 3) {
          let arr = q.yourAnswer ? q.yourAnswer.split(',') : []
          arr.includes(index + '') ? arr = arr.filter(it => it != (index + '')) : arr.push(index)
          this.list[this.questionIndex - 1].yourAnswer = arr.join(',')
        } else {
          this.list[this.questionIndex - 1].yourAnswer = index + ''
        }
      },
      getDesc(type) {
        let tt1 = ['', '判断题，', '单选题，', '多选题，'][type]
        let tt2 = ['', '请判断对错！', '请在备选答案中选择你认为正确的答案！', '请在备选答案中选择多个你认为正确的答案！'][type]
        return tt1 + tt2
      },

      handleConfirm() {
        const wdLength = this.list.filter(it => !it.yourAnswer).length
        if (wdLength) {
          uni.showModal({
            title: '考试确认窗口',
            content: `您还有${wdLength}题未答，是否确认交卷？`,
            confirmText: '确认交卷',
            cancelText: '继续考试',
            success: (res) => {
              if (res.confirm) {
                this.toSubmit()
              }
            }
          })
        } else {
          uni.showModal({
            title: '考试确认窗口',
            content: `是否确认交卷？`,
            confirmText: '确认交卷',
            cancelText: '继续考试',
            success: (res) => {
              if (res.confirm) {
                this.toSubmit()
              }
            }
          })
        }
      },
      timeFinish() {
        uni.showToast({
          title: "考试结束，将为您自动交卷~",
          icon: 'none'
        })
        setTimeout(() => {
          this.toSubmit()
        }, 1000)
      },
      toSubmit() {
        const restTime = this.time.hours * 60 * 60 + this.time.minutes * 60 + this.time.seconds
        const score = this.list.reduce((pre, cur) => {
          const isTrue = cur.trueAnswer == cur.yourAnswer.replace(/,-g/, '')
          let s = 0
          if (isTrue) {
            s = this.subject == 1 ? 1 : 2
          }
          return pre + s
        }, 0)
        submitTest({
          "carTypeId": storage.get('carType') || '1001',
          "score": score,
          "testTime": 60 * 60 - restTime,
          subject: this.subject
        }).then(resp => {
          uni.showToast({
            title: '考试结束！',
            icon: 'none',
            complete() {
              uni.navigateBack()
            }
          })
        })
      }
    },
  }
</script>

<style lang="scss" scoped>
  .left {
    flex: 1;
    display: flex;
    flex-direction: column;

    .info {
      width: 100px;
      display: flex;
      flex-direction: column;

      .info-box {
        margin-left: 5px;
        padding-left: 5px;
        height: 28px;
        line-height: 28px;
        box-shadow: inset 2px 2px 5px #babecc, inset -5px -5px 10px #fff;
        font-size: 10px;
        color: #333;
      }
    }

    .question-box {
      position: relative;
      padding: 10px;
      border-top: 1px solid #999;
      border-left: 1px solid #999;
    }

    .ans-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 50px;
      border-top: 1px solid #999;

      .time {
        position: relative;
        display: flex;
        width: 90px;
        height: 32px;
        line-height: 16px;
        justify-content: center;
        align-items: center;
        font-size: 14px;
        color: #333;
        border: 1px solid #999;

        &::before {
          content: '剩余时间';
          position: absolute;
          left: 6px;
          top: 0;
          background-color: #f5f5f5;
          font-size: 10px;
          color: #333;
          transform: translateY(-50%);
        }
      }
    }
  }

  .right {
    width: 270px;

    .q-item {
      width: 28px;
      height: 27px;
      font-size: 10px;
      line-height: 27px;
      text-align: center;
    }
  }

  .operate-box {
    padding-left: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
    border-top: 2px solid rgb(43, 102, 167);
    border-bottom: 2px solid rgb(43, 102, 167);
    border-left: 1px solid #999;
    border-right: 1px solid #999;
  }

  .btn {
    margin-right: 10px;
    height: 30px;
    line-height: 30px;
    // background-color: rgb(244, 243, 239);
    font-size: 14px;
    box-shadow:
      0 0 4px rgba(0, 0, 0, .4),
      // -7px -7px 12px rgba(255, 255, 255, .9);
  }

  .img-box {
    height: 120px;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid #999;
  }

  .current-question {
    background-color: #93F0E4;
  }

  .done {
    background-color: #33FF66;
  }
</style>