<template>
  <div class="exam-box">
    <div id="top-view">
      <div class="tool-box">
        <div class="time">{{ remainingTime }}</div>
        <div class="tag-box">
          <span @click="signQuestion" v-if="isExamEnd">标记</span>
          <span @click="showCard">答题卡</span>
          <span @click="submitShowPop" v-if="isExamEnd">交卷</span>
        </div>
      </div>
    </div>
    <div class="topic-box" id="bottom-view" v-if="questionsData">
      <swiper ref="mySwiper" :options="swiperOptions">
        <template v-for="(item) in questionsData.questions">
          <template v-for="(dItem, dIndex) in item.question_list">
            <swiper-slide :key="dIndex+dItem.id" :data-dId="dItem.id" :data-cId="item.id">
              <!-- <answer :item="item" :dItem="dItem" :currentNum="currentNum" :questionsData="questionsData" :requestData="requestData" :requestData2="requestData2"></answer> -->
              <div class="title">
                <div class="type">{{ dItem.question_title }}</div>
                <div class="count">{{ currentNum }}/{{ questionsData.sheet.question_count }}</div>
              </div>
              <div class="topic" v-html="dItem.question_content">
              </div>
              <ul class="option" v-if="item.type === '1' || item.type === '6' || item.type === '5' && dItem.answer_count <= 1">
                <template v-for="(opt, oIndex) in dItem.question_options">
                  <template v-if="requestData2 != 0 && requestData[item.id]">
                    <li :key="oIndex" v-if="requestData[item.id][dItem.id]" :class="requestData[item.id][dItem.id].answer.find(res => { return res === opt.id }) ? 'active' : ''" @click="selectRadio(dItem, opt.id, oIndex, item)" :data-id="opt.id">{{opaKey[oIndex]}}.{{ opt.option }}</li>
                    <li :key="oIndex" v-else :class="dItem.activeIndex == oIndex ? 'active' : ''" @click="selectRadio(dItem, opt.id, oIndex, item)" :data-id="opt.id">{{opaKey[oIndex]}}.{{ opt.option }}</li>
                  </template>
                  <template v-else>
                    <li :key="oIndex" :class="dItem.activeIndex == oIndex ? 'active' : ''" @click="selectRadio(dItem, opt.id, oIndex, item)" :data-id="opt.id">{{opaKey[oIndex]}}{{ opt.option }}</li>
                  </template>
                </template>
              </ul>
              <ul class="option" v-if="item.type === '2' || item.type === '5' && dItem.answer_count > 1">
                <template v-for="(opt, oIndex) in dItem.question_options">
                  <template v-if="requestData2 != 0 && requestData[item.id]">
                    <li :key="oIndex+'-'" v-if="requestData[item.id][dItem.id]" :class="opt.active ? 'active' : ''" @click="selectCheckbox(opt, opt.id, dItem, item, oIndex)" :data-id="opt.id">{{opaKey[oIndex]}}.{{ opt.option }}</li>
                    <li :key="oIndex+'-'" v-else :class="opt.active ? 'active' : ''" @click="selectCheckbox(opt, opt.id, dItem, item, oIndex)" :data-id="opt.id">{{opaKey[oIndex]}}.{{ opt.option }}</li>
                  </template>
                  <template v-else>
                    <li :key="oIndex+'-'" :class="opt.active ? 'active' : ''" @click="selectCheckbox(opt, opt.id, dItem, item, oIndex)" :data-id="opt.id">{{opaKey[oIndex]}}.{{ opt.option }}</li>
                  </template>
                </template>
              </ul>
              <div class="analy" v-if="isAnalysis || $route.query.id">
                <div class="tit">答案解析</div>
                <div class="txt">正确答案：<span>{{ dItem.answerOpt }}</span></div>
                <div class="txt">您的答案：<span>{{ dItem.opaVal }}</span></div>
                <div class="exp">
                  <p class="name">解析：</p>
                  <p class="nr" v-html="dItem.question_analysis"></p>
                </div>
              </div>
            </swiper-slide>
          </template>
        </template>
      </swiper>
    </div>
    <div class="btn-box">
      <div class="padd">
        <div class="analysis" @click="analyShow" v-if="$route.query.id || $route.query.course_id || $route.query.chapter_id">查看解析</div>
        <div class="btn left" @click="switchQuestions('left')">上一题</div>
        <div class="btn right" @click="switchQuestions('right')">下一题</div>
      </div>
    </div>
    <card v-if="isCard" @cardChange="cardChange" @showCard="showCard" :questionsData="questionsData" :requestData="requestData"></card>
    <!-- <exam-end @cardChange="cardChange;examIsShow = false;isExamSubPop = false" @examEndBack="examEndBack" v-if="examIsShow" :questionsData="questionsData" :requestData="requestData"></exam-end> -->
    <div class="exam_submit" v-if="isExamSubPop">
      <div class="pop">
        <div class="tit">交卷</div>
        <div class="txt">您确定提交吗？</div>
        <div class="btn_box">
          <div class="btn" @click="isExamSubPop = false">继续做题</div>
          <div class="btn btn2" @click="goExamResult;examSubmit(1, true)">交卷</div>
        </div>
      </div>
    </div>
    <div class="exam-end-pop" v-if="timePopIsShow">
      <div class="pop">
        <div class="tit">提示</div>
        <img src="../assets/images/time.png" alt="">
        <div class="txt">考试时间到！答题结束</div>
        <div class="btn" @click="goExamResult ;examSubmit(1, true)">确定</div>
      </div>
    </div>
  </div>
