<template>
  <div>
    <div class="exam-box">
      <div class="topic-box">
        <swiper ref="mySwiper" :options="swiperOptions">
          <template v-for="(item, index) in questionData.list">
            <swiper-slide :key="index" :data-id="item.question_id">
              <div id="top-view">
                <div class="tool-box">
                  <div class="time">{{ item.sheet_time }}</div>
                  <div class="tool-all">
                    <div class="tag-box" @click="goAnswerCard">
                      <span style="margin-right:.4rem">答题卡</span>
                    </div>
                    <div v-if="$route.query.type != 2" :class="item.is_collection ? 'icon1 active' : 'icon1'" @click="collectQuestion(item.question_id)"></div>
                    <div class="icon2" @click="delQuestion(item.question_id)"></div>
                  </div>
                </div>
              </div>
              <div class="title">
                <div class="type">{{ other.type[item.question_type] }}</div>
                <div class="count">{{ item.num }}/{{ $route.query.type == 1 ? questionData.error_total : $route.query.type == 2 ? questionData.collection_total : questionData.total }}</div>
              </div>
              <div class="topic-bt" v-if="item.question_type == '5'" v-html="item.common_content"></div>
              <div class="topic" v-html="item.question_content"></div>
              <ul class="option">
                <template v-for="opt in item.question_options">
                  <li
                    v-if="$route.query.type != 3"
                    :key="opt.id"
                    @click="selectOptions(item, opt)"
                    :class="item.user_answer.length != 0 && item.question_answer.find(id => { return id === opt.id })
                    ? 'active2'
                    : item.user_answer.find(id => { return id === opt.id })
                      ? 'active'
                      : ''"
                    >{{ opt.option }}</li>
                  <li
                    v-else
                    :key="opt.id+'=-='"
                    @click="selectOptions(item, opt)"
                    :class="item.question_answer.find(id => { return id === opt.id })
                    ? 'active2'
                    : item.user_answer.find(id => { return id === opt.id })
                      ? 'active'
                      : ''"
                    >{{ opt.option }}</li>
                </template>
              </ul>
              <div class="analy" v-show="isAnalysis || item.user_answer.length != 0">
                <div class="tit">答案解析</div>
                <div class="txt">正确答案：
                  <span>
                    {{
                      item.question_answer.map((i, index) => {
                        return A_Z[item.question_options.findIndex(id => { return id.id === i })]
                      }).toString().replace(new RegExp(',', 'g'), '')
                    }}
                  </span>
                </div>
                <div class="txt">您的答案：
                  <span>
                    {{
                      item.user_answer.map((i, index) => {
                        return A_Z[item.question_options.findIndex(id => { return id.id === i })]
                      }).toString().replace(new RegExp(',', 'g'), '')
                    }}
                  </span>
                </div>
                <div class="exp">
                  <p class="name">解析：</p>
                  <p class="nr" v-html="item.question_analysis"></p>
                </div>
              </div>
            </swiper-slide>
          </template>
        </swiper>
      </div>
      <template>
        <div class="btn-box">
          <div class="padd" v-if="$route.query.type != 2">
            <!-- <div class="analysis" @click="isAnalysis = !isAnalysis" v-if="$route.query.type == 1 || $route.query.type == 2">查看解析</div> -->
            <div class="btn left" @click="switchQuestions('left')" v-if="isBtnShow.currentPage != 1">上一题</div>
            <div class="btn right" @click="switchQuestions('right')" v-if="isBtnShow.currentPage != isBtnShow.pageCount">下一题</div>
          </div>
          <div class="padd new" v-else>
            <div class="ysc">已收藏</div>
            <!-- <div class="analysis" @click="isAnalysis = !isAnalysis" v-if="$route.query.type == 1 || $route.query.type == 2">查看解析</div> -->
            <div class="btn left" @click="switchQuestions('left')" v-if="isBtnShow.currentPage != 1">上一题</div>
            <div class="btn right" @click="switchQuestions('right')" v-if="isBtnShow.currentPage != isBtnShow.pageCount">下一题</div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import * as api from '@/api/my.js'
