<style scoped>
.clearfix:after{content:".";display:block;height:0;clear:both;visibility:hidden}
.clearfix{overflow:hidden;_zoom:1;}
input{background:none;outline:none;border:0px;}
.text-gray{color:#717171;}
.text-orange{color:#eb7741;}
.text-danger{color:#c03546;}
.text-blue{color: #3A8AFB;}
.text-yellow{color:#ffd453;}
.AnswerSend{background-color: #f3f6ff;}
.timeQuestion{padding:0.2rem 3%;color:#ffd453;background-color: #fff;padding-bottom: 0.4rem;}
.timeQuestion .asQuestionLeft{float: left;padding: 0.4rem;padding-left: 1.2rem;background: url(https://release-sup8-images.oss-cn-shanghai.aliyuncs.com/h5_key/studyCenter/icon-time.png) no-repeat left center;background-size: 1rem 1rem;}
.timeQuestion .asQuestionRight{float: right;padding: 0.4rem 0;}
.asContent{padding:0 3%;padding-bottom:2rem;background-color: #fff;}
.asQuestionType,.asTitle{font-size: 0.9rem;font-weight: 600;margin: 0;}
.asTitle{line-height: 1.4rem;margin-top:0.6rem;word-wrap:break-word;}
.asSimpleInfo{cursor: pointer;display:flex;word-wrap:break-word;margin-top:0.6rem;padding-left: 1.1rem;background: url(https://release-sup8-images.oss-cn-shanghai.aliyuncs.com/h5_key/studyCenter/icon-seletedNo.png) no-repeat left 0.1rem;background-size: 1rem 1rem;}
.asSimpleInfo.selected{background-image: url(https://release-sup8-images.oss-cn-shanghai.aliyuncs.com/h5_key/studyCenter/icon-seletedOk.png);}
.asSimpleInfo span{margin-left:0.4rem;line-height: 1.4rem;}
.asSimpleInfo .asqType{max-width: 93%;}
.bcButton{flex:1;background-color:#3A8AFB;border-radius: 0;height:3rem;margin:0;}
.btnContent{height:3rem;position: absolute;bottom:0;width: 100%;display: flex;}
.btnPrev{background-color: #fff;border:1px solid #3A8AFB;}
.btnNext{color: #fff;}
.mask {position: fixed;top: 0;left: 0;height: 100%;width: 100%;background: rgba(0, 0, 0, 0.5);}
.againPopu{width: 14rem;background-color: #fff;border-radius: 0.4rem;padding:1.6rem 1rem;text-align: center;position: absolute;top: 30%;left: 50%;-webkit-transform: translate3d(-50%, -50%, 0);transform: translate3d(-50%, -50%, 0);-webkit-backface-visibility: hidden;backface-visibility: hidden;-webkit-transition: .2s ease-out;transition: .2s ease-out;}
.againPopu p{font-weight: 600;padding-bottom: 0.8rem;}
.againPopu p.text-blue{font-weight: 800;}
.againAnswer{height:2.2rem;background-color:#fff;width:80%;border:1px solid #3A8AFB;}
.closeImg{width: 2rem;height: 2rem;position: absolute;bottom: -3.2rem;margin-left:-1rem;left: 50%;}
.resultPopu{width: 70%;max-width: 18rem;background-color: #fff;border-radius: 0.4rem;padding:1.2rem 1.6rem;text-align: center;position: absolute;top: 40%;left: 50%;-webkit-transform: translate3d(-50%, -50%, 0);transform: translate3d(-50%, -50%, 0);-webkit-backface-visibility: hidden;backface-visibility: hidden;-webkit-transition: .2s ease-out;transition: .2s ease-out;}
.arContent{padding-bottom:1rem;text-align: center;background-color:#fff;border-bottom:1px solid #f3f6ff;}
.arScore{position:relative;padding-bottom: 2rem;}
.arTitle{font-weight: 600;font-size: 0.9rem;margin-bottom:1rem;word-wrap:break-word;}
.arFraction{width:7.6rem;margin:0 auto;padding: 1.8rem 0;background-color: #3A8AFB;border-radius: 50%;color:#fff;height:4rem;overflow: hidden;
/*background: url(https://release-sup8-images.oss-cn-shanghai.aliyuncs.com/h5_key/studyCenter/icon-scoreCircle.png) no-repeat left 0.1rem;background-size: 100% 100%;*/}
.arFraction span:nth-of-type(1){font-size: 3rem;}
.arFraction span:nth-of-type(2){font-size: 0.7rem;}
.arTip{width:100%;position: absolute;top:5.6rem;text-align: center;color: #fff;}
.arTip p{width:12rem;margin:0 auto;padding:0.6rem 0;padding-bottom:2.4rem;background: url(https://release-sup8-images.oss-cn-shanghai.aliyuncs.com/h5_key/studyCenter/icon-colorBar.png) no-repeat left 0.1rem;background-size: 100% 100%;}
.arGift{font-size: 0.9rem;font-weight: 600;word-wrap:break-word;}
.arIntroduction{background-color:#fff;padding:0.8rem 3%;}
.arQuestion{display: flex;}
.arQuestion p{flex:1;text-align: center;}
.arQuestion p:nth-of-type(1){text-align: left;}
.arQuestion p:nth-last-of-type(1){text-align: right;}
.resultPopu .againAnswer{width:94%;}
.arAnswerTime{text-align: left;}
</style>
<template v-cloak>     
  <div class="jfBaseSize AnswerSend" v-cloak v-bind:style="isShow.vh?'height:100vh':'height: 100%;'" > 
    <div class="timeQuestion clearfix">
      <span class="asQuestionLeft" v-html="setResponse.timeSecondsName">00:00</span>
      <span class="asQuestionRight"><span class="asQuestionLevel" v-html="(modelPaper.QuestionCount?setResponse.questionSelected+1:0)"></span><span class="asQuestionAll text-gray" v-html="'/'+(modelPaper.QuestionCount?modelPaper.QuestionCount:0)">/20</span></span>
    </div>
    <div v-for="(item,index) in setResponse.questionList" v-bind:key="item.QuestionID">
      <div class="asContent" v-if="setResponse.questionSelected==index">
        <p class="asQuestionType text-blue" v-html="item.QuestionTypeName">一、单选题</p>
        <p class="asTitle clearfix">
          {{(index+1)+'.'+item.QuestionTitle}}<span style="font-weight: 500;">(<span class="text-yellow">{{item.QuestionScore}}分</span>)</span>
        </p>
        <p class="asSimpleInfo clearfix" v-bind:class="item.selected?'selected':''" v-for="(item,qlIndex) in item.QuestionOptList" v-bind:key="item.OptionID" v-on:click="selectedChange(index,qlIndex)">
          <span class="asqType">{{item.OptionNum}}</span><span>{{item.OptionContent}}</span>
        </p>
      </div>
      <div class="btnContent">
        <mt-button class="bcButton btnPrev text-blue" v-on:click="itemChange('prev')" type="default" v-if="setResponse.questionSelected>0&&setResponse.questionSelected<setResponse.questionList.length">上一题</mt-button>
        <mt-button class="bcButton btnNext" v-on:click="itemChange('next')" type="default" v-if="setResponse.questionSelected<(setResponse.questionList.length-1)">下一题</mt-button>
        <mt-button class="bcButton btnNext" v-on:click="itemChange('submit')" type="default" v-if="setResponse.questionSelected==(setResponse.questionList.length-1)">提交答案</mt-button>
      </div>
    </div>
    
    <div class="mask" v-show="isShow.isShowMask"></div>
    <div class="againPopu" v-show="isShow.isShowAgain">
      <p class="text-blue">
        很遗憾！
      </p>
      <p>
        本次考试时间已经结束！
      </p>
      <mt-button class="againAnswer text-blue" v-on:click="repeatAnswerGO(false)" type="default">重新考试</mt-button>
      <img class="closeImg" src="http://image.supercarrier8.com/h5_key/icon-close-white.png" alt="close" v-on:click="repeatAnswerGO('S_HomeP')"> 
    </div>
    <div class="resultPopu" v-show="isShow.isShowResult">
      <div class="arContent">
        <p class="arTitle" v-html="(model.PaperName?model.PaperName:'-')"></p>
        <div class="arScore">
          <div>
            <p class="arFraction">
              <span v-html="(model.Score?model.Score:'0')"></span>
              <span>分</span>
            </p>
          </div>
          <div class="arTip">
            <p>考试成绩</p>
          </div>
        </div>
        <p class="arGift text-blue" v-html="'获得奖励：'+(model.Gift_Name?model.Gift_Name:'-')" v-if="model.PrizeId"></p>
      </div>
      <div class="arIntroduction">
        <div class="arQuestion">
          <p>题量：{{(model.QuestionCount)}}题</p>
          <p>正确：{{(model.RightCount)}}题</p>
          <p>错误：{{(model.QuestionCount-model.RightCount)}}题</p>
        </div>
        <div class="arAnswerTime">
          <p>考试用时：{{(model.AnswerTime?model.AnswerTime:'-')}}</p>
        </div>
      </div>
      <mt-button class="againAnswer text-blue" v-on:click="repeatAnswerGO(false)" type="default">重新答题</mt-button>
      <img class="closeImg" src="http://image.supercarrier8.com/h5_key/icon-close-white.png" alt="close" v-on:click="repeatAnswerGO('S_HomeP')"> 
    </div>
     <ReturnHome ref="returnhome"></ReturnHome>
  </div>
</template>
<script>
import Vue from 'vue';
import { Toast,Indicator,MessageBox } from 'mint-ui';
import channelHelper from "@/assets/js/channelHelper.js";
import '@/assets/js/libs/js.cookie';
	import ReturnHome from "@/components/channel/temp001/ReturnHome";
import utils from "@/assets/js/utils.js";
export default {
  props: [],
   components: {ReturnHome},
  provide(){       
     return{           
        goPage:this.goPage       
     }   
  },
  data() {
    return {
      isShow:{
        vh:true,
        isShowMask:false,
        isShowAgain:false,
        isShowResult:false,
        isTimeOut:true,
        isSubmit:true,
      },
      searchRequest:{
        EnterpriseNo:'',
        UserToken:'',
        LanguageType:"zh-cn",
        ID:''
      },
      modelPaper:{
        ID:'',
        AnswerRecordCount: '',
        AnswerTimeLimit: '',
        PaperFace: '',
        PaperIntro: '',
        PaperName: '',
        PaperNo: '',
        QuestionCount: 0,
      },
      model:{
        ID:'',
        PaperId:'',
        PaperName:'',
        Score:'',
        AnswerTime:'',
        QuestionCount:'',
        RightCount:'',
        PrizeId:'',
        Gift_Name:'',
        GiftType:'',
        Amount:'',
        UnitPoints:'',
        UnitMoney:'',
      },
      setResponse:{
        questionSelected:0,
        timeSeconds:0,
        timeSecondsName:'00:00:00',
        timeSecondsAll:0,
        questionList:[],
      },
    }
  },
  methods: {
    goPage(pagetype){
        this.$parent.changeSelectedPage(pagetype);
    },
    startAnswer(){
    },
    //试卷信息
    H5GetTestPaperInfo(){
      var that=this;
      var url = "/channel/H5GetTestPaperInfo";
      var dataParams = that.searchRequest;
      Indicator.open();
      var cbSuccess = function(res){
        if (res.flag) {
          var data=res.data;
          var AnswerTimeLimit=parseInt(data.AnswerTimeLimit);
          that.$set(that.setResponse,'timeSecondsAll',AnswerTimeLimit*60+1);
          that.$set(that.setResponse,'timeSeconds',AnswerTimeLimit*60);
          that.timeChange();
          that.$set(that,'modelPaper',data);
        }else
        { 
            Toast(res.msg);
        }
        Indicator.close();
      };
      var cbError = function(jqXHR, textStatus, errorThrown){
        Toast(jqXHR.responseText);
      };
      //请求后端
      channelHelper.CommonCallService(url,dataParams,cbSuccess,cbError,null,null);
    },
    //获取试卷所有题目信息
    H5GetPaperQuestionList(){
      var that=this;
      var url = "/channel/H5GetPaperQuestionList";
      var dataParams = that.searchRequest;
      Indicator.open();
      var cbSuccess = function(res){
        if (res.flag) {
          var data=res.data;
          if(data&&data.length>0){
            for(var i=0;i<data.length;i++){
              var item=data[i];
              var arrList=new Array((item.QuestionType=='3'?2:4));
              for(var j=0;j<item.QuestionOptList.length;j++){
                var QuestionOptList=item.QuestionOptList[j];
                QuestionOptList['selected']=false;
                if(QuestionOptList.OptionNum=='A'){
                  arrList[0]=QuestionOptList;
                }else if(QuestionOptList.OptionNum=='B'){
                  arrList[1]=QuestionOptList;
                }else if(QuestionOptList.OptionNum=='C'){
                  arrList[2]=QuestionOptList;
                }else{
                  arrList[3]=QuestionOptList;
                }
              }
              if(data[i].QuestionType=='1'){
                data[i]['QuestionTypeName']='一、单选题';
              }else if(data[i].QuestionType=='2'){
                data[i]['QuestionTypeName']='二、多选题';
              }else{
                data[i]['QuestionTypeName']='三、判断题';
              }
              // debugger
              // data[i]['QuestionNum']=that.toChinesNum(i+1);
              // console.log(data[i].QuestionNum);
              data[i].QuestionOptList=arrList;
            }
          }
          that.$set(that.setResponse,'questionList',data);
        }else
        { 
            Toast(res.msg);
        }
        Indicator.close();
      };
      var cbError = function(jqXHR, textStatus, errorThrown){
        Toast(jqXHR.responseText);
      };
      //请求后端
      channelHelper.CommonCallService(url,dataParams,cbSuccess,cbError,null,null);
    },
    selectedChange(index,qlIndex){
      var that=this;
      var questionList=that.setResponse.questionList[index];
      var questionOptList=questionList.QuestionOptList;
      if(questionList.QuestionType=='1'||questionList.QuestionType=='3'){
        questionOptList.forEach((e,i) => {
          questionOptList[i].selected=false;
          if(qlIndex==i){
            questionOptList[i].selected=true;
          }
        });
      }else if(questionList.QuestionType=='2'){
        questionOptList[qlIndex].selected=!questionOptList[qlIndex].selected;
      }
    },
    timeChange(){
      var that=this;
      if(that.isShow.isTimeOut){
        var timeSecondsAll=that.setResponse.timeSecondsAll-1;
        that.$set(that.setResponse,'timeSecondsAll',timeSecondsAll);
        var str=that.fmtTime(timeSecondsAll);
        that.$set(that.setResponse,'timeSecondsName',str);
        if(that.setResponse.timeSecondsAll>0){
          setTimeout(() => {
            that.timeChange();
          }, 1000);
        }else{
          that.$set(that.isShow,'isShowMask',true);
          that.$set(that.isShow,'isShowAgain',true);
        }
      }
    },
    fmtTime:function(timeData){
      var mm=parseInt(timeData/60);
      var second=parseInt(timeData%60);
      var hh=parseInt(mm/60);
      mm=parseInt(mm%60);
      var str='';
      if(hh<10){
        str+='0'+hh+':';
      }else{
        str+=hh+':';
      }
      if(mm<10){
        str+='0'+mm+':';
      }else{
        str+=mm+':';
      }
      if(second<10){
        str+='0'+second;
      }else{
        str+=second;
      }
      return str;
    },
    itemChange(type){
      var that=this;
      var index=that.setResponse.questionSelected;
      if(type=='prev'){
        that.$set(that.setResponse,'questionSelected',index-1);
      }else{
        var questionList=that.setResponse.questionList[index];
        var questionOptList=questionList.QuestionOptList;
        var selected=false;
        questionOptList.forEach((e,i) => {
          if(e.selected==true){
            selected=true;
          }
        });
        if(!selected){
          Toast('请完成题目！');
        }else{
          if(type=='next'){
            that.$set(that.setResponse,'questionSelected',index+1);
          }else{
            that.$set(that.isShow,'isTimeOut',false);
            MessageBox.confirm('是否确定提交答案？','提示',{closeOnClickModal:false}).then(()=>{
              that.H5SubmitTestPaper();
            }).catch(() => {
              that.$set(that.isShow,'isTimeOut',true);
              that.timeChange();
            });
          }
        }
      }
    },
    H5SubmitTestPaper(){
      var that=this;
      if(that.isShow.isSubmit){
        that.$set(that.isShow,'isSubmit',false);
      }else{
        return;
      }
      Indicator.open();
      var url = "/channel/H5SubmitTestPaper";
      var dataParams = that.searchRequest;
      dataParams['PaperId']=that.searchRequest.ID;
      dataParams['AnswerTime']=that.fmtTime(that.setResponse.timeSeconds-that.setResponse.timeSecondsAll);
      dataParams['AnswerStatus']=1;
      var QuestionList=[];
      that.setResponse.questionList.forEach(e => {
        var list=[];
        e.QuestionOptList.forEach(item => {
          if(item.selected){
            list.push(item.OptionID);
          }
        });
        QuestionList.push(
          {
            QuestionID:e.QuestionID,
            OptionIDList:list,
          }
        );
      });
      dataParams['QuestionListStr']=JSON.stringify(QuestionList);
      var cbSuccess = function(res){
        if (res.flag) {
          var data=res.data;
          // sessionStorage.setItem('S_AnswerSendResultId',data);
          // that.goPage("S_AnswerR");
          
          that.H5GetPaperAnswerRecord(data);
        }else
        { 
          Toast(res.msg);
          that.$set(that.isShow,'isSubmit',true);
          that.$set(that.isShow,'isTimeOut',true);
          that.timeChange();
          Indicator.close();
        }
      };
      var cbError = function(jqXHR, textStatus, errorThrown){
        Indicator.close();
        that.$set(that.isShow,'isSubmit',true);
        Toast(jqXHR.responseText);
      };
      //请求后端
      channelHelper.CommonCallService(url,dataParams,cbSuccess,cbError,null,null);
    },
    repeatAnswerGO(url){
      var that=this;
      var S_AnswerSendRepeatId=that.searchRequest.ID;
      sessionStorage.setItem('S_AnswerSendRepeatId',url?url:S_AnswerSendRepeatId);
      that.$router.go(-1);
    },
    //结果
    H5GetPaperAnswerRecord(id){
      var that=this;
      var url = "/channel/H5GetPaperAnswerRecord";
      var dataParams ={
        EnterpriseNo:that.searchRequest.EnterpriseNo,
        UserToken:that.searchRequest.UserToken,
        LanguageType:that.searchRequest.LanguageType,
        ID:id
      };
      Indicator.open();
      var cbSuccess = function(res){
        if (res.flag) {
          var data=res.data;
          if(data&&data.ID){
            if(data.PrizeId){
              if(data.GiftType==2){
                if(data.Amount&&data.UnitMoney){
                  data.Gift_Name=Number(data.Amount)*Number(data.UnitMoney)+'元红包';
                }else{
                  data.Gift_Name='0元红包';
                }
              }else if(data.GiftType==4){
                if(data.Amount&&data.UnitPoints){
                  data.Gift_Name=parseInt(data.Amount)*parseInt(data.UnitPoints)+'积分';
                }else{
                  data.Gift_Name='0积分';
                }
              }
            }
            that.$set(that,'model',data);
            that.$set(that.isShow,'isShowMask',true);
            that.$set(that.isShow,'isShowResult',true);
          }else{
            Toast('未获取到相关记录，请稍后重试');
          }
        }else
        { 
            Toast(res.msg);
        }
        Indicator.close();
      };
      var cbError = function(jqXHR, textStatus, errorThrown){
        Toast(jqXHR.responseText);
      };
      //请求后端
      channelHelper.CommonCallService(url,dataParams,cbSuccess,cbError,null,null);
    },
  //   toChinesNum(num){
  //     let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']; 
  //     let unit = ["", "十", "百", "千", "万"];
  //     num = parseInt(num);
  //     let getWan = (temp) => {
  //   　　let strArr = temp.toString().split("").reverse();
  //   　　let newNum = "";
  //   　　for (var i = 0; i < strArr.length; i++) {
  //     　　newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
  //     　}
  //       return newNum;
  //     }
  //     let overWan = Math.floor(num / 10000);
  //     let noWan = num % 10000;
  //     if (noWan.toString().length < 4) {
  // 　　　　　　noWan = "0" + noWan;
  // 　　　 }
  //     return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
  //   },
    judgeLogin:function(){
      var eno = this.sup8.context.enterpriseno;
      if (!channelHelper.CheckLogin(this.$parent,eno,this.sup8.context.entranceid)) {
        this.$parent.changeSelectedPage('Key_Login');
        return false;
      }
    },
  },
  watch: {},
  created: function() {
    var that = this;
    //判断是否登录
    that.judgeLogin();
    var ID=sessionStorage.getItem('S_AnswerSendQuestionId');
    // var prevPage=sessionStorage.getItem('prevPage');
    if(ID){
      // sessionStorage.setItem('prevPage',ID);
      that.$set(that,'model',ID);
      that.$set(that,'searchRequest',{
        EnterpriseNo:this.sup8.context.enterpriseno,
        UserToken:channelHelper.GetUserToken(),
        LanguageType:"zh-cn",
        ID:ID
      });
      that.H5GetTestPaperInfo();
      that.H5GetPaperQuestionList();
      sessionStorage.removeItem('S_AnswerSendQuestionId');
    }
    // else if(prevPage){
    //   that.goPage('S_AnswerD');
    // }
    //监控浏览器返回事件
    // setTimeout(function() {
    //     window.addEventListener("popstate", function(e) {
    //       MessageBox.confirm('返回后此答题无效，确定返回？').then(()=>{

    //       }).catch(() => {
    //         e.preventDefault();
    //         e.stopPropagation();
    //       });
    //     },true);
    //   }, 50);
  },
  mounted: function() {
    var that =this;
    var isDesign = location.pathname.indexOf('design');
    if (!(isDesign>-1)) {
        that.$set(that.isShow,'vh',true);
    }else{
        that.$set(that.isShow,'vh',false);
    }
  }
};
</script>

