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

  /**
   * 页面的初始数据
   */
  data: {
    sc: true,
    bjsrc: Api.HOST_P + 'xinli/Public/public/images/60/raven_answer/border.png',
    six: 1,
    arr: {
      src: '',
      answer: []
    },
    sty: -1,
    flag: true,
    tiBtn: 0,
    nextFlag: true,
    uploadData: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var s = Api.HOST_P + 'xinli/Public/public/images/60/raven_answer/border.png';
    console.log(s, 's')
    var answerData_rw = wx.getStorageSync('answerData_rw');
    var lb_rw = wx.getStorageSync('lb_rw');
    var liangbiaoCon = wx.getStorageSync("liangbiaoCon");
    var liangbiaoCon1 = liangbiaoCon.res[1];
    var bjsrc = ""
    if (liangbiaoCon.res[0].measure_id == 442) {
      bjsrc = Api.HOST_P + 'xinli/Public/public/images/442/raven_answer/border.png'
    } else if (liangbiaoCon.res[0].measure_id == 60) {
      bjsrc = Api.HOST_P + 'xinli/Public/public/images/60/raven_answer/border.png'
    }
    this.setData({
      bjsrc: bjsrc
    })
    var yanzhengid3 = wx.getStorageSync("yanzhengid3");
    var lb_descript = wx.getStorageSync("lb_descript");
    if (lb_descript.desc.record_id == -1) {
      this.loadData();
    } else if (yanzhengid3 == lb_descript.desc.record_id) {
      if (answerData_rw == '') {
        this.loadData();
      } else {
        let n = answerData_rw.score.length < lb_rw.length ? answerData_rw.score.length : lb_rw.length - 1;
        var len = lb_rw[n].answer.length == 6 ? 1 : 2;
        // 最后一题
        if (answerData_rw.answer.length == liangbiaoCon.res[1].length) {
          this.setData({
            tiBtn: 1
          })

        }
        this.setData({
          arr: lb_rw[n],
          sty: answerData_rw.answer[n],
          six: len
        })

      }
    } else {
      this.loadData();
    }


    wx.setNavigationBarTitle({
      title: liangbiaoCon.res[0].measure_name
    });
  },

  selectAnswer(e) {
    let that = this;
    var lb_descript = wx.getStorageSync('lb_descript');
    wx.setStorageSync('yanzhengid3', lb_descript.desc.record_id);
    var answerData_rw = wx.getStorageSync('answerData_rw');
    var lb_rw = wx.getStorageSync('lb_rw');
    // var idn = e.currentTarget.dataset.idn;
    var num = e.currentTarget.dataset.num;
    var answer = e.currentTarget.dataset.answer;
    var score = e.currentTarget.dataset.score;
    console.log(num, 'idnidnidn')
    this.setData({
      num: num
    })
    if (lb_rw[Number(num) - 1].answer.length)
      var len = lb_rw[Number(num) - 1].answer.length == 6 ? 1 : 2;
    // 避免点击过快导致报错
    if (lb_rw.length >= answerData_rw.score.length) {
      if (Number(num) > answerData_rw.score.length) {
        answerData_rw.score.push(score);
        answerData_rw.answer.push(answer);
      } else {
        answerData_rw.score[Number(num) - 1] = score;
        answerData_rw.answer[Number(num) - 1] = answer;
      }
      wx.setStorageSync('answerData_rw', answerData_rw)
    }
    this.setData({
      // arr: lb_rw[num],
      sty: answer,
      six: len
    })
    if (this.data.nextFlag) {
      this.setData({
        nextFlag: false
      })
      that.next(Number(num));
      setTimeout(function () {
        that.setData({
          nextFlag: true
        })
      }, 500)
    }

  },
  next: function (e) {
    console.log(e)
    let that = this;
    var lb_rw = wx.getStorageSync('lb_rw');
    var answerData_rw = wx.getStorageSync('answerData_rw');

    if (lb_rw.length <= answerData_rw.score.length) {
      console.log(this.data.num < lb_rw.length, '1')
      if (this.data.num < lb_rw.length) {
        var len = lb_rw[e].answer.length == 6 ? 1 : 2;
        this.setData({
          arr: lb_rw[e],
          sty: answerData_rw.answer[e],
          six: len,
          tiBtn: 0
        })
      }
      this.setData({
        tiBtn: 1
      })
      // 发送请求
    } else {
      console.log(2)
      var len = lb_rw[e].answer.length == 6 ? 1 : 2;
      if (Number(e) < answerData_rw.score.length) {
        console.log(3)
        this.setData({
          arr: lb_rw[e],
          sty: answerData_rw.answer[e],
          six: len,
          tiBtn: 0
        })
      } else {
        console.log(4)
        this.setData({
          arr: lb_rw[e],
          sty: -1,
          six: len,
          tiBtn: 0
        })
      }
    }
  },
  tijiao: function () {
    let that = this;
    that.setData({
      sc: false
    })
    if (this.data.flag) {
      this.setData({
        flag: false
      })
      // setTimeout(function () {
      //   that.setData({
      //     flag: true
      //   })
      // }, 10000)

      // 计算答题时间
      var startTime2 = wx.getStorageSync('startTime2');
      var timeArr2 = wx.getStorageSync('timeArr2');
      var chaTime2 = 0;
      for (let i = 0; i < timeArr2.length; i++) {
        if (Number(timeArr2) > 1000000040000) {
          timeArr2[i] = 0;
        }
        chaTime2 += timeArr2[i]
      }
      var thisTime = Date.parse(new Date());
      var cha = thisTime - startTime2 + chaTime2;
      console.log(cha, 'cha')
      var time = Api.reversalTime(cha)
      console.log(time, 'time')
      var liangbiaoCon = wx.getStorageSync('liangbiaoCon');
      var answer = wx.getStorageSync('answerData_rw');
      var user = wx.getStorageSync('user');
      var lb_descript = wx.getStorageSync('lb_descript');
      if (liangbiaoCon.talp == '1') {
        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';
      } 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.showLoading({
        title: '上传中...',
        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.hideLoading();
            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;
          console.log(res, 'res-id')
          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;
            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.removeStorageSync('answerData_rw')
            wx.removeStorageSync('chaTime2')
            wx.removeStorageSync('endTime')
            wx.removeStorageSync('startTime2')
            wx.removeStorageSync('timeArr2')
            wx.removeStorageSync('lbCon')
            wx.removeStorageSync('liangbiaoCon')

            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',
                  success: function () {
                    that.setData({
                      flag: true
                    })
                  }
                })
              } else {
                wx.reLaunch({
                  url: '/pages/info/info?otype=1&g_id=' + qrcode_id,
                  success: function () {
                    that.setData({
                      flag: true
                    })
                  }
                })
              }
            } 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) {



        }

      })
    }
  },
  preve: function (e) {
    var num = e.currentTarget.dataset.num;
    num = Number(num) - 2;
    var lb_rw = wx.getStorageSync('lb_rw');
    var answerData_rw = wx.getStorageSync('answerData_rw');
    var len = lb_rw[num].answer.length == 6 ? 1 : 2;

    this.setData({
      arr: lb_rw[num],
      sty: answerData_rw.answer[num],
      six: len
    })
  },
  downloadImg: function (c, n) {
    // var arr = [];
    // for(let i=n;i<10;i++){

    wx.downloadFile({
      url: c, //仅为示例，并非真实的资源
      success: function (res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          // arr[i] = ;
          // arr.push(res.tempFilePath)
          // console.log(arr, 'sdsdsds')
          return res.tempFilePath
        }
      }
    })
    // }
    // if(arr.length!=0){
    //   // console.log(arr,'sdsdsds')
    //   return arr;
    // }

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

    var startTime2 = Date.parse(new Date());
    var cha = wx.getStorageSync('chaTime2') ? wx.getStorageSync('chaTime2') : 0;
    wx.setStorageSync('startTime2', Number(startTime2));
  },

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

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

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

  },

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

  },
  loadData: function () {
    var timeArr2 = [];
    wx.setStorageSync("timeArr2", timeArr2);
    let data = wx.getStorageSync('liangbiaoCon');
    wx.setStorageSync("yanzhengid3", -1);
    let rwData = data.res[1];
    var arr = [];
    if (data.res[0].measure_id == 442) {
      var host = Api.HOST_P + 'xinli/Public/public/images/442/raven_question/';
      // console.log(host)
      var host1 = Api.HOST_P + "xinli/Public/public/images/442/raven_answer/";
    } else if (data.res[0].measure_id == 60) {
      var host = Api.HOST_P + 'xinli/Public/public/images/60/raven_question/';
      var host1 = Api.HOST_P + "xinli/Public/public/images/60/raven_answer/";
    }
    for (let i = 0; i < rwData.length; i++) {
      // console.log(host,rwData[i].quesion_title)
      var obj = {
        src: this.imgLink(rwData[i].quesion_title, host),
        // src: this.downloadImg(d[i],0),
        answer: (host1 + rwData[i].quesion_answer).replace(/,/g, "," + host1).split(","),
        score: rwData[i].quesion_score.split(","),
        all: rwData.length,
        num: i + 1
      }
      // console.log(obj,'obj')
      arr.push(obj);
    }
    var answerData = {
      answer: [],
      score: []
    }
    console.log(arr, 'arr')
    wx.setStorageSync('lb_rw', arr);
    wx.setStorageSync('answerData_rw', answerData)
    if (arr[0].answer.length == 6) {
      this.setData({
        six: 1
      })
    } else {
      this.setData({
        six: 0
      })
    }
    var timeArr2 = [];
    wx.setStorageSync("timeArr2", timeArr2);
    this.setData({
      arr: arr[0]
    })
  },
  imgLink: function (str, host) {
    return (host + str);
  },

})