<template>
  <div>
    <div id="top-view">
      <div class="head">
        <i class="el-icon-arrow-left"></i>
        <div class="title">答题</div>
      </div>
      <div class="tool-box">
        <div class="time">{{ remainingTime }}</div>
        <div class="tag-box">
          <span @click="signQuestion">标记</span>
          <span @click="showCard">答题卡</span>
          <span @click="isExamSubPop = true">交卷</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">
              <div class="title">
                <div class="type">{{ dItem.question_title }}</div>
                <div class="count">{{ currentNum }}/{{ questionsData.sheet.question_count }}</div>
              </div>
              <div class="topic">
                {{ 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">
                <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">{{ 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="false">查看解析</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 @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="examChangeShow;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="examChangeShow">确定</div>
      </div>
    </div>
  </div>
</template>
<script>
import card from '../components/answerCard.vue'
import examEnd from '../components/examEnd.vue'
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
  },
  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() {
            _this.isAnalysis = false
            _this.currentNum = this.activeIndex + 1
          }
        }
      },
      questionsData: {
        questions: []
      },
      requestData: {},
      requestData2: {},
      clockCount: null,
      isExamEnd: true,
      examIsShow: false,
      isExamSubPop: false,
      timePopIsShow: false,
      initTime: null
    }
  },
  computed: {
    swiper() {
      return this.$refs.mySwiper.$swiper
    }
  },
  props: {
    params: {
      type: Object,
      required: false,
      default () {
        return {}
      }
    }
  },
  mounted () {
    this.swiper.slideTo(0, 1000, false)
    this.initTime = setInterval(() => {
      this.examSubmit(0)
    }, 5000)
    this.scrollDom()
  },
  created() {
    this.initData()
  },
  methods: {
    // 答题结束禁止答题
    examEnd() {
      // lhh   this.examIsShow = true
      this.examIsShow = false
      this.isExamEnd = false
    },
    examEndBack() {
      this.examIsShow = false
    },
    // 答题卡点击跳题
    cardChange(e) {
      // const aa = null
      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 = () => {
        this.$message({
          showClose: true,
          message: '已完成标记',
          type: 'success',
          center: true,
          iconClass: ''
        })
      }
      const off = () => {
        this.$message({
          showClose: true,
          message: '已取消标记',
          type: 'success',
          center: true,
          iconClass: ''
        })
      }
      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 (sec === 0) {
          clearInterval(this.clockCount)
          return false
        }
        this.remainingTime = this.secondToDate(sec)
        sec--
      }, 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
      console.log(this.requestData)
      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'), '')
      })
      console.log(this.requestData)
      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() {
      const param = {
        type: 1,
        is_create: 1
      }
      Exam.getExam(param).then(res => {
        if (res === 2) {
          this.getPower()
          return false
        }
        if (res.sheet.remainingTime > 0) {
          this.setClock(res.sheet.remainingTime)
        } else {
          this.examEnd()
        }
        this.scrollDom()
        this.questionsData = res
        setTimeout(() => {
          this.examSubmit(0)
        }, 1500)
        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
        }
      })
    },
    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
    },
    examChangeShow(n) {
      const param = {
        type: 1,
        is_create: 0
      }
      Exam.getExam(param).then(res => {
        this.questionsData = res
        this.requestData = res.answers
        this.examIsShow = true
      })
    },
    getPower() {
      Exam.getPower({ role: 1 }).then(res => {
      })
    },
    examSubmit(status, isSub) {
      const reqData = this.requestData
      const param = {
        sheet_id: this.questionsData.sheet.id,
        answers: JSON.stringify(reqData),
        duration: this.getSecond(this.remainingTime)
      }
      param.status = status
      Exam.examSubmit(param).then(res => {
        if (res.exm_status === 1) {
          clearInterval(this.initTime)
          clearInterval(this.clockCount)
          console.log()
          if (this.questionsData.sheet.remainingTime > 0) {
            if (isSub) {
              this.examChangeShow(1)
            }
            return false
          }
          this.remainingTime = '00:00:00'
          this.timePopIsShow = true
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.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;
  }
  .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;
      }
    }
  }
}
.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;
    height: 3.1rem;
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%,-50%);
    background:rgba(255,255,255,1);
    border-radius:.12rem;
    padding-top: .4rem;
    .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;
    height: 4.08rem;
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%,-50%);
    background:rgba(255,255,255,1);
    border-radius:.12rem;
    padding-top: .4rem;
    .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>
