<template>
  <div>
    <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="left">
          <question
            v-if="Object.keys(questionParams.question).length"
            :contentHeight="contentHeight"
            :questionParams="questionParams"
            ref="signHandle"
            @isSign="isSign"
          ></question>
        </div>
        <div class="right">
          <answer-card :questionParams="questionParams" :changeTime="changeTime" :info="sInfo.info"></answer-card>
        </div>
      </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'
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: {}
      }
    }
  },
  mounted() {
    // this.sendExamInfo(3)
    this.setTick()
    this.getTopic()
    this.countHeight()
    window.onresize = () => {
      this.countHeight()
    }
  },
  methods: {
    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
              }
            })
          }
        })
        // if (!this.isExamEnd) {
        //   this.endExamRequest(1)
        // }
      } 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)
        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++)
      }
    },
    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
            }
          }
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.answer-box{
  width: 100%;
  height: 100%;
  // background: #f9f9f9;
  .head{
    width: 100%;
    height: 80px;
    background: #FFFFFF;
    display: flex;
    .title{
      padding-left: 30px;
      font-size: 24px;
      font-weight: bold;
      color: #222222;
      line-height: 80px;
    }
    .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;
      overflow-y: scroll;
      scrollbar-width: none;
      &::-webkit-scrollbar {
        display: none;
      }
    }
    .right{
      position: relative;
      width: 220px;
      background: #fff;
      padding: 0 20px;
      overflow-y: scroll;
      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;
        }
      }
    }
  }
}
</style>
