// pages/dati/dati.js
var Api = require('../../utils/api.js');
var util = require('../../utils/util.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nine1: true,
    item: {
      answer: [],
      con: '12',
      active: -1,
      num: '',
      add: '',
      lb_id: '',
      time: '',
      tiBtn: 0
    },
    lbCon: '',
    flag: true,
    uploadData: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var lb_con_id = wx.getStorageSync('lb_descript');
    var yanzhengid = wx.getStorageSync('yanzhengid');
    this.setData({
      lb_id: lb_con_id
    })
    var answerData = wx.getStorageSync('answerData');
    console.log(yanzhengid == lb_con_id.desc.measure_id)
    if (lb_con_id.desc.record_id == -1) {
      this.structureData_1();
    } else if (yanzhengid == lb_con_id.desc.record_id) {
      if (answerData != 0) {

        let len = Number(answerData.score.length) > 0 ? Number(answerData.score.length) : 0;
        let lbCon = wx.getStorageSync('lbCon');
        if (len == lbCon.length) {
          len = len - 1;
        }
        var item = {
          con: lbCon[len].con,
          score: lbCon[len].score,
          num: Number(len) + 1,
          answer: lbCon[len].answer,
          active: answerData.score[len],
          add: lbCon.length,
          tiBtn: 1
        }
        console.log('con')
        if (lbCon[0].answer.length > 5) {
          this.setData({
            nine1: false
          })
        }
        this.setData({
          item: item
        })
        console.log('1')
      } else {

        this.structureData_1();

      }
    } else {
      this.structureData_1();
    }


  },

  /**
   * 自定义函数--合成数据
   */
  structureData_1() {
    var lb_con = wx.getStorageSync('liangbiaoCon');
    var timeArr = [];
    wx.setStorageSync("timeArr", timeArr);
    lb_con = lb_con.res;
    var lb = lb_con[1];
    var arr = [];
    for (let j in lb) {
      var obj = {
        con: lb[j].quesion_title,
        answer: lb[j].quesion_answer.split(','),
        score: lb[j].quesion_score.split(',')
      }
      arr.push(obj)
    }
    var answerData = {
      score: [],
      answer: [],
      id: lb_con[0].measure_id
    }
    var yanzhengid = -1;
    wx.setStorageSync('answerData', answerData);
    wx.setStorageSync('yanzhengid', yanzhengid);
    var lbCon = wx.setStorageSync('lbCon', arr);
    var answerData = wx.getStorageSync('answerData');
    let len = answerData.score.length ? answerData.score.length : 0;
    // console.log(lb_con[0].measure_id)
    var item = {
      con: arr[0].con,
      add: arr.length,
      answer: arr[0].answer,
      num: 1,
      score: arr[0].score,
    }
    // console.log(arr[0].answer.length > 6)
    if (arr[0].answer.length > 5) {
      this.setData({
        nine1: false,
        lbCon: lbCon
      })
    }
    this.setData({
      item: item
    })
  },
  /**
   * 自定义函数---选择答案功能
   * 功能1--选择答案--反选  
   * 功能2--选择后进入下一题
   * 参数
   */
  selectData(e) {
    let that = this;
    var lb_con_id = wx.getStorageSync('lb_descript');
    wx.setStorageSync('yanzhengid', lb_con_id.desc.record_id);
    // 每条数据的id
    var idx = Number(e.currentTarget.dataset.id);
    // 选择的答案
    var answer = e.currentTarget.dataset.id;
    // 每个答案的分数
    var score = Number(e.currentTarget.dataset.score);
    var answerData = wx.getStorageSync('answerData');
    var lbCon = wx.getStorageSync('lbCon');
    var num = Number(this.data.item.num);
    if (Number(num) <= lbCon.length) {
      var tiBtn = 0;
      console.log(num, 'num')
      if (answerData.score.length >= num) {
        tiBtn = 1;
        answerData.score[num - 1] = score;
        answerData.answer[num - 1] = answer;
      } else if (answerData.score.length < num) {
        answerData.score.push(score);
        answerData.answer.push(answer);
        tiBtn = 0;
      }
      wx.setStorageSync('answerData', answerData);
      var ind = num - 1;
      console.log('zhele')
      var item = {
        con: lbCon[ind].con,
        answer: lbCon[ind].answer,
        active: idx,
        add: lbCon.length,
        num: num,
        score: lbCon[ind].score,
        tiBtn: tiBtn
      }
      that.setData({
        item: item
      })
      setTimeout(function() {
        that.next(num); //下一题 
      }, 100)

    }

  },
  /**
   * 自定义函数---下一题
   * 功能1--渲染当前数据  
   * 功能2--判断答题完成时提交
   * 参数
   */
  next(n) {
    let that = this;
    // n  --0开始，长度减一
    var lbCon = wx.getStorageSync('lbCon');
    var answer = wx.getStorageSync('answerData').answer;
    // n 是当前题号   
    console.log(n, "是当前题号")
    // console.log(answer.length >= n)
    // console.log(answer.length, 'answer.length')
    if (n == lbCon.length) {
      console.log('------------')
      console.log(that.data.flag)
      console.log('sc',that.data.sc)
      var item = {
        con: lbCon[n - 1].con,
        answer: lbCon[n - 1].answer,
        active: answer[n - 1],
        add: lbCon.length,
        num: n,
        score: lbCon[n - 1].score,
        tiBtn: 1
      }
      this.setData({
        item: item
      })

    } else if (n < lbCon.length) {
      console.log()
      // n = (n == lbCon.length) ? lbCon.length-1:n;
      console.log(n, 'next')
      if (answer.length == n) {
        var item = {
          con: lbCon[n].con,
          answer: lbCon[n].answer,
          active: answer[n],
          add: lbCon.length,
          num: n + 1,
          score: lbCon[n].score,
          tiBtn: 0
        }
        that.setData({
          item: item
        })
      } else if (answer.length > n) {
        var item = {
          con: lbCon[n].con,
          answer: lbCon[n].answer,
          active: answer[n],
          add: lbCon.length,
          num: n + 1,
          score: lbCon[n].score,
          tiBtn: 1
        }
        this.setData({
          item: item
        })
      }


    }
  },
  tijiao: function() {
    let that = this;
    
    var lbCon = wx.getStorageSync('lbCon');
    var answer = wx.getStorageSync('answerData').answer;
    if (this.data.flag) {
      this.setData({
        flag: false
      })
      setTimeout(function() {
        that.setData({
          flag: true
        })
      }, 10000)
      console.log("次数")
      wx.showLoading({
        title: '正在上传',
        mask:true
      })
      var startTime = wx.getStorageSync('startTime');
      var timeArr = wx.getStorageSync('timeArr');
      var chaTime = 0;
      console.log(timeArr, 'timeArr123')
      for (let i = 0; i < timeArr.length; i++) {
        if (Number(timeArr) > 1000000040000) {
          timeArr[i] = 0;
        }
        chaTime += timeArr[i]
      }
      console.log(timeArr, 'timeArr00003')
      var thisTime = Date.parse(new Date());
      var cha = thisTime - startTime + chaTime;
      console.log(cha, 'cha')
      var time = Api.reversalTime(cha)
      console.log(time)
      var user = wx.getStorageSync('user');
      var answer = wx.getStorageSync('answerData');
      for (let i = 0; i < answer.score.length; i++) {
        // console.log(typeof (answer.score[8]).toString(),'2222')
        answer.score[i] = answer.score[i].toString().replace(/[\r\n]/g, '');
      }
      var lb_descript = wx.getStorageSync('lb_descript');
      var liangbiaoCon = wx.getStorageSync('liangbiaoCon');
      var lb_tz = wx.getStorageSync('lb_tz');
      if (lb_tz == '1') {
        var data = {
          user_stime: time,
          user_answer: answer.score,
          answer: answer.answer,
          user_number: lb_descript.desc.z_openid,
          measure_id: lb_descript.id[0],
        };
        var url = Api.HOST_xinli + '/index.php/Api/add_res';
      } else {
        var data = {
          user_stime: time,
          user_answer: answer.score,
          answer: answer.answer,
          user_number: user.openid,
          measure_id: lb_descript.id[0],
        };
        var url = Api.HOST_xinli + '/index.php/Api/add_res';
      }
      data.unitid = lb_descript.desc.unitid;
      var uploadData = setTimeout(function() {
        wx.hideLoading()
        wx.showToast({
          icon: 'none',
          title: '您当前的网络不稳定，请检查网络重新提交',
          duration: 2000
        })

        that.setData({
          flag: true
        })
      }, 5000)
      wx.showToast({
        title: '上传中',
        icon: 'loading',
        duration: 2000,
        mask:true
      })
      wx.request({
        method: 'POST',
        url: url,
        data: data,
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success(res) {
          clearTimeout(uploadData)
          if (Number(res.data) == 0) {
            wx.hideToast();
            Api.alert("提交失败，请重新提交。")
            that.setData({
              flag: true
            })
            return;
          }
          var liangbiaoCon = wx.getStorageSync('liangbiaoCon');
          var data1 = {};
          var urls = Api.HOST + 'wechatIteration.php?s=Home/del_vip';
          var ti_title = liangbiaoCon.res[0].measure_name;
          var lb_descript = wx.getStorageSync("lb_descript");
          data1.g_time = lb_descript.desc.g_time || lb_descript.desc.time;
          data1.measure_name = ti_title;
          data1.res_id = res.data;
          data1.user_stime = time;
          var lb_tz = wx.getStorageSync('lb_tz');
          if (lb_tz == '1') {
            var unitid = wx.getStorageSync("unitid");
            data1.unitid = unitid;
            data1.z_openid = lb_descript.desc.z_openid;
            data1.t_openid = lb_descript.desc.t_openid;
            data1.openid = lb_descript.desc.z_openid;
            data1.is_type = 0;
            // console.log(lb_descript.desc.measure_id)
            data1.measure_id = lb_descript.id[0];
          } else {
            data1.z_openid = user.openid;
            data1.t_openid = lb_descript.desc.t_openid;
            data1.openid = user.openid;
            data1.is_type = 1;
            data1.unitid = lb_descript.desc.unitid;
            data1.measure_id = lb_descript.id[0];
          }
          Api.fetchPost(urls, data1, (err, res) => {
            if (err) {
              that.setData({
                flag: true
              })
            }
            that.setData({
              flag: true
            })
            wx.hideLoading()
            wx.removeStorageSync('answerData')
            wx.removeStorageSync('chaTime')
            wx.removeStorageSync('endTime')
            wx.removeStorageSync('startTime')
            wx.removeStorageSync('timeArr')
            wx.removeStorageSync('lbCon')
            wx.removeStorageSync('liangbiaoCon')
            // wx.removeStorageSync('lb_descript')
            // console.log(res)

            if (res == 1) {
              var lb_tz = wx.getStorageSync('lb_tz');
              var qrcode_id = wx.getStorageSync('qrcode_id')
              if (lb_tz == '1') {
                wx.reLaunch({
                  url: '/pages/info1/info1?otype=1'
                })
              } else {
                wx.reLaunch({
                  url: '/pages/info/info?otype=1&g_id=' + qrcode_id,
                })
              }
            } else if (res == 0) {
              wx.removeStorageSync('tplbDetail');
              wx.removeStorageSync('weiLb');
              let roomService =wx.getStorageSync('roomService');
              //判断是否从IM跳入
              if(roomService){
                wx.reLaunch({
                  url: `/packageA/chat/chat?t_unionid=${roomService.t_unionid}&groupID=${roomService.groupID}&orderId=${roomService.orderId}`,
                  success: function() {
                    that.setData({
                      flag: true
                    })
                    wx.removeStorageSync('roomService');
                  }
                })
              }else{
                wx.reLaunch({
                  url: '/pages/my/my',
                  success: function() {
                    that.setData({
                      flag: true
                    })
                    wx.removeStorageSync('lb_descript')
                  }
                })
              }
            }
          })
        },
        fail(e) {
          console.error(e)
        },
        complete: function(e) {
          // wx.showLoading({
          //   title: '上传中...',
          // })


        }
      })

    }
  },
  /**
   * 自定义函数---上一个
   * 功能：返回上一个
   * 
   * **/
  preve() {
    var lbCon = wx.getStorageSync('lbCon');
    var answerData = wx.getStorageSync('answerData');
    var n = Number(this.data.item.num) - 1;
    if (n > 0) {
      console.log(n, '上一题的题号')
      var item = {
        num: n,
        con: lbCon[n - 1].con,
        answer: lbCon[n - 1].answer,
        active: answerData.answer[n - 1],
        add: lbCon.length,
        score: lbCon[n].score,
      }
      if (item.num) {
        this.setData({
          item: item
        })
      }
    }

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var startTime = Date.parse(new Date());
    var cha = wx.getStorageSync('chaTime') ? wx.getStorageSync('chaTime') : 0;
    wx.setStorageSync('startTime', Number(startTime));
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    var endtTime = Date.parse(new Date());
    var startTime = wx.getStorageSync('startTime');
    // var cha = endtTime - startTime;
    var cha = Number(endtTime) - Number(startTime);
    var arr = wx.getStorageSync("timeArr");
    if (Number(cha) < 1000000040000) {
      arr.push(Number(cha))
      wx.setStorageSync("timeArr", arr);
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    var endtTime = Date.parse(new Date());
    var startTime = wx.getStorageSync('startTime');
    var cha = endtTime - startTime;
    var arr = wx.getStorageSync("timeArr");
    if (Number(cha) < 1000000040000) {
      arr.push(Number(cha))
      wx.setStorageSync("timeArr", arr);
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

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

  },

})