<template>
    <div class="liuyan">
<!--      <back  title="考试中心" buttonText="模拟考试" buttonUrl="/examTest"></back>-->
      <mt-header fixed title="考试中心">
        <mt-button icon="back" @click="back" slot="left"></mt-button>
        <mt-button class="sub-button" slot="right" @click="GoExamTest">模拟考试</mt-button>
      </mt-header>
      <div class="exam-info" v-if="is_start == 0 && config.exam_type != 3">
        <div>
          <p>1、考试时间为{{config.exam_time / 60}}分钟。一旦开始考试，不可中断，如中途退出，继续计时，且所答的题目不做记录。</p>
          <p>2、考试题共{{config.exam_num}}题。不答视为0分。</p>
          <p>3、{{config.exam_score}}分及以上视为考试通过，考试通过后，可通过首页证书页面查看证书。如未通过，请联系企业负责人申请补考。</p>
          <p>4、右下角点击序号会显示序号列表，点击跳至对应题目，当前的题显示为蓝色，未作答的题显示为红色。</p>
          <p>5、请在课程结束日期前完成所有课程所有课程完成后进入考试系统 。</p>
          <p v-if="config.exam_type == 2" class="active">6、本次考试为补考，补考开始时间请联系工作人员确认。您已参与补考{{config.bu_num}}次。</p>
        </div>
        <mt-button class="tijiao" type="primary" size="large" @click="start" v-if="config.exam_type == 1">开始考试</mt-button>
        <mt-button class="tijiao" type="primary" size="large" @click="start_bu" v-if="config.exam_type == 2">开始补考</mt-button>
      </div>
      <div v-if="is_start == 0 && config.exam_type == 3" class="pass-exam">
        恭喜您！<br />您已通过考核！
        <mt-button class="tijiao" type="primary" size="large" @click="goCert">查看证书</mt-button>
      </div>
      <div v-if="is_start == 1" class="lx">
        <div class="times">剩余时间：{{time_str}}</div>
        <div v-if="current_question_data.type == 13">
          <div class="lianxiTiMu">
            <span class="lianxiTiMu1">判断题</span>
            <span>{{current_question_data.name}}</span>
          </div>
          <div class="lianxiTiMu" v-for="(item,index) in current_question_data.content" :key="index" @click="responseQ(item)">
            <span class="lianxiXueZe" v-bind:class="{ active: current_question_data.response == item }">{{xuhao[index]}}</span>
            <span class="lianxiXueZe1">{{item}}</span>
          </div>
        </div>
        <div v-if="current_question_data.type == 3">
          <div class="lianxiTiMu">
            <span class="lianxiTiMu1">单选题</span>
            <span>{{current_question_data.name}}</span>
          </div>
          <div class="lianxiTiMu" v-for="(item,index) in current_question_data.content" :key="index" @click="responseQ(item)">
            <span class="lianxiXueZe" v-bind:class="{ active: current_question_data.response == item }">{{xuhao[index]}}</span>
            <span class="lianxiXueZe1">{{item}}</span>
          </div>
        </div>
        <div v-if="current_question_data.type == 4">
          <div class="lianxiTiMu">
            <span class="lianxiTiMu1">多选题</span>
            <span>{{current_question_data.name}}</span>
          </div>
          <div class="lianxiTiMu" v-for="(item,index) in current_question_data.content" :key="index" @click="responseS(index)">
            <span class="lianxiXueZe" v-bind:class="{ active: current_question_data.response.indexOf(index) != -1 }">{{xuhao[index]}}</span>
            <span class="lianxiXueZe1">{{item}}</span>
          </div>
        </div>
				<div v-if="current_question_data.type == 12">
				  <div class="lianxiTiMu">
				    <span class="lianxiTiMu1">填空题</span>
				    <span>{{current_question_data.name}}</span>
						<div class="tiankong" v-for="(i,key) in tiankongdata" :key="key">
							<div v-for="(item,index) in i.label.length" :key="index">
								<input type="text" class="tiank"	maxlength="1"  v-model="i.num[index]"
						    :id="'tk'+index" @blur="responseC(i.num[index])">
							</div>
						</div>
				  </div>
				</div>
        <div class="lianxiBottom">
          <div class="lianxiBottomL">

            <div @click="prevQ">上一题</div>
            <div @click="nextQ">下一题</div>
            <div @click="subQ">交卷</div>
          </div>

          <div class="lianxiBottomR" @click="popupVisible = true"><img src="../../../static/img/gengduo.png" alt=""><span>{{current_question + 1}}</span>/{{questions.length}}</div>
        </div>
      </div>
      <mt-popup v-model="popupVisible" position="bottom" >
        <div class="order_number">
          <div v-for="(item,index) in questions" :key="index" @click="goQ(index)" v-bind:class="{error: !item.response && current_question != index,active: current_question == index}">
            {{index+1}}
          </div>
        </div>
      </mt-popup>
    </div>