</template>
<script>
import card from '../components/answerCard.vue'
// import answer from '../components/answer.vue'
import examEnd from '../components/examEnd.vue'
import { Toast } from 'vant'
import Exam from '../action'
import { Swiper, SwiperSlide, directive } from 'vue-awesome-swiper'
import 'swiper/css/swiper.css'
export default {
  name: 'ExamTopic',
  components: {
    Swiper,
    SwiperSlide,
    card,
    examEnd,
    [Toast.name]: Toast
  },
  directives: {
    swiper: directive
  },
  data () {
    const _this = this
    return {
      isCard: false,
      opaKey: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
      remainingTime: '01:00:00',
      currentNum: 1,
      isAnalysis: false,
      swiperOptions: {
        observer: true,
        on: {
          slideChangeTransitionStart: function() {
            document.getElementById('bottom-view').scrollTop = 0
            _this.isAnalysis = false
            _this.currentNum = this.activeIndex + 1
          }
        }
      },
      questionsData: {
        questions: []
      },
      requestData: {},
      requestData2: {},
      clockCount: null,
      isExamEnd: true,
      // examIsShow: false,
      isExamSubPop: false,
      timePopIsShow: false,
      initTime: null,
      cache: null
    }
  },
  computed: {
    swiper() {
      return this.$refs.mySwiper.$swiper
    }
  },
  props: {
    requestParam: {
      type: Object,
      required: false,
      default () {
        return {}
      }
    }
  },
  beforeDestroy() {
    clearInterval(this.initTime)
    // clearInterval(this.cache)
  },
  mounted () {
    if (!this.$route.query.id) {
      this.swiper.slideTo(0, 1000, false)
      clearInterval(this.initTime)
      this.initTime = setInterval(() => {
        this.examSubmit(0)
      }, 5000)
      this.initData()
    } else {
      this.examEnd()
      this.initData(0)
    }
    this.scrollDom()
  },
  methods: {
    async submitShowPop() {
      const isLogin = await this.$store.dispatch('checkLogin')
      if (!isLogin) {
        if (this.isWeapp) {
          // 小程序
          wx.miniProgram.navigateTo({
            url: `/pages/login/index?redirect_uri=${encodeURIComponent(
              `/exam/result?type=${this.$route.query.type}&is_create=0&papersUrl=${this.$route.query.papersUrl}`
            )}`
          })
        } else {
          this.$router.push({
            path: '/login',
            query: {
              redirect_uri: `/exam/result?type=${this.$route.query.type}&is_create=0&papersUrl=${this.$route.query.papersUrl}`
            }
          })
        }
        return false
      }
      this.isExamSubPop = true
    },
    // 答题结束禁止答题
    examEnd() {
      this.isExamEnd = false
    },
    // 答题卡点击跳题
    cardChange(e) {
      for (let i = 0; i < this.questionsData.sheet.question_count; i++) {
        if (this.swiper.slides[i].attributes['data-dId'].nodeValue === e) {
          this.swiper.slideTo(i, 0, false)
          this.currentNum = this.swiper.activeIndex + 1
        }
      }
    },
    showCard() {
      this.isCard = !this.isCard
    },
    // 标记
    signQuestion() {
      const itemDid = this.swiper.slides[this.swiper.activeIndex].attributes['data-dId'].nodeValue
      const itemCid = this.swiper.slides[this.swiper.activeIndex].attributes['data-cId'].nodeValue
      const on = () => {
        Toast('已完成标记')
      }
      const off = () => {
        Toast('已取消标记')
      }
      if (!this.requestData[itemCid]) {
        this.requestData[itemCid] = {
          [itemDid]: {
            sign: true,
            answer: []
          }
        }
        on()
        return false
      }
      if (!this.requestData[itemCid][itemDid]) {
        this.requestData[itemCid][itemDid] = {
          sign: true,
          answer: []
        }
        on()
      } else {
        if (this.requestData[itemCid][itemDid].sign) {
          this.requestData[itemCid][itemDid].sign = false
          off()
        } else {
          this.requestData[itemCid][itemDid].sign = true
          on()
        }
      }
    },
    // 时间倒计时
    setClock(time) {
      let sec = parseInt(time)
      this.clockCount = setInterval(() => {
        if (this.requestParam.course_id) {
          this.remainingTime = this.secondToDate(sec)
          sec++
        } else {
          if (this.$route.query.id) {
            this.remainingTime = '00:00:00'
            return false
          }
          sec--
          if (sec === 0) {
            clearInterval(this.clockCount)
            this.timePopIsShow = true
            return false
          }
          this.remainingTime = this.secondToDate(sec)
        }
        this.questionsData.sheet.duration++
        // this.questionsData.sheet.duration += parseInt(this.questionsData.sheet.duration)
      }, 1000)
    },
    secondToDate(result) {
      const h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600)
      const m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60))
      const s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60))
      if (h === 0) {
        result = m + ':' + s
      } else {
        result = h + ':' + m + ':' + s
      }
      return result
    },
    // 点击上一题下一题按钮切换
    switchQuestions(e) {
      if (e === 'left') {
        this.swiper.slidePrev()
      } else {
        this.swiper.slideNext()
      }
      // 切换时关闭解析
      this.isAnalysis = false
    },
    // 显示隐藏解析
    analyShow() {
      this.isAnalysis = !this.isAnalysis
      this.scrollDom()
    },
    // 单选事件 判断题事件
    selectRadio(cData, checkId, index, oData) {
      if (!this.isExamEnd) {
        return false
      }
      const opa = this.opaKey
      cData.opaVal = opa[index]
      cData.activeIndex = index
      if (this.requestData[oData.id]) {
        if (!this.requestData[oData.id][cData.id]) {
          this.requestData[oData.id][cData.id] = {
            sign: false,
            answer: [checkId]
          }
        } else {
          this.requestData[oData.id][cData.id].answer = [checkId]
        }
      } else {
        this.requestData[oData.id] = {
          [cData.id]: {
            sign: false,
            answer: [checkId]
          }
        }
      }
      this.$forceUpdate()
    },
    // 多选事件
    selectCheckbox(opt, checkId, cData, oData, index) {
      if (!this.isExamEnd) {
        return false
      }
      opt.active === undefined ? opt.active = true : opt.active = !opt.active
      if (opt.active) {
        if (this.requestData[oData.id]) {
          if (this.requestData[oData.id][cData.id]) {
            const arr = this.requestData[oData.id][cData.id].answer
            this.requestData[oData.id][cData.id] = {
              sign: this.requestData[oData.id][cData.id].sign
            }
            arr.push(checkId)
            this.requestData[oData.id][cData.id].answer = arr
          } else {
            this.requestData[oData.id][cData.id] = {
              sign: false,
              answer: [checkId]
            }
          }
        } else {
          this.requestData[oData.id] = {
            [cData.id]: {
              sign: false,
              answer: [checkId]
            }
          }
        }
      } else {
        const index = this.requestData[oData.id][cData.id].answer.indexOf(checkId)
        this.requestData[oData.id][cData.id].answer.splice(index, 1)
      }
      const opa = this.opaKey
      const opaArr = []
      cData.question_options.map((item, i) => {
        if (item.active) {
          opaArr.push(opa[i])
        }
        cData.opaVal = opaArr.toString().replace(new RegExp(',', 'g'), '')
      })
      this.$forceUpdate()
    },
    // 页面过高局部滚动
    scrollDom() {
      const topViewH = document.getElementById('top-view').offsetHeight
      const clientHeight = document.documentElement.clientHeight
      const bottomView = document.getElementById('bottom-view')
      bottomView.style.height = (clientHeight - topViewH) + 'px'
    },
    initData(n) {
      const param = this.requestParam
      if (window.localStorage.userId !== 'undefined') {
        param.user_id = window.localStorage.userId
      }
      Exam.getExam(param, this.requestParam.papersUrl).then(res => {
        const times = res.sheet.remainingTime ? res.sheet.remainingTime : res.sheet.duration
        if (this.$route.query.id === -1 || this.$route.query.id === '-1') {
          this.errorQuestion(res)
        } else {
          this.questionsData = res
        }
        window.localStorage.userId = res.user_id
        this.remainingTime = this.secondToDate(times)
        this.setClock(times)
        if (res.sheet.status === 1 || res.sheet.status === 2) {
          if (res.sheet.remainingTime === undefined) {
            this.setClock(res.sheet.duration)
          } else {
            if (res.sheet.remainingTime > 0) {
              this.setClock(res.sheet.remainingTime)
            } else {
              this.examEnd()
              this.scrollDom()
            }
          }
        }
        // clearTimeout(this.cache)
        setTimeout(() => {
          this.examSubmit(0)
        }, 1000)
        setTimeout(() => {
          this.cardChange(this.$route.query.id)
        }, 100)
        if (res.answers !== null) {
          const datas = res.answers
          if (datas.length === 0) {
            this.requestData = {}
            this.requestData2 = 0
            return false
          }
          this.requestData = res.answers
          this.requestData2 = Object.keys(datas).length
        } else {
          this.requestData = {}
          this.requestData2 = 0
        }
      })
    },
    errorQuestion(data) {
      let count = data.sheet.question_count
      data.questions.map((item) => {
        item.question_list.map((dItem, index) => {
          if (data.score_items[item.id][dItem.id].is_right) {
            item.question_list.splice(index, 1)
            count--
          }
        })
      })
      data.sheet.question_count = count
      this.questionsData = data
    },
    getSecond(time) {
      let s = ''
      const hour = time.split(':')[0]
      const min = time.split(':')[1]
      const sec = time.split(':')[2]
      s = Number(hour * 3600) + Number(min * 60) + Number(sec)
      return s
    },
    goExamResult(n) {
      const param = this.requestParam
      param.is_create = 0
      this.$emit('goExamResult', this.requestParam)
    },
    examSubmit(status, isSub) {
      const reqData = this.requestData
      const param = {
        sheet_id: this.questionsData.sheet.id,
        answers: JSON.stringify(reqData),
        duration: this.questionsData.sheet.duration,
        user_id: window.localStorage.userId
      }
      param.status = status
      Exam.examSubmit(param, this.requestParam.papersUrl).then(res => {
        if (res.exm_status === 1) {
          clearInterval(this.initTime)
          clearInterval(this.clockCount)
          if (this.requestParam.course_id !== undefined || this.questionsData.sheet.remainingTime > 0) {
            if (isSub) {
              this.goExamResult()
            }
            return false
          }
          this.remainingTime = '00:00:00'
          this.timePopIsShow = true
        }
      })
    }
  }
}
</script>

