// pages/chargemoney/chargemoney.js
let log = require('../../utils/log.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    chargemoney_select: null,
    userInfo: {},
    isLogin: false
  },
  bindMoneyTap(e) {
    let chargemoney_select = e.currentTarget.id;
    this.setData({
      chargemoney_select
    });
  },
  saveMoney(e) {
    //console.log(e);
    let chargemoney_select = e.detail.value;
    this.setData({
      chargemoney_select
    });
  },
  beginChargemoney(e){

    let that = this
    wx.showModal({
      title: '',
      content: '每日退款最大额度为500元，您是否确认本次充值为' + this.data.chargemoney_select + '元？',
      confirmColor:'#00AADD',
      success(res) {
       if (res.confirm) {
        that.beginChargemoneySuccess(e);
       } else if (res.cancel) {
        wx.showToast({
          title: '充值已取消',
          icon: 'error',
          duration: 2000
         })
       }
      }
     })
  },
  beginChargemoneySuccess(e) {




    //console.log(this.data.chargemoney_select);
    log.info('[充值]', '[开始充值流程]');
    let that = this;

    if(that.data.userInfo==null ||that.data.userInfo=={} || that.data.userInfo.userId==null ){
      return 
    }

    if (this.data.chargemoney_select) {
      wx.showLoading({
        title: '充值中...',
        mask: true
      });
      log.info('[充值]', '[开始微信充值]', '[wx.login请求]');
      wx.login({
        success(res) {
          console.log(res);
          log.info('[充值]', '[开始微信充值]', '[wx.login响应]', res);
          if (res.code) {
            // 发起网络请求
            log.info('[充值]', '[服务端微信充值]', '[请求]', {
              //outTradeNo: new Date().getTime(), //订单号
              totalFee: that.data.chargemoney_select, //钱
              //totalFee:0.01,
              code: res.code,
              userId: that.data.userInfo.userId
            });
            wx.request({
              url: getApp().globalData.postHeadAgreement +'/restapi/wechatpay/dopaychargmoney',
              data: {
                //outTradeNo: new Date().getTime(), //订单号
                totalFee: that.data.chargemoney_select, //钱
                //totalFee:0.01,
                code: res.code,
                userId: that.data.userInfo.userId
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
              },
              method: 'POST',
              success(res1) {
                log.info('[充值]', '[服务端微信充值]', '[响应]', res1.data);
                console.log(res1);
                if(res1.data.errCodeDes==2 && res1.data.bindingPhone==0 ){
                  wx.hideLoading();
                  wx.showModal({
                    title: '提示',
                    content: '您未绑定手机号,请重新登录后自动刷新绑定信息',
                    confirmText: '去登录',
                    showCancel:false,
                    confirmColor:'#00AADD',
                    success: function (res1) {
                      if (res1.confirm) {
                        wx.removeStorageSync('userInfo');
                        wx.removeStorageSync('isLogin');
                        let url = '/pages/login/phone_login/phone_login';
                        wx.redirectTo({
                          url
                        })
                      }
                    }
                  });
                  return;
                } else if(res1.data.processResult == 1){
                  wx.hideLoading();
                  wx.showModal({
                    content: res1.data.errCodeDes,
                    showCancel:false,
                    confirmColor:'#00AADD',
                  });
                  return;
                }
                log.info('[充值]', '[微信支付]', '[请求]', {
                  timeStamp: res1.data.timeStamp,
                  nonceStr: res1.data.nonceStr,
                  package: res1.data.package,
                  signType: res1.data.signType,
                  paySign: res1.data.paySign
                });
                wx.requestPayment({
                  timeStamp: res1.data.timeStamp,
                  nonceStr: res1.data.nonceStr,
                  package: res1.data.package,
                  signType: res1.data.signType,
                  paySign: res1.data.paySign,
                  success(res2) {
                    console.log(res2);
                    log.info('[充值]', '[微信支付]', '[响应]', res2);
                    log.info('[充值]', '[微信支付回调]', '[请求]', {
                      userId: that.data.userInfo.userId,
                      rechargeMoney: that.data.chargemoney_select
                      //rechargeMoney: 0.01,
                    });
                    wx.request({
                      url: getApp().globalData.postHeadAgreement +'/restapi/pileLog/wechatrechargeback',
                      data: {
                        userId: that.data.userInfo.userId,
                        rechargeMoney: that.data.chargemoney_select
                        //rechargeMoney: 0.01,
                      },
                      method: 'POST',
                      success(res3) {
                        wx.hideLoading();
                        let {
                          data
                        } = res3;
                        log.info('[充值]', '[微信支付回调]', '[响应]', data);
                        if (data && data.code == 200) {
                          wx.showModal({
                            showCancel: false,
                            content: '微信扣款成功，平台入账稍有延迟，请您确认余额更新后再启动充电。',
                            confirmColor:'#00AADD',
                          });
                          let url = `/pages/chargemoneyresult/chargemoneyresult?timeStamp=${res1.data.timeStamp}&money=${that.data.chargemoney_select}`;
                          wx.redirectTo({
                            url
                          })
                          log.info('[充值]', '[微信支付回调]', '[成功]');
                        } else {
                          wx.showModal({
                            showCancel: false,
                            content: '充值失败',
                            confirmColor:'#00AADD',
                          });
                          log.info('[充值]', '[微信支付回调]', '[失败data null||data.code<>200]', data);
                        }
                      }
                    });
                  },
                  fail(res3) {
                    wx.hideLoading();
                    console.log(res3);
                    log.info('[充值]', '[微信支付]', '[fail]', res3);
                  }
                });
              }
            });
          } else {
            wx.hideLoading();
            console.log('登录失败！' + res.errMsg)
            log.info('[充值]', '[开始微信充值]', '[wx.login响应失败code null]', res);
          }
        }
      })


    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    log.info('[充值]', '[页面加载完成]');
    let userInfo = wx.getStorageSync('userInfo');
    let isLogin = wx.getStorageSync('isLogin');
    // 页面显示
    if (userInfo && isLogin) {
      if(userInfo.bindingPhone==0){
        wx.showModal({
          title: '提示',
          content: '当前账户未绑定手机号，请您进行手机号绑定操作',
          showCancel:false,
          confirmText: '去绑定',
          confirmColor:'#00AADD',
          success: function (res1) {
              let url = `/pages/bindPhone/bindPhone`;
              wx.navigateTo({
                url
              });
          }
        })
        return;
      }
      //console.log(userInfo);
      //userInfo.flag = true;
      this.setData({
        userInfo: userInfo,
        isLogin: isLogin
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})