<template>
  <div class="testForm">
    <u-navbar title="法治学习" :background="backgroundNavbar"></u-navbar>
    <div class="testForm_info" >
      <div v-for="(item,index) in list" :key="index">
        <div v-if="activeIndex === index">
          <div class="type">
            <div class="type_left">{{ item.type==0? '单选题':item.type==1? '多选题': '判断题' }}</div>
            <div><span class="col_blue">{{ activeIndex + 1 }}</span>/{{ list.length }}</div>
          </div>
          <div class="topic">
            <div>
              <div >
                <!-- 题目 -->
                <div>{{ item.title }}</div>
                <!-- 单选,判断 -->
                <div class="answer_list" v-if="item.type==0 || item.type==2">
                  <div class="answer_item" v-for="(opt,inx) in item.items" :key="inx"
                  :class="{'Checked': clickIndex === inx, 'Succeed': showAnalysis && opt.checked == 1, 'Error': showAnalysis && clickIndex === inx && opt.checked == 0}"
                  @click="itemClick(inx)">
                    {{ opt.sort }}: {{ opt.content}}
                  </div>
                </div>
                <!-- 多选 -->
                <div class="answer_list" v-if="item.type==1">
                  <div class="answer_item" v-for="(opt,inx) in item.items" :key="inx"
                  :class="{'Checked': opt.isChecked,'Succeed': showAnalysis && opt.checked == 1, 'Error': showAnalysis && opt.isChecked && opt.checked == 0}"
                  @click="itemClick(inx)">
                    {{ opt.sort }}: {{ opt.content}}
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="type mar-top" v-if="showAnalysis">
            <div class="type_left">答案解析</div>
          </div>
          <div class="topic mar-top" v-if="showAnalysis">
            <div><span>正确答案：</span></div>
            <div style="margin-top: 8px" v-html="list[activeIndex].analysis"></div>
          </div>
        </div>
      </div>

      <div class="btn" @click="nextTopic" v-if="activeIndex < list.length - 1 && showNext">下一题</div>
      <div class="btn" v-show="showConfirm" @click="confirm">确定</div>
      <div class="btn" v-show="showTiJiao" @click="submit">提交</div>

    </div>
    
  </div>
</template>