import { Toast, Dialog } from 'vant'
import { Swiper, SwiperSlide, directive } from 'vue-awesome-swiper'
// import card from '../../components/answerCard.vue'
import 'swiper/css/swiper.css'
export default {
  beforeDestroy() {
    clearInterval(this.cacheTime)
  },
  metaInfo: {
    title: '已做试题'
  },
  components: {
    [Toast.name]: Toast,
    Swiper,
    SwiperSlide,
    [Dialog.name]: Dialog
  },
  directives: {
    swiper: directive
  },
  data() {
    const _this = this
    return {
      isBtnShow: {
        currentPage: 1,
        pageCount: 1
      },
      cacheTime: null,
      cacheList: {},
      prevQuestionId: '',
      pages: 0,
      isMove: true,
      other: {
        type: {
          1: '单选题',
          2: '多选题',
          5: '案例题',
          6: '判断题'
        }
      },
      A_Z: ['A', 'B', 'C', 'D', 'E', 'F'],
      questionData: {
        list: []
      },
      isAnalysis: false,
      swiperOptions: {
        observer: true,
        observeParents: true,
        notNextTick: true,
        autoHeight: true,
        on: {
          init() {
            setTimeout(() => {
              const qId = _this.swiper.slides[_this.swiper.activeIndex].attributes['data-id'].nodeValue
              const item = _this.questionData.list.find(item => { return item.question_id === qId })
              if (item.num % 30 === 0) {
                _this.nextQuestionLoading()
              }
              if ((item.num - 1) % 30 === 0) {
                _this.prevQuestionLoading()
              }
              _this.isBtnShow.currentPage = item.num
            }, 500)
          },
          slideChangeTransitionStart: function() {
            _this.switchPages()
          },
          slidePrevTransitionEnd: function() {
            if (this.activeIndex === 0) {
              _this.prevQuestionLoading()
            }
          },
          slideNextTransitionEnd: function() {
            if (this.activeIndex === this.slides.length - 1) {
              _this.nextQuestionLoading()
            }
          }
        }
      }
    }
  },
  created() {
    parseInt(this.$route.query.type) === 3 ? this.isAnalysis = true : this.isAnalysis = false
  },
  mounted() {
    this.pages = this.$route.query.page
    this.initData(this.pages)
  },
  computed: {
    swiper() {
      return this.$refs.mySwiper.$swiper
    }
  },
  methods: {
    // 缓存试题
    cacheQuestion() {
      const param = {
        type: this.$route.query.type === undefined ? 1 : this.$route.query.type,
        question_type: this.$route.query.questionType === undefined ? '' : this.$route.query.questionType,
        answer: JSON.stringify(this.cacheList)
      }
      api.cacheQuestion(param).then(res => {})
    },
    // init到最后一题加载
    nextQuestionLoading() {
      Toast.loading({
        message: '加载中...',
        duration: 1000,
        loadingType: 'spinner'
      })
      const qId = this.swiper.slides[this.swiper.activeIndex].attributes['data-id'].nodeValue
      const item = this.questionData.list.find(item => { return item.question_id === qId })
      this.prevQuestionId = item.question_id
      this.initData(parseInt(item.num / 30) + 1)
    },
    // init到第一题加载
    prevQuestionLoading() {
      Toast.loading({
        message: '加载中...',
        duration: 1000,
        loadingType: 'spinner'
      })
      const qId = this.swiper.slides[this.swiper.activeIndex].attributes['data-id'].nodeValue
      const item = this.questionData.list.find(item => { return item.question_id === qId })
      this.prevQuestionId = item.question_id
      this.initData(parseInt(item.num / 30), true)
    },
    // 跳转答题卡
    goAnswerCard() {
      this.cacheQuestion()
      clearInterval(this.cacheTime)
      this.$router.push({
        name: 'answerCard',
        query: {
          type: this.$route.query.type === undefined ? 1 : this.$route.query.type,
          questionType: this.$route.query.questionType === undefined ? '' : this.$route.query.questionType
        }
      })
    },
    // 收藏试题
    collectQuestion(queId) {
      const queIds = Array.isArray(queId) ? queId : [queId]
      queIds.map(id => {
        const items = this.questionData.list.find(item => { return item.question_id === queId })
        items.is_collection ? this.removeColl(queIds, () => {
          Toast('取消收藏成功')
          items.is_collection = false
        }) : this.addColl(queIds, () => {
          Toast('收藏成功')
          items.is_collection = true
        })
      })
    },
    addColl(idGroup, callback) {
      api.collectQuestion({ question_id: idGroup.toString() }).then(res => {
        if (res.code === 0) {
          callback()
        }
      })
    },
    removeColl(idGroup, callback) {
      api.deleteQuestion({ type: 2, question_id: idGroup.toString() }).then(res => {
        if (res.code === 0) {
          callback()
        }
      })
    },
    // 删除试题
    delQuestion(ids) {
      const idGroup = Array.isArray(ids) ? ids : [ids]
      const param = {
        question_id: idGroup.toString(),
        type: this.$route.query.type
      }
      api.deleteQuestion(param).then(res => {
        if (res.code === 0) {
          const isNext = this.questionData.list[this.questionData.list.findIndex(item => { return item.question_id === ids }) + 1]
          isNext === undefined ? this.swiper.slidePrev() : this.swiper.slideNext()
          this.$router.replace({
            path: '/my/questionsDetails',
            query: {
              id: this.swiper.slides[this.swiper.activeIndex].attributes['data-id'].nodeValue,
              page: this.$route.query.page,
              type: this.$route.query.type
            }
          })
        }
      })
    },
    // 切换上一题下一题
    switchQuestions(e) {
      if (e === 'left') {
        this.swiper.slidePrev()
      } else {
        this.swiper.slideNext()
      }
    },
    switchPages() {
      const qId = this.swiper.slides[this.swiper.activeIndex].attributes['data-id'].nodeValue
      window.localStorage.myQuestionDetileId = qId
      const itemNum = this.questionData.list.find(item => { return item.question_id === qId })
      this.isBtnShow.currentPage = itemNum.num
      parseInt(this.$route.query.type) === 3 ? this.isAnalysis = true : this.isAnalysis = false
    },
    // 选择选项
    selectOptions(item, opt) {
      if (parseInt(this.$route.query.type) !== 3) {
        this.isAnalysis = true
        if (parseInt(item.question_type) === 1 || parseInt(item.question_type) === 6 || (parseInt(item.question_type) === 5 && item.answer_count === 1)) {
          item.user_answer = [opt.id]
        } else {
          const fIndex = item.user_answer.findIndex(id => { return id === opt.id })
          fIndex === -1 ? item.user_answer.push(opt.id) : item.user_answer.splice(fIndex, 1)
        }
        this.cacheList[item.question_id] = item.user_answer
      }
    },
    // 初始化数据 || 翻页请求数据
    initData(pages, isPush) {
      const params = {
        type: this.$route.query.type === undefined ? 1 : this.$route.query.type,
        question_type: this.$route.query.questionType === undefined ? '' : this.$route.query.questionType,
        page: pages,
        page_size: 30
      }
      api.getMyQuestion(params).then(res => {
        this.questionData.error_total = res.error_total
        this.questionData.total = res.total
        this.questionData.collection_total = res.collection_total
        parseInt(this.$route.query.type) === 1
          ? this.isBtnShow.pageCount = res.error_total
          : parseInt(this.$route.query.type) === 2
            ? this.isBtnShow.pageCount = res.collection_total
            : this.isBtnShow.pageCount = res.total
        const list = []
        res.list.map(item => {
          const isCf = this.questionData.list.findIndex(i => { return i.question_id === item.question_id })
          isCf === -1 && list.push(item)
        })
        this.moveLoading(list, isPush)
        this.$nextTick(() => {
          if (this.isMove) {
            this.isMove = false
            const goIndex = this.questionData.list.findIndex(item => { return item.question_id === window.localStorage.myQuestionDetileId })
            this.swiper.slideTo(goIndex, 0, false)
          }
        })
        if (this.$route.query.type !== 3) {
          clearInterval(this.cacheTime)
          this.cacheTime = setInterval(() => {
            this.cacheQuestion()
          }, 3000)
        }
      })
    },
    // 请求回来试题后删除多余的试题
    moveLoading(list, isPush) {
      if (isPush) {
        this.questionData.list = [...list, ...this.questionData.list]
        if (this.questionData.list.length >= 90) {
          for (let i = 0; i < 30; i++) {
            this.questionData.list.splice(this.questionData.list.length - 1, 1)
          }
        }
        const goIndex = this.questionData.list.findIndex(i => { return i.question_id === this.prevQuestionId })
        if (!this.isMove) {
          setTimeout(() => {
            this.swiper.slideTo(goIndex, 0, false)
          }, 500)
        }
      } else {
        this.questionData.list = [...this.questionData.list, ...list]
        if (this.questionData.list.length >= 90) {
          for (let i = 0; i < 30; i++) {
            this.questionData.list.splice(0, 1)
          }
        }
        const goIndex = this.questionData.list.findIndex(i => { return i.question_id === this.prevQuestionId })
        if (!this.isMove) {
          setTimeout(() => {
            this.swiper.slideTo(goIndex, 0, false)
          }, 500)
        }
      }
    }
  }
}
</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;
    .tool-all{
      margin-left: auto;
      display: flex;
      .icon1{
        width: .44rem;
        height: .44rem;
        background: url('../../assets/images/collect.png');
        background-size: 100% 100%;
        margin-right: .53rem;
      }
      .icon1.active{
        background: url('../../assets/images/collect2.png');
        background-size: 100% 100%;
      }
      .icon2{
        width: .41rem;
        height: .44rem;
        background: url('../../assets/images/del.png');
        background-size: 100% 100%;
      }
    }
    .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;
    }
    .btn{
      width:2.4rem;
      height:.7rem;
      background:#C62245;
      border-radius:.12rem;
      text-align: center;
      line-height: .7rem;
      color: #fff;
    }
    .new{
      .btn{
        width:1.7rem;
        height:.7rem;
      }
      .ysc{
        color: #ccc;
        margin-right: .4rem;
      }
      .analysis{
        margin-left: .4rem;
        margin-right: .4rem;
      }
    }
    .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>