</template>

<script>
  import Back from "../common/Back"
  import { getStore } from '@/utils/storage'
  import { Toast } from "mint-ui"
  import { MessageBox } from 'mint-ui'
    export default {
      name: "LiuYan",
      components:{Back},
      data(){
        return{
          id: '',
          config:{},
          is_start: 0,
          exam_data: {},
          xuhao:['A','B','C','D','E','F','G','H','I','J','K','L','M','N'],
          questions:[],
          current_question:0,
          current_question_data:{},
          popupVisible: false,
          timer: '',
          time_str: '',
          tiankongdata: [],
        }
      },
      methods:{
        back(){
          this.$router.go(-1)
        },
        GoExamTest(){
					MessageBox.confirm('确定开始模拟考试吗?').then(action => {
						this.getData('/Question/examNum',{token:getStore('token')}).then(
            data=>{
              if(data.code == 2){
                Toast(data.msg)
              }
              if(data.code == 1){
                this.$router.push({path: '/examTest'});
              }
            })
					}, () => {});

        },
        goCert(){
          this.$router.push({path: '/certificate'});
        },
        start(){
          this.getData('/Question/getExamQuestions',{token:getStore('token')}).then(
            data=>{
              if(data.code==1){
                let _this = this
                this.is_start = 1
                this.id =  data.data.id
                this.questions = data.data.question_data
                this.current_question_data = data.data.question_data[0]
                this.exam_data = data.data.exam_data
                this.timer = setInterval(function () {
                  if(_this.exam_data.remain_time > 0){
                    _this.exam_data.remain_time--
                  }else{
                    _this.time_str = '时间结束'
                    _this.subQ()
                    clearInterval(_this.timer)
                  }
                  let times = _this.exam_data.remain_time
                  if (times > 60) {
                    _this.time_str = parseInt(times / 60.0) + "分" + parseInt((parseFloat(times / 60.0) - parseInt(times / 60.0)) * 60) + "秒";
                  }else{
                    _this.time_str = parseInt(times) + "秒"
                  }
                },1000)
              }else{
                Toast(data.msg);
              }
            },
            err=>{  })
        },
        start_bu(){
          this.getData('/Question/getExamBuQuestions',{token:getStore('token')}).then(
            data=>{
              if(data.code==1){
                let _this = this
                this.is_start = 1
                this.questions = data.data.question_data
                this.current_question_data = data.data.question_data[0]
                this.exam_data = data.data.exam_data
                if(this.current_question_data.type == 12){
                  this.tk(this.current_question_data.answer.split('*'))
                }
                this.timer = setInterval(function () {
                  if(_this.exam_data.remain_time > 0){
                    _this.exam_data.remain_time--
                  }else{
                    _this.time_str = '时间结束'
                    _this.subQ()
                    clearInterval(_this.timer)
                  }
                  let times = _this.exam_data.remain_time
                  if (times > 60) {
                    _this.time_str = parseInt(times / 60.0) + "分" + parseInt((parseFloat(times / 60.0) - parseInt(times / 60.0)) * 60) + "秒";
                  }else{
                    _this.time_str = parseInt(times) + "秒"
                  }
                },1000)
              }else{
                Toast(data.msg);
              }
            },
            err=>{  })
        },
        getConfig(){
          this.getData('/Question/getExamConfig',{token:getStore('token')}).then(
            data=>{
              if(data.code==1){
                this.config = data.data;
              }else{
                Toast(data.msg);
              }
            },
            err=>{  })
        },
        tk(daan){
          let _this=this
                   _this.tiankongdata = []
           let bb = this.questions[this.current_question].response;

           if(bb.length>0){
             let cc = bb.split("*")

             for(var i =0; i<daan.length-1;i++){

                var json = {
                   'label': daan[i],
                   'num': cc[i].split("|")
                 }
                  _this.tiankongdata.push(json);
             }
           }else{
             for(var i =0; i<daan.length-1;i++){

                var json = {
                   'label': daan[i],
                   'num':[]
                 }
                  _this.tiankongdata.push(json);
             }
           }
          // daan.forEach(function(data,i){
          //   var str=['，','。','、',',','.'] //定义一个能够被使用的标点符号集合，这块补充全面，足以注意徐弘雯应中文英文都需要考虑的
          //   //如果是文字。就跳出，如果是标点，就放到具体的位置上面
          //   if(str.indexOf(data)>=0){
          //     //faxian标点，就把标点昂到卡暖绑定的数组相应的位置显示
          //     _this.current_question_data.response[i] = data
          //     setTimeout(function(){
          //       document.getElementById('tk'+i).disabled = true
          //     },100)
          //   }else{
          //     setTimeout(function(){
          //      document.getElementById('tk'+i).disabled = false
          //     },100)
          //   }
          // })
        },
        prevQ(){
          if (this.current_question <=0 ){
            Toast('已是第一题');
          }else{
            this.current_question--
            this.current_question_data = this.questions[this.current_question]
            if(this.current_question_data.type == 12){
              this.tk(this.current_question_data.answer.split('*'))
            }
          }
        },
        nextQ(){
          if (this.current_question >= this.questions.length - 1 ){
            Toast('已是最后一题');
          }else{
            this.current_question++
            this.current_question_data = this.questions[this.current_question]
            if(this.current_question_data.type == 12){
              this.tk(this.current_question_data.answer.split('*'))
            }
          }
        },
        responseQ(item){
          this.questions[this.current_question].response = item
          this.current_question_data = {}
          this.current_question_data = this.questions[this.current_question]
        },
        responseS(item){
          let arr = this.questions[this.current_question].response;
          if (!arr){
            this.questions[this.current_question].response = [item];
            return;
          }
          let index;
          index = arr.indexOf(item)
          if (index == -1){
            this.questions[this.current_question].response.push(item);
          }else{
            this.questions[this.current_question].response.splice(index, 1);
          }
          this.current_question_data = {}
          this.current_question_data = this.questions[this.current_question]
        },
				responseC(item){
          var str = "";
          for (let i=0;i<this.tiankongdata.length;i++){
            var aa = this.tiankongdata[i].num;
            for(var j = 0; j<aa.length;j++){
              str +=aa[j];
              str +="|";
            }
            str+="*"
             // console.log(this.tiankongdata[i].num)
          }
          this.questions[this.current_question].response = str
					// var dom = document.getElementsByClassName("tiank");
					// var currInput = dom[index];
					// var nextInput = dom[index + 1];
					// var lastInput = dom[index - 1];
					// if (el.keyCode != 8) {
					// 		if (index < (this.current_question_data.answer.length - 1)) {
					// 				nextInput.focus();
					// 		} else {
					// 				currInput.blur();
					// 		}
					// }else{
					// 		if (index !=0) {
					// 				lastInput.focus();
					// 		}
					// }
					// console.log()

				},
        goQ(index){
          this.current_question = index
          this.current_question_data = this.questions[this.current_question]
        },
        subQ(){
          // function compare(a,b){
          //   return a-b;
          // }
          let subQuestions = this.questions
          for (let i=0;i<subQuestions.length;i++){
            if  (subQuestions[i].type == 4){
              let arr = subQuestions[i].response;
              let newArr = arr;
              let res = '';
              for (let j=0; j<newArr.length;j++){
                res += subQuestions[i].content[newArr[j]];
                if (j < newArr.length -1){
                  res += '|'
                }
              }
              subQuestions[i].response = res
            }

						if (subQuestions[i].type == 12){
						  let arrT = subQuestions[i].response;
							if (typeof(arrT) == "string") {
							  subQuestions[i].response = arrT.replace(/\|/g,"")
							}
						}
          }
          if (this.config.exam_type == 1){
            this.getData('/Question/sendExam',{token:getStore('token'), content: JSON.stringify(subQuestions), id:this.id}).then(
              data=>{
                if(data.code==1){
                  if (data.data.is_standard == 1){
                    MessageBox.alert('您的考试成绩为' + data.data.score + '分，通过了本次考试', '恭喜').then(action => {
                      this.$router.push({path: '/'});
                    });
                  }else{
                    MessageBox.alert('您的考试成绩为' + data.data.score + '分，未通过本次考试', '抱歉').then(action => {
                      this.$router.push({path: '/'});
                    });
                  }
                }else{
                  Toast(data.msg);
                }
              },
              err=>{  })
          }else if(this.config.exam_type == 2){
            this.getData('/Question/sendExamBu',{token:getStore('token'), content: JSON.stringify(this.questions), id: this.exam_data.id,num:'3'}).then(
              data=>{
                if(data.code==1){
                  if (data.data.is_standard == 1){
                    MessageBox.alert('您的考试成绩为' + data.data.score + '分，通过了本次补考', '恭喜').then(action => {
                      this.$router.push({path: '/'});
                    });
                  }else{
                    MessageBox.alert('您的考试成绩为' + data.data.score + '分，未通过本次补考', '抱歉').then(action => {
                      this.$router.push({path: '/'});
                    });
                  }
                }else{
                  Toast(data.msg);
                }
              },
              err=>{  })
          }else{
            Toast('非法操作');
          }

        }
      },
      mounted(){
        this.getConfig()
      },
    }