<script>
import dayjs from "dayjs"
export default {
  customNavigation: true,
  data() {
    return {
      backgroundNavbar: {
        background: "url('https://cdn.cunwuyun.cn/qujing/navbar.png') no-repeat",
        backgroundSize: '100% 100%',
      },
      list: [],
      activeIndex: 0, // 当前第几题
      activeAnswer: undefined,
      endTime: '', // 结束时间
      id: '', // 题库id
      showConfirm: false,
      showNext: false,
      showTiJiao: false,
      clickIndex: '',
      showAnalysis: false,
      subjectConfigs: [],
      score: 0,
      assessments: [], // 不合格的分数段
      status: 1, // 考试结果，0：未通过、1：通过
      startTime: '',
      nowTime: '',  // 时间戳
      studyDuration: 0,
      assessmentType: '',
      examinationId: '',
      rightCount: 0,
      flag: false,
    }
  },
  methods: {
    getList(id) {
      this.$instance.post(`/app/appexaminationinfo/queryDetailById?id=${id}`).then(res=> {
        if(res?.data) {
          res.data.questions.forEach(item => {
            item.items.forEach(item1 =>{
              item1.isChecked = false
            })
          });
          this.list =  res.data.questions
          this.subjectConfigs = res.data.subjectConfigs
          this.assessments = res.data.assessments
          this.examinationId = res.data.id
        }
      })
    },
    itemClick(i) {
      if (this.showAnalysis) return
      this.showConfirm = true
      if(this.list[this.activeIndex].type==0 || this.list[this.activeIndex].type==2){ // 单选判断
        this.clickIndex = i  
      }
      if(this.list[this.activeIndex].type==1) { // 多选
        this.list[this.activeIndex].items[i].isChecked=!this.list[this.activeIndex].items[i].isChecked
      }
    },
    // 下一题
    nextTopic() {
      this.activeIndex ++;
      this.clickIndex = ''
      this.showAnalysis = false
      this.showNext = false
    },
    // 确定
    confirm() {
      this.showAnalysis = true;
      // 单选判断
      if(this.list[this.activeIndex].type==0 || this.list[this.activeIndex].type==2){
        if(this.list[this.activeIndex].items[this.clickIndex].checked==1) {
          this.score=this.score + this.subjectConfigs[this.list[this.activeIndex].type].eachScore
          this.rightCount ++
        }
      }
      if(this.list[this.activeIndex].type==1) { // 多选
        if(this.list[this.activeIndex].items.every(item=>item.checked===item.isChecked)){ 
          this.score = this.score + this.subjectConfigs[this.list[this.activeIndex].type].eachScore
          this.rightCount ++
        }
      }
      if(this.activeIndex < this.list.length - 1) {
        this.showNext = true;
        this.showConfirm = false;
      } else {
        this.showTiJiao = true;
      }
    },
    getScoreType(score) {
      let conditionMap = [
        (a, b) => a - b >= 0,
        (a, b) => a - b > 0,
        (a, b) => a - b == 0,
        (a, b) => a - b <= 0,
        (a, b) => a - b < 0
      ]
      let type = ['0','1','2','3']
      for (let i = 0; i < this.assessments.length; i++) {
        let ret = this.assessments[i].upScore;
        let con = this.assessments[i].upCondition;
        if (conditionMap[con](score, ret)) {
          this.assessmentType = type[i]
          break;
        }
      }
    },
    // 提交
    submit() {
      if(this.flag) return
      this.getScoreType(this.score)

      let endTime = new Date().getTime()
      this.studyDuration = Math.ceil((endTime - this.nowTime) / 1000 / 60)

      let buhege = this.assessments.filter(e=> e.assessmentType == 3)
      if(buhege[0].upCondition == 3) { // 3：小于等于、4：小于
        if(this.score <= buhege[0].upScore) {
          this.status = 0
        }
      }
      if(buhege[0].upCondition == 4) {
        if(this.score < buhege[0].upScore) {
          this.status = 0
        }
      }
      this.flag = true
      this.$instance.post(`/app/appexaminationinfo/commit`,{
        assessmentType: this.assessmentType,
        examinationId: this.examinationId,
        startTime: this.startTime,
        status: this.status,
        studyDuration: this.studyDuration,
        score: this.score
      }).then(res=> {
        if(res?.code == 0) {
          this.flag = false
          this.$u.toast('提交成功')
          setTimeout(()=> {
            uni.navigateTo({
              url: `./result?status=${this.status}&time=${this.studyDuration}&rightCount=${this.rightCount}&examCount=${this.list.length}&score=${this.score}`
            })
          }, 600)
        }
      }).catch(err=> {
        this.flag = false
        this.$u.toast(err.masg)
      })
    },
  },
  onReachBottom() {
    this.current ++;
  },
  onLoad(o) {
    this.getList(o.id)
    this.startTime = dayjs().format("YYYY-MM-DD HH:mm:ss")
    this.nowTime = new Date().getTime()

  }
}
</script>

<style lang="scss" scoped>
.testForm {
  .testForm_info {
    background: url("https://cdn.cunwuyun.cn/qujing/bg.png") no-repeat;
    background-size: 100% auto;
    padding: 80px 130px 0 32px;
    box-sizing: border-box;

    .type {
      display: flex;
      justify-content: space-between;
      font-size: 28px;
      color: #333333;

      .type_left {
        font-weight: 600;
      }

      .col_blue {
        color: #2D7DFF;
      }

    }

    .topic {
      background: #FFF;
      margin-top: 32px;
      padding: 24px;
      margin-top: 80px;
      border-radius: 16px;
      box-shadow: 0 0 8px 0 rgba(0,0,0,0.02);

      .answer_list {
        margin-top: 32px;

        .answer_item {
          background: #FBFCFE;
          border: 1px solid #CCCCCC;
          border-radius: 16px;
          padding: 28px 24px;
          box-sizing: border-box;
          margin-bottom: 24px;

          .myChoice {
            width: 136px;
            height: 48px;
            background: #FFFFFF;
            border: 1px solid #E23C3C;
            border-radius: 8px;
          }
        }

        .Checked {
          border: 2px solid #2D7EFE;
          color: #2D7DFF;
          background: #EAF2FF;
        }

        .Succeed {
          border: 2px solid #3BBC37;
          color: #3BBC37;
          background: #F5FCF5;
        }

        .Error {
          border: 2px solid #E23C3C;
          color: #E23C3C;
          background: #FDF4F4;
        }
      }
    }

    .mar-top {
      margin-top: 32px;
    }

    .btn {
      position: fixed;
      left: 50%;
      bottom: 0;
      transform: translate(-50%, -50%);
      width: 320px;
      height: 88px;
      line-height: 88px;
      text-align: center;
      background: #2D7DFF;
      border-radius: 44px;
      font-weight: 500;
      font-size: 34px;
      color: #FFFFFF;
    }
  }
}
</style>