<template>
  <div @touchmove.prevent>
    <div class="answer-box">
      <div class="head" id="head-h">
        <div class="title">{{ examInfo.name }}</div>
        <div class="right">
          <div class="count">{{ examTime }}</div>
          <!-- <div class="time">
            <div class="icon"></div>
            <div class="mun">60:00</div>
          </div> -->
        </div>
      </div>
      <div class="exam-main" :style="{ height: this.contentHeight + 'px' }">
        <div :class="isMobile() ? 'left scroll' : 'left hidden'" ref="wrapper2">
          <div>
            <question
              style="padding-bottom: 30px"
              v-if="Object.keys(questionParams.question).length"
              :contentHeight="contentHeight"
              :questionParams="questionParams"
              ref="signHandle"
              @isSign="isSign"
            ></question>
          </div>
        </div>
        <div class="right" ref="wrapper">
          <answer-card
            :questionParams="questionParams"
            :changeTime="changeTime"
            :info="sInfo.info"
            @switchQuestion="switchQuestion"
          ></answer-card>
        </div>
        <ul class="flag-tips">
          <li>
            <div class="circle1"></div>
            <div class="txt">已答</div>
          </li>
          <li>
            <div class="circle2"></div>
            <div class="txt">未答</div>
          </li>
          <li>
            <div class="circle3"></div>
            <div class="txt">当前</div>
          </li>
          <li>
            <div class="circle4"></div>
            <div class="txt">标记</div>
          </li>
        </ul>
      </div>
      <div class="foot" id="foot-h">
        <div class="exam-btn">
          <div @click="changeIndex('prev')" :class="this.questionParams.questionIndex !== 0 ? 'active' : ''">
            上一题
          </div>
          <div
            :class="questionParams.questionIndex + 1 !== questionParams.question.total_question_count ? 'active' : ''"
            @click="changeIndex('next')"
          >
            下一题
          </div>
        </div>
        <div class="rigth-btn">
          <div class="sign" @click="signHandle">
            <div :class="itemSign ? 'icon active' : 'icon'"></div>
            <div class="txt">{{ itemSign ? '取消标记' : '标记' }}</div>
          </div>
          <div class="end-exam-btn">
            <div class="btn" @click="endExam(2)">提交试卷</div>
          </div>
        </div>
      </div>
    </div>
    <my-dia :title="title" :prompt="prompt" v-if="isPopup" @close="close">
      <template v-slot:button>
        <button @click="close">关闭</button>
        <button @click="endExamRequest">确定</button>
      </template>
    </my-dia>
  </div>
