// pages/newAddPage/safetyBriefingLearning/index.js
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    //所有三级安全教育视频
    allVideo:{},
    // 声明一个数组,里面放着要展示的视频链接
    videoList:[],
    formatanswer:'',
    second:0,
    second_state:true,
    timer:'',

    index:0,
    answer:false,

    up:false,
    down:false,
    to:false,

    questionsData:[],
    //单独视频url
    videoUrl:'',
    videoObj:{},
    //学习时长
    learnTime:1,
    watchTimer:'',
    openId:'',
    activeState:1,
    //答案提示
    answerTip:'',
     //考试分数
    fullScore:'',
    examPaperId:'',
    //控制视频时长
    companyTimer:'',
    companyTime:0,
    projectTimer:'',
    projectTime:0,
    groupTimer:'',
    groupTime:0,
    //试题显示标识
    paperFlag:false
  },
  trainingTypeJump(e){
    var that  = this
    // this.onClickShow();
    let index = e.currentTarget.dataset.index;
    var videoList = []
    let titleName =  '';
  
    switch(index) {
      case '1':
          titleName = '公司级';
          videoList = that.data.allVideo.companyList
          break;
      case '2':
        if(that.data.companyTime < 30) {
          app.toast("温馨提示：当前视频学习完成后，方可进行下一个视频学习。");
          return;
        } else {
          if( that.data.projectTime <30) {
            var projectTimer = setInterval(() => {
              var projectTime = that.data.projectTime;
              if(projectTime >= 0 && projectTime <= 29){
                this.setData({
                  projectTime:parseInt(projectTime) + 1,
                  projectTimer:projectTimer
                })              
              }else{
                clearInterval(this.data.projectTimer);
              }
            }, 1000);
          }
          
        }
        titleName = '项目级';
        videoList = that.data.allVideo.projectList
        
        break;  
      case '3':
        if(that.data.companyTime < 30 || that.data.projectTime < 30) {
          app.toast("温馨提示：当前视频学习完成后，方可进行下一个视频学习。");
          return;
        } else {
          if(that.data.groupTime < 30) {
            var groupTimer = setInterval(() => {
              var groupTime = that.data.groupTime;
              if(groupTime >= 0 && groupTime <= 29){
                this.setData({
                  groupTime:parseInt(groupTime) + 1,
                  groupTimer:groupTimer
                })
              }else{
                clearInterval(this.data.groupTimer);
                that.setData({
                  paperFlag:true
                })
              }
            }, 1000);
          }
          
        }
        titleName = '班组级';
        videoList = that.data.allVideo.groupList
        break; 
      default:
        videoList = []   
        break
   }

    
    this.setData({
      titleName:titleName,
      activeState:index,
      videoList:videoList,
      pageNo:1,
      type:1,
      trainingType:index,
      startDate:'',
      endDate:'',
      collaborateRanksId:''
    });
    console.log(videoList)
    // this.getTrainingList();
    // this.getTrainingNumberOfPeopleCount();
  },
  //打开视频
  bindplay_click(){
    var timer = setInterval(() => {
      var second = this.data.second
      if(second == parseInt(this.data.videoObj.effectiveDuration)) {
        this.addUserRecord()
      }
      if(second > 0){
        this.setData({
          second:second - 1,
          timer:timer
        })
      }
      else{
        clearInterval(this.data.timer);
        this.setData({
          second_state:false,
        })
      }
    }, 1000);
    


    var watchTimer = setInterval(() => {
      var learnTime = this.data.learnTime;
      if(learnTime >= 0){
        this.setData({
          learnTime:parseInt(learnTime) + 1,
          watchTimer:watchTimer
        })
      }else{
        clearInterval(this.data.watchTimer);
      }
    }, 1000);


  },

  //暂停视频
  bindpause_click(){
    if(this.data.second > 0){
      clearInterval(this.data.timer);
    }
    if(this.data.learnTime > 0) {
      clearInterval(this.data.watchTimer);
    }
  },
  // 点击查看详情
