<template>
  <div>
    <div class="exam-box">
      <div class="topic-box">
        <swiper ref="mySwiper" :options="swiperOptions">
          <template v-for="item in questionData.list">
            <swiper-slide :key="item.id" :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 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
                    :key="opt.id"
                    @click="selectOptions(item, opt)"
                    :class="isAnalysis && 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">
                <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')">上一题</div>
            <div class="btn right" @click="switchQuestions('right')" >下一题</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')">上一题</div>
            <div class="btn right" @click="switchQuestions('right')" >下一题</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 'swiper/css/swiper.css'
export default {
  metaInfo: {
    title: '已做试题'
  },
  components: {
    [Toast.name]: Toast,
    Swiper,
    SwiperSlide,
    [Dialog.name]: Dialog
  },
  directives: {
    swiper: directive
  },
  data() {
    const _this = this
    return {
      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,
        autoHeight: true,
        on: {
          slideChangeTransitionStart: function() {
            const qId = this.slides[this.activeIndex].attributes['data-id'].nodeValue
            const item = _this.questionData.list.find(item => { return item.question_id === qId })
            const totalNum = parseInt(_this.$route.query.type) === 1 ? _this.questionData.error_total : _this.questionData.total
            if (this.activeIndex === this.slides.length - 1) {
              if (item.num < totalNum) {
                _this.pages++
                _this.initData(_this.pages)
              }
            }
            if (this.activeIndex === 0) {
              if (item.num > 5) {
                _this.pages--
                _this.initData(_this.pages, 1)
              }
            }
            _this.switchPages()
          }
        }
      }
    }
  },
  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: {
    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() {
      parseInt(this.$route.query.type) === 3 ? this.isAnalysis = true : this.isAnalysis = false
    },
    selectOptions(item, opt) {
      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)
      }
    },
    initData(pages, isPush) {
      const params = {
        type: this.$route.query.type,
        page: pages,
        page_size: 50
      }
      api.getMyQuestion(params).then(res => {
        this.questionData.error_total = res.error_total
        this.questionData.total = res.total
        this.questionData.collection_total = res.collection_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)
        })
        if (!isPush) {
          if (this.swiper.slides.length !== 0) {
            this.questionData.list = [...this.questionData.list, ...list]
            this.swiper.slideTo(0, 0, false)
          } else {
            this.questionData.list = [...this.questionData.list, ...list]
          }
          if (this.questionData.list.length > 90) {
            for (let i = 0; i < 50; i++) {
              this.questionData.list.splice(0, 1)
            }
          }
        } else {
          if (this.swiper.slides.length !== 0) {
            this.questionData.list = [...list, ...this.questionData.list]
            this.swiper.slideTo(this.questionData.list.length - 1, 0, false)
          } else {
            this.questionData.list = [...list, ...this.questionData.list]
          }
          if (this.questionData.list.length > 90) {
            for (let i = 0; i < 50; i++) {
              this.questionData.list.splice(this.questionData.list.length - 1, 1)
            }
          }
        }
        if (this.isMove) {
          this.isMove = false
          const goIndex = this.questionData.list.findIndex(item => { return item.question_id === this.$route.query.id })
          this.swiper.slideTo(goIndex, 0, false)
        }
      })
    }
  }
}
</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: #67A8FF;
        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: #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{
        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:rgba(43,124,233,1);
      border-radius:.12rem;
      text-align: center;
      line-height: .7rem;
      color: #fff;
    }
    .new{
      .btn{
        width:1.7rem;
        height:.7rem;
      }
      .ysc{
        color: #ccc;
      }
      .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>