</template>
<script>
import action from '@action'
import answerCard from '../../components/exam/answerCard.vue'
import question from '../../components/exam/question.vue'
import dialogComponent from '../../components/exam/dialogComponent.vue'
import BScroll from 'better-scroll'
export default {
  metaInfo() {
    return {
      title: JSON.parse(window.localStorage.getItem('examInfo')).name || ''
    }
  },
  components: {
    answerCard,
    question,
    'my-dia': dialogComponent
  },
  data() {
    return {
      isExamEnd: false,
      isExamTimeDate: true,
      itemSign: false,
      examTime: '00:00:00 倒计时',
      clearTime: null,
      sInfo: JSON.parse(window.localStorage.getItem('studentInfo')),
      examInfo: JSON.parse(window.localStorage.getItem('examInfo')),
      title: '提示',
      prompt: '确定后要结束本次考试？还有作答时间，结束考试后，将不能返回本次考试！',
      isPopup: false,
      contentHeight: 0,
      // 题的数据所需的参数
      changeTime: 0,
      questionParams: {
        // 用户选择的选项 --- 提交后台的数据
        answerRecord: {},
        // 当前题的下标
        questionIndex: 0,
        // 所有题 和题的信息
        question: {},
        domBScroll: null
      }
    }
  },
  mounted() {
    // this.sendExamInfo(3)
    this.setTick()
    this.getTopic()
    this.countHeight()
    window.onresize = () => {
      this.countHeight()
    }
    if (!this.isMobile()) {
      const wrapper = this.$refs.wrapper
      new BScroll(wrapper, { click: true })
      this.initBscroll()
    }
  },
  methods: {
    // 初始化bscroll插件
    initBscroll() {
      setTimeout(() => {
        const wrapper2 = this.$refs.wrapper2
        this.domBScroll = new BScroll(wrapper2, { click: true })
      }, 1000)
    },
    sendExamInfo(status) {
      const param = {
        student_id: this.sInfo.info.student_id,
        exam_id: this.examInfo.exam_id,
        status: status
      }
      action.Login.sendExamInfo(param)
        .then(res => {})
        .catch(err => {
          console.log(err)
        })
    },
    countHeight() {
      this.contentHeight = parseInt(
        document.body.clientHeight - (this.getDom('head-h').offsetHeight + this.getDom('foot-h').offsetHeight)
      )
    },
    // 标记
    signHandle() {
      this.$refs.signHandle.onSignHandle()
    },
    isSign(value) {
      this.itemSign = value
      console.log(value)
    },
    // 提交考试
    endExam(n) {
      if (n === 1) {
        this.$alert('考试时间到', {
          confirmButtonText: '确定',
          callback: action => {
            this.$router.replace({
              path: '/examEnd',
              query: {
                id: JSON.parse(window.localStorage.getItem('examInfo')).exam_id
              }
            })
          }
        })
      } else {
        const count = parseInt(this.questionParams.question.total_question_count) - parseInt(this.countAnswer())
        if (count === 0) {
          this.$confirm('确定后要结束本次考试？还有作答时间，结束考试后，将不能返回本次考试！', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '关闭',
            type: 'warning'
          })
            .then(() => {
              this.endExamRequest()
            })
            .catch(() => {})
        } else {
          this.$confirm(`确定要结束本次考试？还有${count}题未答，结束考试后，将不能返回本次考试`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              this.endExamRequest()
            })
            .catch(() => {})
        }
      }
    },
    countAnswer() {
      let countNum = 0
      const data = this.questionParams.answerRecord
      for (const item in data) {
        const list = Object.values(data[item])
        for (let i = 0; i < list.length; i++) {
          if (list[i].answer.length) {
            countNum++
          }
        }
      }
      return countNum
    },
    endExamRequest(n) {
      // this.sendExamInfo(5)
      const param = {
        answer: JSON.stringify(this.questionParams.answerRecord)
      }
      action.Exam.endExam(this.$route.params.examId, param).then(res => {
        if (!n) {
          clearInterval(this.clearTime)
          this.$router.replace({
            path: '/examEnd'
          })
        }
        // this.sendExamInfo(6)
        window.localStorage.setItem('showflag', 'true')
      })
      // .catch(err => {
      // if (err.message.indexOf('error') !== -1) {
      //   this.$confirm('网络异常，请保持网络通畅', '提示', {
      //     distinguishCancelAndClose: true,
      //     confirmButtonText: '退出考试',
      //     cancelButtonText: '重新提交',
      //     type: 'warning'
      //   })
      //     .then(() => {
      //       this.$router.replace({
      //         path: `/login/${JSON.parse(window.localStorage.getItem('examInfo')).exam_id}`
      //       })
      //     })
      //     .catch(action => {
      //       action === 'cancel' && this.endExamRequest()
      //     })
      // } else {
      //   this.$alert(err.message, {
      //     callback: action => {}
      //   })
      // }
      // })
    },
    countDown(time) {
      const lefttime = parseInt(time / 1000)
      const h = this.addZero(parseInt((lefttime / (60 * 60)) % 24))
      const m = this.addZero(parseInt((lefttime / 60) % 60))
      const s = this.addZero(parseInt(lefttime % 60))
      this.examTime = `${h} : ${m} : ${s} 倒计时`
    },
    setTick() {
      let flag = true
      this.clearTime = setInterval(() => {
        const nowtime = new Date()
        const endtime = new Date(this.examInfo.end_time.replace(/-/g, '/'))
        const countTime = endtime.getTime() - nowtime.getTime()
        if (countTime <= 0) {
          this.isExamTimeDate = false
          clearInterval(this.clearTime)
          this.examTime = '00:00:00 倒计时'
          this.endExam(1)
        } else {
          this.countDown(countTime)
        }
        if (flag) {
          parseInt(countTime) <= 5 &&
            (() => {
              this.endExamRequest(1)
              flag = false
            })()
        }
      }, 1000)
    },
    addZero(i) {
      return i < 10 ? '0' + i : i + ''
    },
    close() {
      this.isPopup = false
    },
    getDom(id) {
      return document.getElementById(id)
    },
    changeIndex(type) {
      if (type === 'prev') {
        this.questionParams.questionIndex > 0 && this.questionParams.questionIndex--
      } else {
        this.questionParams.questionIndex + 1 !== this.questionParams.question.total_question_count &&
          this.questionParams.questionIndex++
      }
      this.refreshBscroll()
    },
    refreshBscroll() {
      if (!this.isMobile()) {
        this.$nextTick(() => {
          this.domBScroll.refresh()
          this.domBScroll.scrollTo(0, -10, 0)
        })
      }
    },
    switchQuestion() {
      this.refreshBscroll()
    },
    getTopic() {
      action.Exam.getTopic(this.$route.params.examId)
        .then(res => {
          this.questionParams.question = res
          this.getCache()
        })
        .catch(err => {
          this.isExamEnd = true
          console.log(err)
        })
    },
    getCache() {
      action.Exam.getCache(this.$route.params.examId)
        .then(res => {
          const data = JSON.parse(res.answer)
          if (data !== null && data !== 'null') {
            this.questionParams.answerRecord = data
            this.getSignStu()
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    getSignStu() {
      this.questionParams.question.question_items.map((item, index) => {
        const currentItem = item.question_list.find(items => {
          return items.q_order === this.questionParams.questionIndex + 1
        })
        if (currentItem) {
          const data = this.questionParams.answerRecord
          if (data[currentItem.question_item_id]) {
            if (data[currentItem.question_item_id][currentItem.id]) {
              this.itemSign = data[currentItem.question_item_id][currentItem.id].sign
            }
          }
        }
      })
    },
    isMobile() {
      const ua = navigator.userAgent
      const isWindowsPhone = /(?:Windows Phone)/.test(ua)
      const isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone
      const isAndroid = /(?:Android)/.test(ua)
      const isPhone = /(?:iPhone)/.test(ua)
      const isPc = !isPhone && !isAndroid && !isSymbian
      return isPc
    }
  },
  computed: {
    changeQuestionIndex() {
      return this.questionParams.questionIndex
    }
  },
  watch: {
    changeQuestionIndex(newV, oldV) {
      this.refreshBscroll()
    }
  }
}
</script>
<style lang="scss" scoped>
.answer-box {
  width: 100%;
  height: 100%;
  // background: #f9f9f9;
  .head {
    width: 100%;
    background: #ffffff;
    display: flex;
    .title {
      padding-left: 30px;
      font-size: 24px;
      font-weight: bold;
      color: #222222;
      line-height: 60px;
    }
    .right {
      position: relative;
      width: 260px;
      margin-left: auto;
      display: flex;
      justify-content: space-around;
      align-items: center;
      .count {
        font-size: 18px;
        font-weight: bold;
        color: #222222;
      }
      .time {
        display: flex;
        .icon {
          width: 23px;
          height: 23px;
          background: url(../../assets/images/tick.png);
          background-size: 100% 100%;
        }
        .mun {
          font-size: 18px;
          font-weight: bold;
          color: #222222;
          line-height: 25px;
          margin-left: 10px;
        }
      }
    }
  }
  .exam-main {
    display: flex;
    .left {
      flex: 1;
      padding: 10px 20px 0 53px;
      &.hidden{
        overflow: hidden;
      }
      &.scroll{
        overflow-y: scroll;
        scrollbar-width: none;
        &::-webkit-scrollbar {
          display: none;
        }
      }
    }
    .right {
      position: relative;
      width: 220px;
      background: #fff;
      padding: 0 20px;
      overflow-y: hidden;
      // scrollbar-width: none;
      // &::-webkit-scrollbar {
      //   display: none;
      // }
    }
  }
  .foot {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 60px;
    background: #ffffff;
    display: flex;
    align-items: center;
    .exam-btn {
      display: flex;
      padding-left: 40px;
      cursor: pointer;
      div {
        width: 100px;
        height: 40px;
        border-radius: 4px;
        border: 1px solid #cccccc;
        font-size: 14px;
        font-weight: bold;
        color: #999999;
        line-height: 40px;
        text-align: center;
        margin-right: 20px;
        &.active {
          background: #c01540;
          border-radius: 4px;
          color: #fff;
        }
      }
    }
    .rigth-btn {
      display: flex;
      margin-left: auto;
      .end-exam-btn {
        width: 260px;
        display: flex;
        justify-content: center;
        align-items: center;
        .btn {
          cursor: pointer;
          width: 200px;
          height: 40px;
          background: #c01540;
          border-radius: 4px;
          font-size: 14px;
          font-weight: bold;
          color: #fff;
          line-height: 40px;
          text-align: center;
        }
      }
      .sign {
        margin-right: 20px;
        .icon {
          margin: 0 auto;
          width: 24px;
          height: 24px;
          background: url(../../assets/images/sign.png);
          background-size: 100% 100%;
          &.active {
            background: url(../../assets/images/sign2.png);
            background-size: 100% 100%;
          }
        }
        .txt {
          font-size: 14px;
          color: #cccccc;
          line-height: 20px;
          margin-top: 2px;
        }
      }
    }
  }
}
.flag-tips {
  width: 260px;
  position: fixed;
  bottom: 60px;
  right: 0;
  display: flex;
  justify-content: space-around;
  padding: 15px 0 10px;
  background: #fff;
  margin: 0;
  list-style: none;
  li {
    .circle1 {
      width: 24px;
      height: 24px;
      background: #999;
      border: 1px solid #999;
      border-radius: 50%;
    }
    .circle2 {
      width: 24px;
      height: 24px;
      border: 1px solid #cccccc;
      border-radius: 50%;
    }
    .circle3 {
      width: 24px;
      height: 24px;
      border: 2px solid #0fc118;
      background: rgba(15, 193, 24, 0.1);
      border-radius: 50%;
    }
    .circle4 {
      position: relative;
      width: 24px;
      height: 24px;
      border: 1px solid #cccccc;
      border-radius: 50%;
      &::after {
        content: '';
        position: absolute;
        top: -1px;
        right: -1px;
        width: 4px;
        height: 4px;
        background: #c01540;
        border-radius: 50%;
      }
    }
    .txt {
      margin-top: 5px;
      font-size: 12px;
      color: #cccccc;
      line-height: 17px;
    }
  }
}
</style>
