<template>
  <div class="exam-box">
    <div id="top-view" v-show="!topicCard.isShow">
      <div class="tool-box">
        <div class="time">{{ $route.query.id !== undefined ? '' : $route.query.course_id || $route.query.tag_id ? '' : '倒计时' }}{{ remainingTime }}</div>
        <div class="tag-box">
          <span @click.prevent.stop="signQuestion" v-if="isExamEnd" :class="signText == '标记' ? '' : 'active'">{{ signText }}</span>
          <span @click="showCard" v-if="isExamEnd">答题卡</span>
          <span @click="submitShowPop" v-if="isExamEnd">交卷</span>
        </div>
      </div>
    </div>
    <div :class="classHide ? 'topic-box' : 'topic-box hide'" 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" v-if="item.type == 1">单选题</div>
                <div class="type" v-if="item.type == 2">多选题</div>
                <div class="type" v-if="item.type == 5">案例题</div>
                <div class="type" v-if="item.type == 6">判断题</div>
                <div class="count">{{ currentNum }}/{{ questionsData.sheet.question_count }}</div>
              </div>
              <div class="topic-bt" v-if="item.type == '5'" v-html="dItem.common_content"></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="dItem.answerOpt.find(cla => { return cla == opaKey[oIndex] }) && (isAnalysis || $route.query.id) ? 'active2' : 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.answerOpt.find(cla => { return cla == opaKey[oIndex] }) && (isAnalysis || $route.query.id) ? 'active2' : 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.answerOpt.find(cla => { return cla == opaKey[oIndex] }) && (isAnalysis || $route.query.id) ? 'active2' : 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="dItem.answerOpt.find(cla => { return cla == opaKey[oIndex] }) && (isAnalysis || $route.query.id) ? 'active2' : 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="dItem.answerOpt.find(cla => { return cla == opaKey[oIndex] }) && (isAnalysis || $route.query.id) ? 'active2' :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="dItem.answerOpt.find(cla => { return cla == opaKey[oIndex] }) && (isAnalysis || $route.query.id) ? 'active2' :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.toString().replace(new RegExp(',', 'g'), '') }}</span></div>
                <template v-if="requestData[item.id]">
                  <div class="txt" v-if="requestData[item.id][dItem.id]">您的答案：<span>{{ requestData[item.id][dItem.id].opaVal.toString().replace(new RegExp(',', 'g'), '') }}</span></div>
                  <div class="txt" v-else>您的答案：<span>{{ dItem.opaVal2 }}</span></div>
                </template>
                <template v-else>
                  <div class="txt">您的答案：<span>{{ dItem.opaVal2 }}</span></div>
                </template>
                <!-- <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-slide v-show="questionsData.questions.length">
          <card @cardChange="cardChange" @showCard="showCard" :questionsData="questionsData" :requestData="requestData" :clickStatus="clickStatus"></card>
        </swiper-slide>
      </swiper>
    </div>
    <!-- v-if="$route.query.id != undefined || questionCount == 1" -->
    <template v-if="$route.query.id == undefined">
      <div class="btn-box" id="bottom-view-btn">
        <div class="padd" v-if="!topicCard.isShow">
          <div v-if="currentNum" :class="collect.currentPages ? 'icon1 active' : 'icon1'" @click="collectQuestion()"></div>
          <div class="analysis" @click="analyShow" v-if="$route.query.id == undefined && ($route.query.course_id || $route.query.tag_id)">查看解析</div>
          <div class="btn left" @click="switchQuestions('left')" v-show="currentNum !== 1">上一题</div>
          <div class="btn right" @click="switchQuestions('right')" v-show="nextBtnShow">下一题</div>
          <div class="btn right" @click="submitShowPop" v-show="!nextBtnShow && isExamEnd">交卷</div>
        </div>
        <div class="padd new-btn" v-else>
          <div class="btn left" @click="swiper.slidePrev()" v-if="isExamEnd">返回答题</div>
          <div class="btn right" @click="submitShowPop" v-if="isExamEnd">交卷</div>
        </div>
      </div>
    </template>
    <template v-else>
      <div class="btn-box" id="bottom-view-btn" v-if="questionCount != 1">
        <div class="padd" v-if="!topicCard.isShow">
          <div v-if="currentNum" :class="collect.currentPages ? 'icon1 active' : 'icon1'" @click="collectQuestion()"></div>
          <div class="analysis" @click="analyShow" v-if="$route.query.id == undefined && ($route.query.course_id || $route.query.tag_id)">查看解析</div>
          <div class="btn left" @click="switchQuestions('left')" v-show="currentNum !== 1">上一题</div>
          <div class="btn right" @click="switchQuestions('right')" v-show="nextBtnShow">下一题</div>
          <div class="btn right" @click="submitShowPop" v-show="!nextBtnShow && isExamEnd">交卷</div>
        </div>
        <div class="padd new-btn" v-else>
          <div class="btn right" @click="submitShowPop" v-if="isExamEnd">交卷</div>
        </div>
      </div>
    </template>
    <!-- <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">{{ subPopText }}</div>
        <div class="btn_box">
          <div class="btn" @click="isExamSubPop = false">继续做题</div>
          <div class="btn btn2" @click="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="submitShowPop(1)">确定</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, Dialog } 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,
    [Dialog.name]: Dialog
  },
  directives: {
    swiper: directive
  },
  metaInfo () {
    if (this.$route.query.id !== undefined) {
      return {
        title: '题目解析',
        meta: [
          // { vmid: 'description', name: 'description', content: this.description }
        ]
      }
    }
  },
  data () {
    const _this = this
    return {
      collect: {
        currentPages: false,
        currentId: '',
        currentIdParent: ''
      },
      currentCollect: false,
      clickStatus: 0,
      questionCount: Number,
      classHide: true,
      nextBtnShow: true,
      isCard: false,
      opaKey: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
      remainingTime: '01:00:00',
      currentNum: 1,
      isAnalysis: false,
      swiperSign: 0,
      swiperOptions: {
        observer: true,
        autoHeight: true,
        on: {
          init() {
            setTimeout(() => {
              _this.setCurrentCollect()
            }, 500)
          },
          slideChangeTransitionStart: function() {
            _this.sildesHeightCount()
            _this.setCurrentCollect()
            _this.getIsSign()
            if (this.activeIndex === _this.questionsData.sheet.question_count) {
              _this.topicCard.isShow = true
            } else {
              _this.topicCard.isShow = false
            }
            document.getElementById('bottom-view').scrollTop = 0
            _this.isAnalysis = false
            _this.currentNum = this.activeIndex + 1
            _this.currentNum === _this.questionsData.sheet.question_count ? _this.nextBtnShow = false : _this.nextBtnShow = true
            _this.requestData.answerPage = this.activeIndex
          },
          slidePrevTransitionEnd: function() {
            if (this.activeIndex === _this.questionsData.sheet.question_count - 1) {
              this.slideTo(_this.swiperSign, 0, false)
              _this.currentNum = this.activeIndex + 1
              _this.currentNum === _this.questionsData.sheet.question_count ? _this.nextBtnShow = false : _this.nextBtnShow = true
            }
          },
          slideNextTransitionEnd: function() {
            if (this.activeIndex === _this.questionsData.sheet.question_count - 1) {
              _this.swiperSign = _this.questionsData.sheet.question_count - 1
            }
            if (this.activeIndex === _this.questionsData.sheet.question_count) {
              _this.clickStatus = Date.parse(new Date())
              _this.requestData.answerPage = _this.questionsData.sheet.question_count - 1
            }
          }
        }
      },
      questionsData: {
        questions: []
      },
      requestData: {},
      requestData2: {},
      clockCount: null,
      isExamEnd: true,
      // examIsShow: false,
      isExamSubPop: false,
      timePopIsShow: false,
      initTime: null,
      cache: null,
      topicCard: {
        isShow: false
      },
      signText: '标记',
      subPopText: '您还有题目未回答，确定交卷吗？'
    }
  },
  computed: {
    isWeapp() {
      return this.$store.state.isWeapp
    },
    swiper() {
      return this.$refs.mySwiper.$swiper
    }
  },
  props: {
    requestParam: {
      type: Object,
      required: false,
      default () {
        return {}
      }
    }
  },
  beforeDestroy() {
    clearInterval(this.initTime)
    clearInterval(this.clockCount)
    this.examSubmit(0)
  },
  mounted () {
    const body = document.querySelector('body')
    // 设置页面点击清除 提示框
    body.addEventListener('click', (e) => {
      Toast.clear()
    }, false)
    this.answerInit()
  },
  methods: {
    sildesHeightCount() {
      // slides高度重新赋值
      if (document.getElementById('bottom-view-btn') === null) {
        return false
      }
      const computedStyle = window.getComputedStyle(this.swiper.slides[this.swiper.activeIndex], null)
      const topView = document.getElementById('top-view').clientHeight
      const bottomView = document.getElementById('bottom-view-btn').clientHeight
      const slidesClentH = document.body.clientHeight - topView - bottomView
      const slidesH = this.swiper.slides[this.swiper.activeIndex].clientHeight
      const countNum = slidesClentH - slidesH
      const sliedsRealH = slidesClentH - (slidesH - parseInt(computedStyle.paddingBottom))
      if (countNum >= 0) {
        this.swiper.slides[this.swiper.activeIndex].style.paddingBottom = `${sliedsRealH}px`
      } else {
        this.swiper.slides[this.swiper.activeIndex].style.paddingBottom = '1.2rem'
      }
    },
    collectQuestion() {
      const queIds = this.collect.currentId
      this.collect.currentPages ? this.removeColl(queIds, () => {
        Toast('取消收藏成功')
        this.collect.currentPages = false
        this.setCollect(false)
      }) : this.addColl(queIds, () => {
        Toast('收藏成功')
        this.collect.currentPages = true
        this.setCollect(true)
      })
      // console.log(this.questionsData.questions)
    },
    setCollect(state) {
      this.questionsData.questions.map(item => {
        if (item.id === this.collect.currentIdParent) {
          const data = item.question_list.find(i => { return i.id === this.collect.currentId })
          data.is_collection = state
        }
      })
    },
    addColl(id, callback) {
      Exam.collectQuestion({ question_id: id }).then(res => {
        if (res.code === 0) {
          callback()
        }
      })
    },
    removeColl(id, callback) {
      Exam.deleteCollect({ type: 2, question_id: id }).then(res => {
        if (res.code === 0) {
          callback()
        }
      })
    },
    // 页面初始化
    answerInit() {
      Toast.loading({
        message: '加载中...',
        duration: 5000
      })
      if (this.$route.query.id === undefined) {
        this.swiper.slideTo(0, 1000, false)
        clearInterval(this.initTime)
        this.initTime = setInterval(() => {
          this.examSubmit(0)
        }, 3000)
        if (this.$route.query.tag_id !== undefined) {
          Exam.getExam(this.requestParam, decodeURIComponent(this.requestParam.papersUrl)).then(res => {
            if (parseInt(res.status) === 1 || parseInt(res.status) === 2) {
              this.requestParam.is_create = 1
            } else {
              this.requestParam.is_create = 0
            }
            this.initData()
          })
        } else {
          this.initData()
        }
      } else {
        this.examEnd()
        this.initData(0)
      }
      setTimeout(() => {
        this.getIsSign()
      }, 500)
    },
    getIsSign() {
      const _this = this
      if (_this.swiper.slides[_this.swiper.activeIndex].attributes['data-dId']) {
        const itemDid = _this.swiper.slides[_this.swiper.activeIndex].attributes['data-dId'].nodeValue
        const itemCid = _this.swiper.slides[_this.swiper.activeIndex].attributes['data-cId'].nodeValue
        if (_this.requestData[itemCid]) {
          if (_this.requestData[itemCid][itemDid]) {
            if (_this.requestData[itemCid][itemDid].sign) {
              _this.signText = '已标记'
            } else {
              _this.signText = '标记'
            }
          } else {
            _this.signText = '标记'
          }
        } else {
          _this.signText = '标记'
        }
      }
    },
    async submitShowPop(n) {
      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
      }
      if (n === 1) {
        this.examSubmit(1, true)
        return false
      }
      let count = 0
      Object.keys(this.requestData).map((item, index) => {
        for (let i = 0; i < Object.keys(this.requestData[item]).length; i++) {
          count++
        }
      })
      if (count === this.questionsData.sheet.question_count) {
        this.subPopText = '确定交卷吗？'
      } else {
        this.subPopText = '您还有题目未回答，确定交卷吗？'
      }
      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) {
          setTimeout(() => {
            document.getElementById('bottom-view').scrollTop = 0
            this.swiper.slideTo(i, 0, false)
            this.topicCard.isShow = false
            setTimeout(() => {
              this.requestData.answerPage = this.swiper.activeIndex
              this.currentNum = this.swiper.activeIndex + 1
              this.currentNum === this.questionsData.sheet.question_count
                ? this.nextBtnShow = false
                : this.nextBtnShow = true
              this.setCurrentCollect()
            }, 100)
            this.getIsSign()
          }, 200)
        }
      }
    },
    showCard() {
      this.requestData.answerPage = this.swiper.activeIndex
      this.clickStatus = Date.parse(new Date())
      if (this.swiper.activeIndex !== this.questionsData.sheet.question_count) {
        this.swiperSign = this.swiper.activeIndex
      } else {
        this.swiperSign = this.swiper.activeIndex - 1
      }
      document.getElementById('bottom-view').scrollTop = 0
      this.topicCard.isShow = true
      this.swiper.slideTo(this.questionsData.sheet.question_count, 0, false)
    },
    // 标记
    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 = () => {
        this.signText = '已标记'
        Toast({
          duration: 500,
          message: '已完成标记'
        })
        this.clickStatus = Date.parse(new Date())
      }
      const off = () => {
        this.signText = '标记'
        Toast({
          duration: 500,
          message: '已取消标记'
        })
        this.clickStatus = Date.parse(new Date())
      }
      if (!this.requestData[itemCid]) {
        this.requestData[itemCid] = {
          [itemDid]: {
            sign: true,
            answer: [],
            opaVal: []
          }
        }
        on()
        return false
      }
      if (!this.requestData[itemCid][itemDid]) {
        this.requestData[itemCid][itemDid] = {
          sign: true,
          answer: [],
          opaVal: []
        }
        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)
      clearInterval(this.clockCount)
      this.clockCount = setInterval(() => {
        if (this.requestParam.course_id || this.requestParam.tag_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.remainingTime = '00:00:00'
            this.timePopIsShow = true
            return false
          }
          if (sec === 600) {
            Toast({
              duration: 1000,
              message: '距离考试结束还有10分钟！'
            })
          }
          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
      setTimeout(() => {
        this.sildesHeightCount()
      }, 200)
    },
    // 单选事件 判断题事件
    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],
            opaVal: [cData.opaVal]
          }
        } else {
          this.requestData[oData.id][cData.id].answer = [checkId]
          this.requestData[oData.id][cData.id].opaVal = [cData.opaVal]
        }
      } else {
        this.requestData[oData.id] = {
          [cData.id]: {
            sign: false,
            answer: [checkId],
            opaVal: [cData.opaVal]
          }
        }
      }
      // this.clickStatus = Date.parse(new Date())
      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
            const arr2 = this.requestData[oData.id][cData.id].opaVal
            this.requestData[oData.id][cData.id].sign === undefined
              ? this.requestData[oData.id][cData.id].sign = false
              : this.requestData[oData.id][cData.id].sign = this.requestData[oData.id][cData.id].sign
            arr.push(checkId)
            arr2.push(this.opaKey[index])
            this.requestData[oData.id][cData.id].answer = arr
            this.requestData[oData.id][cData.id].opaVal = arr2
          } else {
            this.requestData[oData.id][cData.id] = {
              sign: false,
              answer: [checkId],
              opaVal: [this.opaKey[index]]
            }
          }
        } else {
          this.requestData[oData.id] = {
            [cData.id]: {
              sign: false,
              answer: [checkId],
              opaVal: [this.opaKey[index]]
            }
          }
        }
      } else {
        if (this.requestData[oData.id][cData.id].answer.length > 1) {
          const index = this.requestData[oData.id][cData.id].answer.indexOf(checkId)
          this.requestData[oData.id][cData.id].answer.splice(index, 1)
          this.requestData[oData.id][cData.id].opaVal.splice(index, 1)
        } else {
          opt.active = true
        }
      }
      const opa = this.opaKey
      const opaArr = []
      cData.question_options.map((item, i) => {
        if (item.active) {
          opaArr.push(opa[i])
        }
        cData.opaVal2 = opaArr.toString().replace(new RegExp(',', 'g'), '')
      })
      // this.clickStatus = Date.parse(new Date())
      this.$forceUpdate()
    },
    // 页面过高局部滚动
    scrollDom() {
      const topViewH = document.getElementById('top-view').offsetHeight
      const clientHeight = document.documentElement.clientHeight
      const bottomView = document.getElementById('bottom-view')
      // const domH = this.swiper.slides[this.swiper.activeIndex].clientHeight
      bottomView.style.height = (clientHeight - topViewH) + 'px'
      // if (domH - 50 >= (clientHeight - topViewH)) {
      //   this.classHide = true
      // } else {
      //   this.classHide = false
      // }
    },
    initData(n) {
      const param = this.requestParam
      if (window.localStorage.userId !== 'undefined') {
        param.user_id = window.localStorage.userId
      }
      Exam.getExam(param, decodeURIComponent(this.requestParam.papersUrl)).then(res => {
        const times = this.$route.query.id === undefined ? res.sheet.remainingTime ? res.sheet.remainingTime : res.sheet.duration : res.sheet.duration
        if (this.$route.query.id === -1 || this.$route.query.id === '-1') {
          this.errorQuestion(res)
        } else {
          this.questionsData = res
        }
        this.questionCount = res.sheet.question_count
        window.localStorage.userId = res.user_id
        this.remainingTime = this.secondToDate(times)
        Toast.clear()
        if (this.$route.query.id === undefined) {
          this.setClock(times)
        }
        setTimeout(() => {
          this.sildesHeightCount()
          this.examSubmit(0)
          this.scrollDom()
        }, 1000)
        setTimeout(() => {
          this.$route.query.id !== undefined && this.cardChange(this.$route.query.id)
        }, 500)
        this.currentNum === this.questionsData.sheet.question_count ? this.nextBtnShow = false : this.nextBtnShow = true
        if (res.answers !== null) {
          if (res.answers.answerPage !== undefined && this.$route.query.id === undefined && res.answers.answerPage !== this.questionsData.sheet.question_count) {
            setTimeout(() => {
              this.currentNum = res.answers.answerPage + 1
              this.swiper.slideTo(res.answers.answerPage, 0, false)
              // this.setCurrentCollect()
              this.currentNum === this.questionsData.sheet.question_count ? this.nextBtnShow = false : this.nextBtnShow = true
            }, 100)
          }
          const datas = res.answers
          if (datas.length === 0) {
            this.requestData = {}
            this.requestData2 = 0
            return false
          }
          this.requestData = datas
          this.requestData2 = Object.keys(datas).length
        } else {
          // setTimeout(() => {
          //   this.setCurrentCollect()
          // }, 300)
          this.requestData = {}
          this.requestData2 = 0
        }
      })
    },
    setCurrentCollect() {
      if (this.swiper.activeIndex + 1 === this.swiper.slides.length) {
        return false
      }
      const itemDid = this.swiper.slides[this.swiper.activeIndex].attributes['data-dId'].nodeValue
      const itemCid = this.swiper.slides[this.swiper.activeIndex].attributes['data-cId'].nodeValue
      this.questionsData.questions.find(item => {
        if (item.id === itemCid) {
          const currentItem = item.question_list.find(i => { return i.id === itemDid })
          // this.currentCollect = currentItem.is_collection
          this.collect.currentPages = currentItem.is_collection
          this.collect.currentId = itemDid
          this.collect.currentIdParent = itemCid
        }
      })
    },
    errorQuestion(data) {
      let count = 0
      const result = data.questions.map(item => {
        const scroeList = data.score_items[item.id]
        const list = item.question_list.filter(subitem => {
          const score = scroeList[subitem.id]
          return !score.is_right
        })
        item.question_list = list
        return item
      })
      result.map(item => {
        item.question_list.map(i => {
          count++
        })
      })
      data.sheet.question_count = count
      data.questions = result
      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) {
      if (status === 0 && this.swiper.activeIndex + 1 === this.swiper.slides.length) {
        return false
      }
      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.requestParam.tag_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{
    padding-bottom: env(safe-area-inset-bottom);
    .swiper-slide{
      padding-bottom: 1.2rem;
    }
  }
  .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: #F47885;
        border-radius: .25rem;
        margin-left: .2rem;
      }
      .active{
        background: #FF8000;
      }
    }
  }
  .topic-box{
    width: 100%;
    margin: 0 auto;
    font-size: .3rem;
    color: #222;
    overflow-y: scroll;
    .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;
      }
    }
    .topic-bt{
      font-size: .26rem;
      line-height: .4rem;
      padding: 0 .4rem;
      font-weight: bold;
      margin-bottom: .2rem;
      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;
        word-wrap:break-word;
      }
      .active{
        color: #5F95DE;
        background:#DDF1FF;
      }
      .active2{
        color: #40A38B;
        background: #E4F9ED;
      }
    }
    .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{
        margin-top: .4rem;
        overflow: hidden;
        p{
          float: left;
        }
        .nr{
          width: 5.8rem;
          p{
            width: 100%;
          }
          img{
            width: 100%;
          }
        }
      }
    }
  }
  .topic-box.hide{
    overflow: hidden;
  }
  .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;
    padding-bottom: env(safe-area-inset-bottom);
    .padd{
      display: flex;
      padding: 0 .4rem;
      align-items: center;
      height: 100%;
    }
    .analysis{
      white-space: nowrap;
      margin-right: .3rem;
    }
    .icon1{
      width: .36rem;
      height: .36rem;
      background: url('../assets/images/collect.png');
      background-size: 100% 100%;
      margin-right: .3rem;
    }
    .icon1.active{
      background: url('../assets/images/collect2.png');
      background-size: 100% 100%;
    }
    .btn{
      width:1.97rem;
      height:.7rem;
      background:#C62245;
      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:#C62245;
          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:#C62245;
        border-radius:.12rem;
        text-align: center;
        line-height: .7rem;
        color: #fff;
        font-size: .3rem;
      }
    }
  }
}
</style>
