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

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    winH: '',
    winW: '',
    disab: true,
    current: 1,
    flag: true,
    animationData: {},
    item: {
      answer: [],
      con: '',
      active: -1,
      num: '',
      add: '',
      lb_id: '',
      time: '',
    },
    nextFalg: {},
    lifeName: lifeEvent.lifeName,
    eName: lifeEvent.lifeEventName[0],
    lifeNum: 0,
    lifeArr: lifeEvent.lifeArr,
    track: [], //答题轨迹
  },
  onLoad: function(options) {
    let that = this;
    var otype = options.otype;
    var answer_swiper = wx.getStorageSync('answer_swiper');
    var swiper_arr = wx.getStorageSync('swiper_arr');
    var lb_descript = wx.getStorageSync('lb_descript');
    var yanzhengid = wx.getStorageSync('yanzhengid');
    let len = answer_swiper != '' ? (answer_swiper.answer.length < swiper_arr[1].length ? answer_swiper.answer.length : swiper_arr[1].length - 1) : 0;
    if (false) {} else {
      if (lb_descript.desc.record_id == -1) {
        this.loadData();
      } else if (yanzhengid == lb_descript.desc.record_id) {
        if (len > 0) {
          var item = swiper_arr[1][len];
          var nextFalg = this.data.nextFalg;
          // 处理最后一题的选择问题
          if (swiper_arr[1].length == answer_swiper.answer.length) {
            var last_len = swiper_arr[1].length - 1; // 最后一题序号
            var ind_len = answer_swiper.answer[last_len].split('-'); // 最后答案
            var con_len = swiper_arr[1][last_len].score; //  最后问题的答案
            for (let i = 0; i < con_len.length; i++) {
              (function(j) {
                if (ind_len[0] == j) {
                  that.setData({
                    active: j,
                    disab: false,
                    nextFalg: nextFalg
                  })
                }
              })(i)
            }
          }
          this.setData({
            item: item,
            current: len,
            all: swiper_arr[1].length,
            nextFalg: nextFalg,
          })
        } else {
          this.loadData();
        }
      } else {
        this.loadData();
      }
    }
  },
  loadData: function() {
    var lb_swiper_con = wx.getStorageSync('lb_swiper_con');
    var lb = lb_swiper_con[1];
    var arr = [];
    var an = ['A.', 'B.', 'C.', 'D.', 'E.', 'F.', 'G.', 'H.', 'I.'];
    let zimu = [];
    for (let j in lb) {
      let le = lb[j].quesion_answer.split(',').length;
      var obj = {
        con: lb[j].quesion_title,
        answer: lb[j].quesion_answer.split(','),
        score: lb[j].quesion_score.split(','),
        check: [],
        zimu: an,
        type: lb[j].type
      }
      obj.check.length = obj.answer.length;
      for (let i = 0; i < obj.answer.length; i++) {
        obj.check[i] = 0;
      }
      arr.push(obj)
    }
    var swiper_arr = [lb_swiper_con[0], arr];
    wx.setStorageSync('swiper_arr', swiper_arr);
    var lb_swiper_con = wx.getStorageSync('lb_swiper_con');
    var answerData = {
      score: [],
      answer: [],
      id: lb_swiper_con[0].measure_id
    }
    var yanzhengid = -1;
    wx.setStorageSync('answer_swiper', answerData);
    let answerPer = {
      score: [],
      answer: [],
    }
    wx.setStorageSync('answerPer', answerPer);
    wx.setStorageSync('yanzhengid', yanzhengid);
    var timeArr = [];
    wx.setStorageSync("timeArr", timeArr);
    // wx.removeStorageSync('lb_swiper_con')
    var item = swiper_arr[1][0];
    var nextFalg = {
      0: false
    }
    this.setData({
      all: arr.length,
      current: 0,
      item: item,
      nextFalg: nextFalg
    });
    wx.setNavigationBarTitle({
      title: swiper_arr[0].measure_name
    });
  },
  selectData: function(e) {
    let that = this;
    var qufentime = wx.getStorageSync('qufentime');
    var lb_descript = wx.getStorageSync('lb_descript');
    wx.setStorageSync('yanzhengid', lb_descript.desc.record_id);
    // var lb_swiper_con = wx.getStorageSync('lb_swiper_con');
    var swiper_arr = wx.getStorageSync('swiper_arr');
    var answer_swiper = wx.getStorageSync('answer_swiper');
    let len = swiper_arr[1].length;
    var record = e.currentTarget.dataset.record;
    var index = e.currentTarget.dataset.index; // 序号，
    // var answer = e.currentTarget.dataset.answer;
    var score = e.currentTarget.dataset.score; // 分数
    var nextFalg = this.data.nextFalg;
    nextFalg[record] = true;
    this.setData({
      nextFalg: nextFalg,
    })
    // 判断题长度
    if (record < Number(len) - 1) {
      // 多选判断
      this.setData({
        active: index,
        all: len,
        current: Number(record)
      })
      this.checkAnswer(score, index, function(checkA) {
        if (checkA.type == 0) {
          that.cacheAnser(checkA.obj, record);
          setTimeout(() => {
            that.next(record);
          }, 300)
        }
      });
    } else {
      let anCurArr = wx.getStorageSync('answer_swiper').answer[that.data.current];
      if (!anCurArr) anCurArr = '';
      anCurArr = anCurArr.split('-');

      if (anCurArr.length == 5 || anCurArr[3] == 0) {
        wx.showToast({
          title: '量表已做完，请提交',
          icon: 'none',
          duration: 1000
        })
        if (anCurArr.length == 5){
          this.setData({
            eName: lifeEvent.lifeArr.impactConTimeArr.title,
          })
        }
        if (anCurArr[3] == 0){
          this.setData({
            eName: lifeEvent.lifeArr.spiritDegreeArr.title,
          })
        }
        return;
      } else {
        this.setData({
          active: index,
          all: len,
          current: Number(record)
        })
        this.checkAnswer(score, index, function(checkA) {
          if (checkA.type == 0) {
            that.cacheAnser(checkA.obj, record);
            let _len = checkA.obj.s.split('-');
            if (_len.length == 5) {
              that.setData({
                eName: lifeEvent.lifeArr.impactConTimeArr.title,
              })
            }
            if (_len.length == 3) {
              that.setData({
                eName: lifeEvent.lifeArr.spiritDegreeArr.title,
              })
            }
            wx.showToast({
              title: '量表已做完，请提交',
              icon: 'none',
              duration: 1000
            })
            that.setData({
              active: index,
              // active: -1,
              all: len,
              current: Number(record),
              disab: false,
            })
          }
        });
      }
    }
  },
  checkAnswer(score, index, back) {
    console.log("score",score,"index",index,"back",back);
    let answerPer = wx.getStorageSync('answerPer');
    let lifeNum = this.data.lifeNum;
    let answerArr = answerPer.answer;
    let scoreArr = answerPer.score;
    let track = this.data.track;
    answerArr.push(index);
    scoreArr.push(score);
    let jsonArr = {};
    if (score == 0) { // 未发生|| 一年前
      this.setData({
        lifeNum: 0,
        track: [],
      })
      answerPer.answer = answerPer.score = [];
      wx.setStorageSync('answerPer', answerPer);
      jsonArr = lifeEvent.lifeArr.happenTimeArr;
      this.changeCon(jsonArr, 1);
      let obj = {
        'type': 0,
        'obj': {
          a: answerArr.join('-'),
          s: scoreArr.join('-')
        }
      }
      back(obj)
      return;
    } else { // 一年内
      track.push(index);
      lifeNum++;
      this.setData({
        track: track
      })
      if (track.length == 1) { // 第一次点击 区分一年内和长期性
        if (score == 1) {
          jsonArr = lifeEvent.lifeArr.happenNumArr;
        } else if (score == 2) {
          jsonArr = lifeEvent.lifeArr.continusTimeArr;
        }
      } else
      if (track.length == 2) {
        jsonArr = lifeEvent.lifeArr.natureArr;
      }
      if (track.length == 3) {
        jsonArr = lifeEvent.lifeArr.spiritDegreeArr;
      }
      if (track.length == 4) {
        jsonArr = lifeEvent.lifeArr.impactConTimeArr;
      }
      if (track.length == 5) {
        this.setData({
          lifeNum: 0,
          track: [],
        })
        answerPer.answer = answerPer.score = [];
        wx.setStorageSync('answerPer', answerPer);
        jsonArr = lifeEvent.lifeArr.happenTimeArr;
        lifeEvent.lifeArr
        this.changeCon(jsonArr, 1);
        let obj = {
          'type': 0,
          'obj': {
            a: answerArr.join('-'),
            s: scoreArr.join('-')
          }
        }
        back(obj)
        return;
      }
      this.setData({
        lifeNum: lifeNum,
      })
      setTimeout(() => {
        if (!jsonArr.title) return;
        this.changeCon(jsonArr);
      }, 200)
      answerPer.answer = answerArr;
      answerPer.score = scoreArr;
      wx.setStorageSync('answerPer', answerPer);
      let obj = {
        'type': 1,
        'obj': {
          a: answerArr.join('-'),
          s: scoreArr.join('-')
        }
      }
      back(obj)
      return;
    }
  },
  // 
  changeCon(j, n) {
    let item = this.data.item;
    item.answer = j.name;
    item.score = j.score;
    if (n && n == 1) {
      this.setData({
        eName: j.title,
        // active: -1
      })
    } else {
      let anCurArr = wx.getStorageSync('answer_swiper').answer[this.data.current];
      if (!anCurArr) anCurArr = '';
      anCurArr = anCurArr.split('-');
      if (anCurArr[this.data.lifeNum]) {
        this.setData({
          item: item,
          eName: j.title,
          active: anCurArr[this.data.lifeNum]
        })
      } else {
        this.setData({
          item: item,
          eName: j.title,
          active: -1
        })
      }

    }
  },
  // 存储答案   n   
  cacheAnser(n, record) {
    var answer_swiper = wx.getStorageSync('answer_swiper');
    if (answer_swiper.score.length <= record) {
      answer_swiper.score.push(n.s);
      answer_swiper.answer.push(n.a);
    } else {
      answer_swiper.score[record] = n.s;
      answer_swiper.answer[record] = n.a;
    }
    wx.setStorageSync('answer_swiper', answer_swiper);
  },
  prev: function(e) {
    if (this.data.current > 0) {
      var record = this.data.current - 1;
      this.prevAnimation();
      var swiper_arr = wx.getStorageSync('swiper_arr');
      let len = swiper_arr[1].length;
      var answer_swiper = wx.getStorageSync('answer_swiper');
      var item = swiper_arr[1][record];
      var nextFalg = this.data.nextFalg;
      nextFalg[record] = true;
      let anserCacheArr = answer_swiper.answer[Number(record)].split('-');
      // 多选题 的数据状态
      this.setData({
        active: anserCacheArr[0],
        current: record,
        item: item,
        nextFalg: nextFalg,
        eName: lifeEvent.lifeArr.happenTimeArr.title,
        lifeNum: 0,
        track: [],
      })
    }

  },

  next: function(n) {
    var answer_swiper = wx.getStorageSync('answer_swiper');
    if (answer_swiper.answer[n].length <= 0) {
      wx.showToast({
        title: '请选择',
        icon: 'none',
        duration: 1000
      });
      return;

    }
    var swiper_arr = wx.getStorageSync('swiper_arr');
    let len = swiper_arr[1].length;
    if (n < len) {
      // this.nextAnimation();
      var item = swiper_arr[1][n + 1]
      var answer_swiper = wx.getStorageSync('answer_swiper');
      var an_len = answer_swiper.answer ? answer_swiper.answer.length : -1;
      if (an_len - n > 1) {
        let anserCacheArr = answer_swiper.answer[n + 1].split('-');
        this.setData({
          active: anserCacheArr[0],
          // active: -1,
          item: item,
          all: len,
          current: n + 1
        })
      } else {
        this.setData({
          active: -1,
          item: item,
          all: len,
          current: n + 1
        })
      }
    } else if (n == len) {} else {
    }

  },
  nextAnimation: function() {
    var that = this;
    var _thisWidth = Number(this.data.winW);
    var animation = wx.createAnimation({
      duration: 400,
      timingFunction: 'linear',
    })
    this.animation = animation
    animation.left(-_thisWidth).opacity(0).step();
    this.setData({
      animationData: animation.export()
    })
    setTimeout(function() {
      var animation1 = wx.createAnimation({
        duration: 0,
        timingFunction: 'step-start',
      })
      that.animation = animation1
      animation1.left(_thisWidth / 2).opacity(1).step();
      that.setData({
        animationData: animation1.export()
      })
    }, 410)
  },
  prevAnimation: function() {
    var that = this;
    var _thisWidth = Number(this.data.winW);
    var animation = wx.createAnimation({
      duration: 300,
      timingFunction: 'linear',
    })
    this.animation = animation
    animation.left(_thisWidth * 2).opacity(1).step();
    this.setData({
      animationData: animation.export()
    })
    setTimeout(function() {
      var animation1 = wx.createAnimation({
        duration: 0,
        timingFunction: 'step-start',
      })
      that.animation = animation1
      animation1.left(_thisWidth / 2).opacity(1).step();
      that.setData({
        animationData: animation1.export()
      })
    }, 310)
  },
  dealPho(str, host) {
    return str.replace("./", host);
  },
  onShow: function() {
    let that = this;
    var lb_descript = wx.getStorageSync('lb_descript');
    var swiper_arr = wx.getStorageSync('swiper_arr');
    if (swiper_arr) {
      wx.setNavigationBarTitle({
        title: swiper_arr[0].measure_name
      });
    }
    wx.getSystemInfo({
      success: (res) => {
        that.setData({
          winW: res.windowWidth,
        })
      }
    });
    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 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);
    }
  },
  tijiao: function() {
    let that = this;
    var lb_descript = wx.getStorageSync('lb_descript');
    let userInfo = wx.getStorageSync('userInfoName');
    if (lb_descript.id[0] == 523) {
      var ans = wx.getStorageSync('answer_swiper')
      if (ans.answer[ans.answer.length - 1].length <= 0) {
        wx.showToast({
          title: '请选择',
          icon: 'none',
          duration: 1000
        });
        return;
      }
    }
    if (this.data.flag && !this.disab) {
      this.setData({
        flag: false
      })
      wx.showLoading({
        title: '上传中...',
        mask:true
      })
      var startTime = wx.getStorageSync('startTime');
      var timeArr = wx.getStorageSync('timeArr');
      var chaTime = 0;
      for (let i = 0; i < timeArr.length; i++) {
        if (Number(timeArr) > 1000000040000) {
          timeArr[i] = 0;
        }
        chaTime += timeArr[i]
      }
      var thisTime = Date.parse(new Date());
      var cha = thisTime - startTime + chaTime;
      var time = Api.reversalTime(cha)
      var user = wx.getStorageSync('user');
      var answer = wx.getStorageSync('answer_swiper');
      // for (let i = 0; i < answer.score.length; i++) {
      //   answer.score[i] = answer.score[i].replace(/[\r\n]/g, '');
      // }
      answer.score = answer.score.join('|');
      answer.score = answer.score.replace(/-/g, ',');
      var lb_descript = wx.getStorageSync('lb_descript');
      var swiper_arr = wx.getStorageSync('swiper_arr');
      var lb_tp = wx.getStorageSync('lb_tz')
      if (lb_tp == '1') {
        var data = {
          user_stime: time,
          user_answer: answer.score,
          answer: answer.score,
          user_number: lb_descript.desc.z_openid,
          measure_id: lb_descript.id[0],
        };
        var url = Api.HOST_xinli + 'xinli/index.php/Api/add_res';
      } else {

        var data = {
          user_stime: time,
          user_answer: answer.score,
          answer: answer.score,
          openid: user.openid,
          user_number: userInfo.user_number,
          user_id: userInfo.user_id,
          qrcode: userInfo.qrcode,
          measure_id: lb_descript.id[0],
        };
        var url = Api.HOST_xinli + 'jswszx/index.php/Api/add_res';
      }
      console.log(data)
      data.unitid = lb_descript.desc.unitid;
      var uploadData = setTimeout(function() {
        wx.hideLoading()
        wx.showToast({
          icon: 'none',
          title: '您当前的网络不稳定，请检查网络重新提交',
          duration: 2000
        })
        that.setData({
          flag: true
        })
      }, 5000)

      Api.fetchPostN(url, data, (err, res) => {
        clearTimeout(uploadData)
        if (Number(res) == 0) {
          Api.alert("提交失败，请重新提交。")
          return;
        }
        var swiper_arr = wx.getStorageSync('swiper_arr');
        var data1 = {};
        var urls = Api.HOST + 'index.php?s=Home/del_vip';
        var ti_title = swiper_arr[0].measure_name;
        var lb_descript = wx.getStorageSync("lb_descript");
        data1.user_id = userInfo.user_id;
        data1.g_id = userInfo.qrcode;
        data1.g_time = lb_descript.desc.g_time || lb_descript.desc.time;
        data1.measure_name = ti_title;
        data1.res_id = res;
        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
          })
          if (res.key == 1 || res.key == 0) {
            wx.removeStorageSync('answer_swiper')
            wx.removeStorageSync('swiper_arr')
            wx.removeStorageSync('chaTime')
            wx.removeStorageSync('endTime')
            wx.removeStorageSync('startTime')
            wx.removeStorageSync('timeArr')
            wx.removeStorageSync('lb_swiper_con')
            wx.hideLoading()
          }
          // var timer = setTimeout(function () {
          //   wx.showLoading({
          //     title: '连接超时',
          //   })
          // }, 8000)


          if (res.key == 1) {
            // clearTimeout(timer)
            wx.showToast({
              title: '还剩' + res.val + '个量表',
              icon: 'success',
              duration: 2000
            })
            setTimeout(function() {
              var lb_tz = wx.getStorageSync('lb_tz');
              if (lb_tz == '1') {
                wx.reLaunch({
                  url: '/pages/info1/info1?otype=1&otype1=1&g_id=' + userInfo.qrcode,
                  success: function() {
                    that.setData({
                      flag: true
                    })
                  }
                })
              } else {
                wx.reLaunch({
                  url: '/pages/info/info?otype=1&otype1=1&g_id=' + userInfo.qrcode,
                  success: function() {
                    that.setData({
                      flag: true
                    })
                  }
                })
              }
            }, 2000)
          } else if (res.key == 0) {
            // clearTimeout(timer)
            wx.showToast({
              title: '上传成功',
              icon: 'success',
              duration: 2000
            })
            setTimeout(function() {
              wx.removeStorageSync('tplbDetail')
              wx.removeStorageSync('weiLb')
              // wx.reLaunch({
              //   // url: '/pages/end/end?lbtype=-1',
              //   url: '/pages/record/record',
              //   success: function() {
              //     that.setData({
              //       flag: true
              //     })
              //     wx.removeStorageSync('lb_descript')
              //   }
              // })
              wx.reLaunch({
                url: '/pages/index/index',
                success: function () {
                  that.setData({
                    flag: true
                  })
                  wx.removeStorageSync('lb_descript')
                }
              })
            }, 2000)
          }
        })
      })
    }
  },
  onReady: function() {
    let that = this;
    // setTimeout(function () {
    wx.getSystemInfo({
      success: (res) => {
        if (/^iPhone X.*/i.test(res.model)) {
          that.setData({
            iPhoneX: true,
            winH: res.windowHeight - 118
          })
        } else {
          that.setData({
            iPhoneX: false,
            winH: res.windowHeight - 118
          })
        }
      }
    });
    // }, 600)
  },
})