<style lang="scss">
.exam-box{
  .swiper-wrapper{
    .swiper-slide{
      padding-bottom: 1rem;
    }
  }
  .head{
    color: #222;
    display: flex;
    padding: .4rem 0;
    align-items: center;
    i{
      font-size: .35rem;
      margin-left: .28rem;
    }
    .title{
      margin-left: .03rem;
      font-size: .3rem;
    }
  }
  .tool-box{
    width: 6.7rem;
    border-bottom: .01rem solid rgba(238,238,238,1);
    padding:  .35rem 0;
    display: flex;
    align-items: center;
    margin: 0 auto;
    color: #222;
    .time{
      font-size: .3rem;
    }
    .tag-box{
      margin-left: auto;
      display: flex;
      span{
        padding: .1rem .2rem;
        font-size: .2rem;
        color: #fff;
        background: #67A8FF;
        border-radius: .25rem;
        margin-left: .2rem;
      }
    }
  }
  .topic-box{
    width: 100%;
    margin: 0 auto;
    font-size: .3rem;
    color: #222;
    // padding-bottom: 1.2rem;
    overflow-y: scroll;
    // .swiper-wrapper{
    //   width:100%;
    // }
    // .swiper-slide{
    //   width:100%;
    // }
    .title{
      padding: .4rem;
      display: flex;
      align-items: center;
      .count{
        margin-left: auto;
      }
    }
    .topic{
      font-size: .26rem;
      line-height: .4rem;
      padding: 0 .4rem;
      span{
        width: 100%;
        display: block;
      }
      img{
        width: 100%;
        display: block;
      }
    }
    .option{
      list-style: none;
      margin: .35rem 0 0 0;
      padding: 0 .4rem;
      li{
        background:rgba(247,247,247,1);
        border-radius: .2rem;
        font-weight: bold;
        padding: .35rem .2rem;
        margin-bottom: .2rem;
      }
      .active{
        color: #fff;
        background:#67A8FF;
      }
      .active2{
        color: #fff;
        background:#67C23A;
      }
    }
    .analy{
      font-size: .3rem;
      color: #222;
      padding: 0.2rem .4rem 1.2rem .4rem;
      .tit{
        font-weight: bold;
        line-height: 100%;
      }
      .txt{
        line-height: 100%;
        margin-top: .4rem;
        span{
          font-weight: bold;
        }
      }
      .exp{
        overflow: hidden;
        p{
          float: left;
        }
        .nr{
          width: 5.8rem;
          p{
            width: 100%;
          }
          img{
            width: 100%;
          }
        }
      }
    }
  }
  .btn-box{
    position: fixed;
    bottom: 0;
    left: 0;
    height: 1rem;
    box-shadow:0px 0px 6px 0px rgba(0,0,0,0.05);
    background: #fff;
    color: #222;
    font-size: .3rem;
    width: 100%;
    z-index: 99;
    .padd{
      display: flex;
      padding: 0 .4rem;
      align-items: center;
      height: 100%;
    }
    .analysis{
      margin-right: .3rem;
    }
    .btn{
      width:2.4rem;
      height:.7rem;
      background:rgba(43,124,233,1);
      border-radius:.12rem;
      text-align: center;
      line-height: .7rem;
      color: #fff;
    }
    .left{
      margin-right: .4rem;
    }
    .right{
      margin-left: auto;
      // background:rgba(255,103,103,1);
    }
  }
  .exam_submit{
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999999;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.6);
    .pop{
      width: 5.9rem;
      position: absolute;
      top: 50%;
      left: 50%;
      -webkit-transform: translate(-50%,-50%);
      background:rgba(255,255,255,1);
      border-radius:.12rem;
      padding: 0.4rem 0;
      .tit{
        font-weight:bold;
        color:rgba(34,34,34,1);
        font-size:.3rem;
        text-align: center;
        line-height: 100%;
      }
      .txt{
        color:rgba(34,34,34,1);
        font-size:.3rem;
        text-align: center;
        line-height: 100%;
        margin-top: .8rem;
      }
      .btn_box{
        padding:0 0.2rem;
        display: flex;
        margin-top: .8rem;
        .btn{
          width:2.6rem;
          height:.7rem;
          background:rgba(43,124,233,1);
          border-radius:.12rem;
          text-align: center;
          line-height: .7rem;
          color: #fff;
          font-size: .3rem;
        }
        .btn2{
          margin-left: auto;
        }
      }
    }
  }
  .exam-end-pop{
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999999;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.6);
    .pop{
      width: 5.9rem;
      position: absolute;
      top: 50%;
      left: 50%;
      -webkit-transform: translate(-50%,-50%);
      background:rgba(255,255,255,1);
      border-radius:.12rem;
      padding: .4rem 0;
      .tit{
        font-size: .3rem;
        color: #222;
        text-align: center;
        font-weight: bold;
      }
      img{
        width: 1.59rem;
        height: 1.35rem;
        display: block;
        margin: 0.4rem auto 0.2rem auto;
      }
      .txt{
        color: #222;
        font-size: .3rem;
        line-height: 100%;
        text-align: center;
      }
      .btn{
        margin: .4rem auto 0 auto;
        width:5.5rem;
        height:.7rem;
        background:rgba(255,103,103,1);
        border-radius:.12rem;
        text-align: center;
        line-height: .7rem;
        color: #fff;
        font-size: .3rem;
      }
    }
  }
}
</style>