chakanBtn(e){
  var data = this.data.questionsData
  var i = this.data.index
  data[i].type=true
  var tempList = data[i].answer_list
  var str = ''
  for(var j =0;j <tempList.length;j++) {
    if(data[i].correct_answer == tempList[j].letter) {
        str = tempList[j].answer;
        break;
    }
  }
  this.setData({
    questionsData:data,
    answerTip:str
  })
  },

  //选择答案
  chooseAnswer(e){
    var data = this.data.questionsData
    var i = this.data.index
    var j = e.currentTarget.dataset.j
    var item =e.currentTarget.dataset.item
    console.log(item);
   
    if(data[i].topic_state == false){
      data[i].type = true
      for(var z = 0;z<data[i].answer_list.length;z++){
        data[i].answer_list[z].answer_state = false
      }
      data[i].answer_list[j].answer_state = true

      if(data[i].correct_answer == item.letter){
        data[i].topic_state = true
        if(i < data.length-1){
          this.setData({
            index:i+1
          })
        }
        if(data.length == 1){
          this.setData({
            to:true,
          })
        }
      }
      var tempList = data[i].answer_list
      var str = ''
      for(var j =0;j <tempList.length;j++) {
        if(data[i].correct_answer == tempList[j].letter) {
            str = tempList[j].answer;
            break;
        }
      }
      this.setData({
        questionsData:data,
        answerTip:str
      })

      if(this.data.index > 0 ){
        this.setData({
          up:true,
        })
        if(this.data.questionsData.length - 1 == this.data.index &&  this.data.questionsData[this.data.index].topic_state == true){
          this.setData({
            to:true,
          })
        }
      }
    }
  },

  //点击上一题
  onClickUp(){
    var that = this
    this.setData({
      index:this.data.index - 1
    })
  
   
    if(that.data.index == 0){
      that.setData({
        up:false,
        down:true
      })
    }else{
      if(that.data.questionsData[that.data.index].topic_state == false){
        that.setData({
          up:true,
          down:false,
          to:false
        
        })
      }else{
        that.setData({
          up:true,
          down:true,
          to:false
        })
      }
    }

    var data = this.data.questionsData
    var i = this.data.index
    var tempList = data[i].answer_list
    var str = ''
    for(var j =0;j <tempList.length;j++) {
      if(data[i].correct_answer == tempList[j].letter) {
          str = tempList[j].answer;
          break;
      }
    }
    this.setData({
      answerTip:str
    })
  },

  //点击下一题
  onClickDown(){
    this.setData({
      index:this.data.index + 1
    })
    if(this.data.index == this.data.questionsData.length-1 ){
      if(this.data.questionsData[this.data.index].topic_state == false){
        this.setData({
          up:true,
          down:false,
          to:false
        })
      }else{
        this.setData({
          up:true,
          down:false,
          to:true
        })
      }
      
    }else{
      if(this.data.questionsData[this.data.index].topic_state == false){
        this.setData({
          up:true,
          down:false,
          to:false
        })
      }else{
        this.setData({
          up:true,
          down:true,
          to:false
        })
      }
    }

    var data = this.data.questionsData
    var i = this.data.index
    var tempList = data[i].answer_list
    var str = ''
    for(var j =0;j <tempList.length;j++) {
      if(data[i].correct_answer == tempList[j].letter) {
          str = tempList[j].answer;
          break;
      }
    }
    this.setData({
      answerTip:str
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    that.setData({
      openId:wx.getStorageSync('userOenId')
    })

    //获取视频链接
    that.getVideoURL(options.projectId,options.firstWorkType,options.secondWorkType)
    //获取在线答题题目信息
    that.getOnlineExamList(1,options.projectId,options.firstWorkType,options.secondWorkType);
    

      // 拿取video盒子的宽高
      /**
       * 生命周期函数--监听页面加载
       */
          // var that = this;
          // var query = wx.createSelectorQuery(); //创建节点选择器
          // //#box需要与wxml里面的id保持一致
          // query.select('#myVideo').boundingClientRect(function (rect) {
          //     console.log('00000',rect);
          //     that.setData({
          //       myVideo: rect
          //     });
          // }).exec();
    var companyTimer = setInterval(() => {
      var companyTime = this.data.companyTime;
      if(companyTime >= 0 && companyTime <= 29){
        this.setData({
          companyTime:parseInt(companyTime) + 1,
          companyTimer:companyTimer
        })
        console.log(this.data.companyTime)
      }else{
        clearInterval(this.data.companyTimer);
      }
    }, 1000);
      
          
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady(){

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  /**
   * 获取在线答题题目信息
   * @param {*} questionType 题目类型（1：安全,2施工技艺）
   */
  getOnlineExamList(questionType,projectId,firstWorkType,secondWorkType){
    var that = this
    wx.request({
      url: app.globalData.szhUrl+'/mkl/api/getOnlineExamList',
      data:{
        "questionType":questionType,
        "projectId":projectId,
        "firstWorkType":firstWorkType,
        "secondWorkType":secondWorkType
      },
      method:"GET",
      success:function(res){
        that.setData({
          questionsData:res.data,
          examPaperId:res.data[0].examPaperId == undefined ?null:res.data[0].examPaperId,
          fullScore:res.data[0].totalScore== undefined ?null:res.data[0].totalScore
        })
      }
    })
  },

  /**
   * 提交答题记录
   */
  onClickTo(){
    var that = this
    wx.request({
      url: app.globalData.szhUrl+'/mkl/api/addOnlineExamLog',
      data:{
        "openId": wx.getStorageSync('userOpenId'),
        "idCardNo": wx.getStorageSync('idCardNo'),
        "score":that.data.fullScore,
        "fullScore":that.data.fullScore,
        "examPaperId":that.data.examPaperId,
        "randomScore":Math.floor(Math.random()*10)
      },
      method:"GET",
      success:function(res){
        if(res.data.code == '200'){
          that.setData({ up:false });
          that.setData({ down:false });
          that.setData({ to:false });
          wx.redirectTo({
            url: '../letterCommitment/index'
          })
        }else{
          app.toast(res.data.msg);
        }
      }
    })
  },

 /**
   * 获取视频链接
   */
  getVideoURL(projectId,firstWorkType,secondWorkType) {
    var that = this
    wx.request({
      url: app.globalData.szhUrl+'/mkl/api/getOnlineVideoList',
      data:{
        fileType: 1,//视频
        projectId:projectId,
        firstWorkType:firstWorkType,
        secondWorkType:secondWorkType
      },
      method:"GET",
      success:function(res){
        console.log(res)
        console.log(res.data.code)
        if(res.data.code == 0) {
            that.setData({
              allVideo:res.data.data
            })
        }
        var videoList = []
       switch(that.data.activeState ) {
          case 1:
              videoList = that.data.allVideo.companyList
              break;
          case 2:
            videoList = that.data.allVideo.projectList
            break;  
          case 3:
            videoList = that.data.allVideo.groupList
            break; 
          default:
            videoList = []   
            break
       }
       that.setData({
          videoList:videoList
       })
       console.log(that.data.videoList)
        // if(res.data.length > 0) {
        //     var list = res.data
        //     let url = list[0].videoUrl;
        //     let effectiveDuration = parseInt(list[0].effectiveDuration)
        //     that.setData({
        //       videoObj:list[0],
        //       videoUrl:url,
        //       second:effectiveDuration
        //     })
        // }
        that.checkUserFinishedFlag()
      }
  })
},

  /**
   * 添加用户学习记录
   */
  addUserRecord() {
    var that = this
    var completeFlag = parseInt(that.data.learnTime) >= parseInt(that.data.videoObj.effectiveDuration == ""?0: that.data.videoObj.effectiveDuration)?1:0
    wx.request({
      url:app.globalData.szhUrl+'/mkl/api/addEducationRecord',
      data:{
        initialId:that.data.videoObj.id,
        userId:wx.getStorageSync('idCardNo'),
        openId:wx.getStorageSync('userOpenId'),
        learningDuration:that.data.learnTime,
        completeFlag:completeFlag
      },
      method:"POST",
      success:function(res){
        if(res.data.code == 0){
          console.log("添加学习记录成功！")
         }else{
          console.log("添加学习记录失败！")
         }
      }
    })
  },

  /**
   * 获取用户学习时长
   */
  getUserLearnTime() {
    this.addUserRecord() 
    this.onClickTo()
  },

  /**
   * 查询用户是否学习
   */
  checkUserFinishedFlag() {
    var that = this
    wx.request({
      url:app.globalData.szhUrl+'/mkl/api/getUserFinishList',
      data:{
        initialId:parseInt(that.data.videoObj.id),
        userId:wx.getStorageSync('idCardNo')
      },
      method:"POST",
      success:function(res){
        if(res.data.code == 0){
           if(res.data.data.length >0) {
              var obj = res.data.data[0];
              if(obj.completeFlag == "1") {
                  that.setData({
                    second_state:false
                  })
              }
           }
         }
      }
    })
  },

  
})