</script>

<style lang="scss" scoped>
  .mint-header.is-fixed{
    color: #000;
    height: 5rem;
    font-size: 1.88rem;
    font-family:MicrosoftYaHei;
    font-weight:400;
    background: #fff;
  }
  .sub-button{
    font-size:1.56rem;
    font-family:MicrosoftYaHei;
    font-weight:400;
    color:rgba(0,131,255,1);
  }
  .liuyan{
    padding-top: 5rem;
    .exam-info{
      width: 80%;
      margin: 0 auto;
      text-align: left;
      font-size: 1.35rem;
      line-height: 2rem;
      >div{
        margin-bottom: 2rem;
        p{
          font-size: 1.5rem;
          &.active{
            color: #e60012;
          }
        }
      }
    }
    .pass-exam{
      width: 80%;
      margin: 10rem auto;
      text-align: center;
      font-size: 3rem;
      line-height: 6rem;
      color: #e60012;
      font-weight: bold;
    }
  }
  .lx{
    padding-bottom: 5rem;
    .lianxiTiMu{
      width: 90%;
      margin:2rem auto;
      font-size:1.56rem;
      font-family:MicrosoftYaHei;
      font-weight:400;
      text-align: left;
      line-height: 2.5rem;
      color: #333333;
      .lianxiTiMu1{
        width:4.9rem;
        line-height:1.7rem;
        color: #0375E4;
        border:0.05rem solid #0375E4;
        border-radius:1rem 0rem 1rem 0rem;
        display: inline-block;
        text-align: center;
        font-size:1.04rem;
        font-family:MicrosoftYaHei;
        font-weight:400;
      }
      .lianxiXueZe{
        color: #5E5E5E;
        width:2.5rem;
        line-height:2.5rem;
        border:0.05rem solid #5E5E5E;
        border-radius:50%;
        display: inline-block;
        font-size:1.56rem;
        font-family:ArialMT;
        font-weight:400;
        text-align: center;
        margin-right: 1rem;
        &.active{
          background: #0083FF;
					color: #fff;
					border-color: #0083FF;
        }
      }
      .lianxiXueZe1{
        color: #5E5E5E;
      }
      &.cuoti{
        color: red;
      }
			.tiankong{
				display: flex;
				flex-wrap: wrap;
				.tiank{
					width: 3rem;
					height: 3rem;
					border: 0.05rem solid #9C9C9C;
					margin: 0.5rem;
					text-align: center;
				}
			}
    }
    .lianxiBottom{
      width: 100%;
      height: 5rem;
      border-top: 0.05rem solid #9C9C9C;
      position: fixed;
      bottom: 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding:0 2rem;
      font-size:1.56rem;
      font-family:MicrosoftYaHei;
      font-weight:400;
      background: white;
      img{
        width: 1.5rem;
        height: 1.5rem;
        margin-right:0.5rem;
      }
      .lianxiBottomL{
        display: flex;
        align-items: center;
        justify-content: space-between;
        width:60%;
        div{
          padding: 0 0.5rem;
          background: #0083FF;
          color: white;
          line-height: 2rem;
          &.disable{
            background: grey;
          }
        }

      }
      .lianxiBottomR{
        color: #A5A5A5;
        span{
          color: #333333;
        }
      }
    }
  }
  .order_number{
    width: 100vw;
    display: flex;
    flex-wrap: wrap;
    >div{
      width: 10vw;
      font-size: 1.5rem;
      height: 10vw;
      line-height: 10vw;
      border: 1px solid black;
      box-sizing: border-box;
      &.active{
        background: #31a6ff;
      }
      &.error{
        background: red;
      }
    }
  }
</style>
