// pages/fillInfo/fillInfo.js
var MD5Util = require('../../utils/md5.js');
//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    timeCount: 60,
    codeBtnHtml: '获取验证码',
    mobileNo: '',
    customerId: '',
    name: '',
    verificationCode: '',
    autogetPhoneNumber: false,
    nameValider: false,
    verificationCodeValider: false,
    disableBtn: false,
    isIpx:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) { this.setData({ isIpx: app.globalData.isIpx });},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  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: 'wx6ae60f33768036aa',
                  secret: 'd31f03454666a2a0dd261ee90c8aa6ce',
                  js_code: res.code
                },
                success: function(res) {
                  wx.setStorageSync('sessionKey', res.data.data.openid)
                }
              })
            } else {
              console.log('登录失败！' + res.errMsg)
            }
          }
        })
      }
    })
  },

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

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      title: '专属于你的保险经纪人服务',
      imageUrl: '../images/share_mini.jpg',
      path: '/pages/index/index'
    }
  },
  formSubmit: function(e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
  },
  /**
   * 获取用户手机号码
   */
  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
            })
          }
        }
      })
    }
  },
  /**
   * 立即支付
   */
  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: '293',
        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: '9',
        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);
        }
      })
    }
  },
  /**
   * 姓名格式校验
   */
  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
    });
  },
  /**
   * 时间格式修改
   */
  dateFormat:function(e){
    if(Number(e)<10){
      return '0' + e;
    }else{
      return e;
    }
  }
})