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

  /**
   * 页面的初始数据
   */
  data: {
    sc: true,
    id: 0,
    winH: '',
    winW: '',
    disab: true,
    current: 1,
    flag: true,
    animationData: {},
    item: {
      answer: [],
      con: '',
      active: -1,
      num: '',
      add: '',
      lb_id: '',
      time: '',
    },
    judgeSex: 1,
    hollander: "", //霍兰德职业倾向
    pizibao: "", //匹兹堡
    pizibao1: "", //社会支持评定
    pizibao2: "", // 成人智残测查量表
    ptime1: "22",
    pminute1: "30",
    ptime2: "07",
    pminute2: "30",
    ptime3: "08",
    pminute3: "00",
    uploadData: '',
    monitor: '', //1为监测
    inquiry: '', //1二维码。2聊天页面心理体检
    inquiry_id: '', //心理体检量表ID
  },
  onLoad: function (options) {
    console.log(options, 'hahahhah');
    var otype = options.otype;
    if (options.inquiry) {
      this.setData({
        inquiry: options.inquiry,
        inquiry_id: options.inquiry_id,
      })
    } else {
      this.setData({
        inquiry: 1,
      })
    }
    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;
    // 判断是不是从首页进入  已经移除 otype == 11
    if (otype && otype == 11) {

    } else {
      console.log(yanzhengid, lb_descript.desc.record_id)
      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];
          // 处理最后一题的选择问题
          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]; // 最后答案
            var con_len = swiper_arr[1][last_len].score; //  最后问题的答案
            console.log(answer_swiper.answer[answer_swiper.answer.length - 1], item, 'item')
            for (let i = 0; i < con_len.length; i++) {
              if (ind_len == con_len[i]) {
                this.setData({
                  active: i,
                  disab: false
                })
              }
            }
          }
          this.setData({
            item: item,
            current: len,
            all: swiper_arr[1].length,

          })
        } else {
          console.log("loadData",2);
          this.loadData();
        }
      } else {
        console.log("loadData",1);
        this.loadData();
      }
    }


  },
  loadData: function () {
    console.log("loadData1111111111111")
    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(','),
        zimu: an,
        type: lb[j].type,
      }
      arr.push(obj)
    }
    var swiper_arr = [
      lb_swiper_con[0], arr
    ]
    if (swiper_arr[0].measure_id == 438) {
      wx.setStorageSync('swiper_arr_chen', swiper_arr);
      swiper_arr[1].length = 6
      wx.setStorageSync('swiper_arr', swiper_arr);
    } else {
      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);
    wx.setStorageSync('yanzhengid', yanzhengid);
    var timeArr = [];
    wx.setStorageSync("timeArr", timeArr);
    // wx.removeStorageSync('lb_swiper_con')
    var item = swiper_arr[1][0]
    this.setData({
      all: arr.length,
      current: 0,
      item: item
    });
    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;
    if (this.data.pizibao2) {
      var swiper_arr_chen = wx.getStorageSync('swiper_arr_chen');
      if (record == 1 && index == 0) {
        swiper_arr[1][2] = swiper_arr_chen[1][2]
      } else if (record == 1 && index == 1) {
        swiper_arr[1][2] = swiper_arr_chen[1][3]
      } else if (record == 1 && index == 2) {
        swiper_arr[1][2] = swiper_arr_chen[1][4]
      }
      swiper_arr[1][3] = swiper_arr_chen[1][5]
      swiper_arr[1][4] = swiper_arr_chen[1][6]
      swiper_arr[1][5] = swiper_arr_chen[1][7]
      wx.setStorageSync('swiper_arr', swiper_arr)
    }
    // 判断题长度
    if (record < Number(len) - 1) {
      this.setData({
        active: index,
        // active: -1,
        all: len,
        current: Number(record)
      })
      if (answer_swiper.score.length <= record) {
        answer_swiper.score.push(score);
        answer_swiper.answer.push(index);
      } else {
        answer_swiper.score[record] = score;
        answer_swiper.answer[record] = index;
      }
      wx.setStorageSync('answer_swiper', answer_swiper);
      // that.next(record);
      setTimeout(function () {
        that.next(record);
      }, 200)
    } else if (record == Number(len) - 1) {
      this.setData({
        active: index,
        // active: -1,
        all: len,
        current: Number(record),
        disab: false,
      })
      if (answer_swiper.score.length <= record) {
        answer_swiper.score.push(score);
        answer_swiper.answer.push(index);
      } else {
        answer_swiper.score[record] = score;
        answer_swiper.answer[record] = index;
      }
      wx.setStorageSync('answer_swiper', answer_swiper);
    } else {}
  },
  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]
      this.setData({
        active: answer_swiper.answer[Number(record)],
        current: record,
        item: item,
      })
    }

  },

  next: function (n) {
    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) {
        this.setData({
          active: answer_swiper.answer[n + 1],
          // 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) {
      console.log('tijiao')
      // this.tijiao();

    } else {
      console.log('meiyouti')
    }

  },
  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');
    console.log(lb_descript.id[0] == 3)
    var judgeSex = wx.getStorageSync('judgeSex');
    var sex = 1;
    // 量表id 
    if (lb_descript.id[0] == 3 && judgeSex == 1) {
      sex = 2;
    } else if (lb_descript.id[0] == 3 && judgeSex == 0) {
      sex = 3;
    } else {
      sex = 1;
    }
    // 量表id == 2  （军人）
    if (lb_descript.id[0] == 2 && judgeSex == 1) {
      sex = 2;
    } else if (lb_descript.id[0] == 3 && judgeSex == 0) {
      sex = 3;
    } else {
      sex = 1;
    }
    // 成人智残测查量表
    var pizibao2 = false;
    if (lb_descript.id[0] == 438) {
      pizibao2 = true;

    }
    // 社会支持评定
    var pizibao1 = false;
    if (lb_descript.id[0] == 444) {
      pizibao1 = true;
    }
    // 匹兹堡
    var pizibao = false;
    if (lb_descript.id[0] == 16) {
      pizibao = true;
    }
    //霍兰德倾向
    var hollander = false;
    console.log('霍兰德倾向', lb_descript.id[0], this.data.item)
    if (lb_descript.id[0] == 144) {
      hollander = true;
      console.log('霍兰德倾向')
    }
    console.log(pizibao, 'pizibao')
    this.setData({
      judgeSex: sex,
      pizibao: pizibao,
      pizibao1: pizibao1,
      pizibao2: pizibao2,
      hollander: hollander,
    })
    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 = Number(endtTime) - Number(startTime);
    var arr = wx.getStorageSync("timeArr");
    if (Number(cha) < 10000000) {
      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:Util.debouce(function () {
    let that = this;
    this.setData({
      sc: false
    })
    console.log(0)
    if (this.data.flag && !this.disab) {
      console.log(1)
      this.setData({
        flag: false
      })
      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, '');
      }
      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.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;
      // function fetchPost(url, data, callback) {
      var uploadData = setTimeout(function () {
        wx.hideLoading()
        wx.showToast({
          icon: 'none',
          title: '您当前的网络不稳定，请检查网络重新提交。',
          duration: 2000
        })

        that.setData({
          flag: true
        })
      }, 5000)
      // setTimeout(function () {
      //   clearTimeout(uploadData)
      // }, 7000)
      wx.showLoading({
        title: '上传中...',
      })
      wx.request({
        method: 'POST',
        url: url,
        data: data,
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success(res) {
          // clearTimeout(that.data.uploadData)
          clearTimeout(uploadData)
          if (Number(res.data) == 0) {
            wx.hideLoading();
            Api.alert("提交失败，请重新提交。")
            that.setData({
              flag: true
            })
            return;
          }
          var swiper_arr = wx.getStorageSync('swiper_arr');
          var data1 = {};
          var urls = Api.HOST + 'wechatIteration.php?s=Home/del_vip';
          var ti_title = swiper_arr[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;
          //2为聊天页面心理体检
          if (that.data.inquiry == 2) {
            data1.inquiry = that.data.inquiry;
            data1.inquiry_id = that.data.inquiry_id;
          }

          if (that.data.monitor == 1) {
            data1.monitor = 1;
            data1.monitor_id = that.data.monitor_id;
          }
          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) => {
            console.log('del_vip', res)
            if (err) {
              that.setData({
                flag: true
              })
            }
            that.setData({
              flag: true
            })
            if (res == 1 || res == 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.removeStorageSync('swiper_arr_chen')
              wx.hideLoading()
            }
            if (res == 1) {
              // clearTimeout(timer)
              wx.showToast({
                title: '上传成功',
                icon: 'success',
                duration: 2000
              })
              setTimeout(function () {
                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 {
                  if (that.data.monitor == 1) {
                    var monitor_url = '/pages/info/info?otype=1&monitor=1&g_id=' + qrcode_id;

                  } else if (that.data.inquiry == 2) { //2聊天页面心理检测报告
                    var monitor_url = '/pages/info/info?otype=1&inquiry=2&inquiry_id=' + that.data.inquiry_id;
                  } else {
                    var monitor_url = '/pages/info/info?otype=1&g_id=' + qrcode_id;
                  }
                  wx.reLaunch({
                    url: monitor_url,
                    success: function () {
                      that.setData({
                        flag: true
                      })
                    }
                  })
                }
              }, 2000)
            } else if (res == 0) {
              // clearTimeout(timer)
              wx.showToast({
                title: '上传成功',
                icon: 'success',
                duration: 2000
              })
              setTimeout(function () {
                wx.removeStorageSync('tplbDetail')
                wx.removeStorageSync('weiLb')
                wx.reLaunch({
                  url: '/pages/my/my',
                  success: function () {
                    that.setData({
                      flag: true
                    })
                    wx.removeStorageSync('lb_descript')
                  }
                })
              }, 2000)
            }
          })
        },
        fail(e) {
          console.error(e)
        },
        complete: function (e) {}
      })
    }
  },1000,true),
  onReady: function () {
    let that = this;
    // setTimeout(function () {
    wx.getSystemInfo({
      success: (res) => {
        if (/^iPhone X.*/i.test(res.model) || /^iPhone 11*/i.test(res.model) || /^iPhone 11 Pro Max*/i.test(res.model)) {
          that.setData({
            iPhoneX: true,
            winH: res.windowHeight - 118
          })
        } else {
          that.setData({
            iPhoneX: false,
            winH: res.windowHeight - 118
          })
        }
      }
    });
    // }, 600)
  },
  pitime: function (e) {
    // console.log(e)
    var txt = e.detail.value;
    var num = Number(txt);
    if (num >= 0 && num < 24) {
      console.log(num, "num")
      if (num < 10) {
        console.log(num, "num")
        txt = '0' + num;
        // console.log(0 < num < 10,"pp")
      }
      // console.log(txt)
      if (this.data.current == 0) {
        this.setData({
          ptime1: txt
        })
      } else if (this.data.current == 2) {
        this.setData({
          ptime2: txt
        })
      } else if (this.data.current == 3) {
        this.setData({
          ptime3: txt
        })
      }

    } else {
      if (this.data.current == 0) {
        this.setData({
          ptime1: ""
        })
      } else if (this.data.current == 2) {
        this.setData({
          ptime2: ""
        })
      } else if (this.data.current == 3) {
        this.setData({
          ptime3: ""
        })
      }

    }
  },
  piminute: function (e) {
    var txt1 = e.detail.value;
    var num1 = Number(txt1);
    if (num1 >= 0 && num1 < 60) {
      if (num1 < 10) {
        txt1 = '0' + num1;
      }
      if (this.data.current == 0) {
        this.setData({
          pminute1: txt1
        })
      } else if (this.data.current == 2) {
        this.setData({
          pminute2: txt1
        })
      } else if (this.data.current == 3) {
        this.setData({
          pminute3: txt1
        })
      }

    } else {
      if (this.data.current == 0) {
        this.setData({
          pminute1: ""
        })
      } else if (this.data.current == 2) {
        this.setData({
          pminute2: ""
        })
      } else if (this.data.current == 3) {
        this.setData({
          pminute3: ""
        })
      }

    }
  },
  pbtn: function () {
    let that = this;
    if (this.data.current == 0) {
      var ptime = this.data.ptime1;
      var pminute = this.data.pminute1;
    } else if (this.data.current == 2) {
      var ptime = this.data.ptime2;
      var pminute = this.data.pminute2;
    } else if (this.data.current == 3) {
      var ptime = this.data.ptime3;
      var pminute = this.data.pminute3;
    }

    if (Number(ptime) < 0 || Number(pminute) < 0 || Number(ptime) > 24 || Number(pminute) > 60 || ptime == "" || pminute == "") {
      console.log("this")
    } else {
      console.log("that")
      wx.hideKeyboard()
      var str = ptime + ":" + pminute;
      console.log(str, 'str')
      var answer_swiper = wx.getStorageSync("answer_swiper");
      var num = this.data.current; // 从0开始 不用加1 和数组下标对应
      answer_swiper.answer[num] = str;
      answer_swiper.score[num] = str;
      wx.setStorageSync("answer_swiper", answer_swiper)
      setTimeout(function () {
        that.next(num);
        that.setData({
          ptime: "",
          pminute: ""
        })
      }, 200)
    }
  }
})