//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    timeCount: 60,
    codeBtnHtml: '获取验证码',
    mobileNo: '',
    customerId: '',
    name: '家庭管理服务测试',
    verificationCode: '',
    autogetPhoneNumber: false,
    nameValider: false,
    verificationCodeValider: false,
    disableBtn: false,
    userInfo: {},
    isIpx: false,
    hasUserInfo: false,
    isBuy: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function() {
    this.setData({
      isIpx: app.globalData.isIpx
    });
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    wx.checkSession({
      success: function() {
        // console.log('未过期，并且在本生命周期一直有效')
        //session_key 未过期，并且在本生命周期一直有效
      },
      fail: function() {
        // console.log('已经失效，需要重新执行登录流程')
        // session_key 已经失效，需要重新执行登录流程
        // 登录
        wx.login({
          success: function(res) {
            if (res.code) {
              //发起网络请求
              wx.request({
                url: 'https://m.zuihuibi.cn/api/jscode2session',
                method: 'POST',
                header: {
                  'X-Authorization': wx.getStorageSync('X-Authorization')
                },
                data: {
                  appid: 'wx53a601e27aaf7897',
                  secret: 'f61707a62e46fee78ef46155330cdf45',
                  js_code: res.code
                },
                success: function(res) {
                  wx.setStorageSync('sessionKey', res.data.data.openid)
                }
              })
            } else {
              console.log('登录失败！' + res.errMsg)
            }
          }
        })
      }
    })
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  /**
   * 获取用户手机号码
   */
  getPhoneNumber: function(e) {
    const phoneNumber = {
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
      sessionKey: wx.getStorageSync('sessionKey')
    }
    var that = this;
    wx.request({
      url: 'https://m.zuihuibi.cn/api/getPhoneNumber',
      method: 'POST',
      header: {
        'X-Authorization': wx.getStorageSync('X-Authorization')
      },
      data: JSON.stringify(phoneNumber),
      success: function(res) {
        that.setData({
          'mobileNo': res.data.data.mobileNo,
          'customerId': res.data.data.customerId
        })
        console.log(res.data.data.mobileNo)
      }
    })
    if (e.detail.encryptedData) {
      this.setData({
        'autogetPhoneNumber': true,
        'verificationCodeValider': true
      })
    } else {
      this.setData({
        'autogetPhoneNumber': false,
        'verificationCodeValider': false
      })
    }
    // console.log(e.detail.errMsg)
    // console.log(e.detail.iv)
    // console.log(e.detail.encryptedData)
  },
  /**
   * 失去焦点获取用户输入手机号
   */
  inputMobileNo: function(e) {
    if (e.detail.value.length === 11) {
      this.setData({
        'mobileNo': e.detail.value
      });
    }
  },
  /**
   * 
   */
  getVerificationCode: function(e) {
    if (e.detail.value.length === 4) {
      this.setData({
        'verificationCode': e.detail.value
      });
      if (this.data.mobileNo) {
        this.checkVerificationCode();
      }
    }
  },
  /**
   * 获取验证码
   */
  getCode: function(e) {
    var VerificationCodeRequest = {
      mobileNo: this.data.mobileNo,
      type: '1'
    }
    if (this.data.mobileNo.length === 11) {
      var that = this;
      wx.request({
        url: 'https://m.zuihuibi.cn/api/verificationCode',
        method: 'POST',
        header: {
          'X-Authorization': wx.getStorageSync('X-Authorization')
        },
        data: JSON.stringify(VerificationCodeRequest),
        success: function(res) {
          if (res.data.success) {
            wx.showToast({
              title: '发送成功',
              icon: 'success',
              duration: 800
            });
            that.setData({
              'disableBtn': true
            });
            var timeCount = that.data.timeCount;
            var codeBtnHtml = that.data.codeBtnHtml;
            var timer = setInterval(function() {
              timeCount--;
              codeBtnHtml = '(' + timeCount + ')s';
              if (timeCount <= 0) {
                codeBtnHtml = '重新获取';
                clearInterval(timer);
                timeCount = 60;
                that.setData({
                  'disableBtn': false
                });
              }
              that.setData({
                'codeBtnHtml': codeBtnHtml
              });
            }, 1000)
          } else {
            wx.showToast({
              title: res.data.message,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    } else {
      wx.showToast({
        title: '请检查您的手机号码是否正确',
        icon: 'none',
        duration: 2000
      })
    }

  },
  /**
   * 验证验证码
   */
  checkVerificationCode: function() {
    var verificationCodeRequest = {
      mobileNo: this.data.mobileNo,
      verificationCode: this.data.verificationCode,
    }
    if (this.data.verificationCode) {
      var that = this;
      wx.request({
        url: 'https://m.zuihuibi.cn/api/checkVerificationCode',
        method: 'POST',
        header: {
          'X-Authorization': wx.getStorageSync('X-Authorization')
        },
        data: JSON.stringify(verificationCodeRequest),
        success: function(res) {
          that.setData({
            'verificationCodeValider': res.data.success
          });
          var mobileNo = {
            mobileNo: that.data.mobileNo
          }
          wx.request({
            url: 'https://m.zuihuibi.cn/api/login',
            method: 'POST',
            header: {
              'X-Authorization': wx.getStorageSync('X-Authorization')
            },
            data: JSON.stringify(mobileNo),
            success: function(res) {
              that.setData({
                'customerId': res.data.data.customerId
              });
            }
          })
          if (!res.data.success) {
            wx.showToast({
              title: res.data.message,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }
  },
  /**
   * 立即购买
   */
  buy: function(e) {
    this.setData({
      'isBuy': true
    })
  },
  /**
   * 姓名格式校验
   */
  nameValid: function(e) {
    var NAME_REGEXP = /(^[\u4e00-\u9fa5]{1}[\u4e00-\u9fa5\.·。]{0,48}[\u4e00-\u9fa5]{1}$)|(^[a-zA-Z]{1}[a-zA-Z\s]{0,48}[a-zA-Z]{1}$)/;
    this.setData({
      'nameValider': NAME_REGEXP.test(e.detail.value),
      'name': e.detail.value
    });
  },
  /**
   * 立即支付
   */
  goPay: function(e) {
    if (!this.data.mobileNo) {
      wx.showToast({
        title: '请检查您的手机号码是否正确',
        icon: 'none',
        duration: 2000
      })
    } else if (!this.data.verificationCodeValider) {
      wx.showToast({
        title: '请检查您的验证码是否正确',
        icon: 'none',
        duration: 2000
      })
    } else if (!this.data.nameValider) {
      wx.showToast({
        title: '请检查您的姓名是否正确',
        icon: 'none',
        duration: 2000
      })
    } else {
      const startDate = new Date();
      const endDate = new Date(new Date(startDate).setFullYear(new Date(startDate).getFullYear() + 1));
      endDate.setDate(endDate.getDate() - 1);
      const data = {
        customerId: this.data.customerId,
        planId: '424',
        startDate: startDate.getFullYear() + '-' + this.dateFormat((Number(startDate.getMonth()) + 1)) + '-' + this.dateFormat((Number(startDate.getDate()))),
        endDate: endDate.getFullYear() + '-' + this.dateFormat((Number(endDate.getMonth()) + 1)) + '-' + this.dateFormat((Number(endDate.getDate()))),
        price: '49',
        openid: wx.getStorageSync('openid'),
        holder: {
          name: this.data.name,
          mobileNo: this.data.mobileNo
        },
        paymentMethod: '4'
      }
      wx.request({
        url: 'https://m.zuihuibi.cn/api/voucherBuy',
        method: 'POST',
        header: {
          'X-Authorization': wx.getStorageSync('X-Authorization')
        },
        data: JSON.stringify(data),
        success: function(res) {
          if (res.data.success) {
            wx.requestPayment({
              'timeStamp': res.data.data.timeStamp,
              'nonceStr': res.data.data.nonceStr,
              'package': res.data.data.packageWX,
              'signType': res.data.data.signType,
              'paySign': res.data.data.paySign,
              'success': function(res) {
                // console.log(res);
                console.log('成功');
                wx.navigateTo({
                  url: '/pages/returnPage/returnPage?paymentStatus=1',
                })
              },
              'fail': function(res) {
                // console.log(res);
                wx.navigateTo({
                  url: '/pages/returnPage/returnPage?paymentStatus=0',
                })
                console.log('失败');
              },
              'complete': function(res) {
                // console.log(res);
                console.log('失败和成功都会有')
              }
            })
          } else {
            if (res.data.data.errorCode === 'C01') {
              wx.navigateTo({
                url: '/pages/returnPage/returnPage?paymentStatus=2',
              })
            } else {
              wx.showToast({
                title: res.data.data.errorMessage,
                icon: 'none',
                duration: 2000
              })
            }
          }

        },
        fail: function(res) {
          console.log(res);
        }
      })
    }
  },
  /**
   * 时间格式修改
   */
  dateFormat: function(e) {
    if (Number(e) < 10) {
      return '0' + e;
    } else {
      return e;
    }
  },
  /**
   * 关闭弹窗
   */
  closeModalBox: function(e) {
    this.setData({
      'isBuy': false
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      title: '1对1家庭风险管理服务',
      imageUrl: '../images/share_img.png',
      path: '/pages/index/index'
    }
  }
})