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

  /**
   * 页面的初始数据
   */
  data: {
    outMoney: null,
    inputValue:'',
    checkPass: false,
    msg:null,
    userInfo: {},
    isLogin: false,
    remarkArray: [{
      value: 1,
      text:'充电站位置不方便'
      },{
      value: 2,
      text:'电费过高'
      },{
      value: 3,
      text:'服务费过高'
      },{
      value: 4,
      text:'充电慢'
      },{
      value: 5,
      text:'油车或电车占位'
      },{
      value: 6,
      text:'停放环境堪忧'
      },{
      value: 7,
      text:'长时间离线无人维修'
      },{
      value: 8,
      text:'充电桩存在安全隐患'
      },{
      value: 9,
      text:'小程序经常卡顿'
      },{
      value: 10,
      text:'变更住所'
      },{
      value: 11,
      text:'车已售出'
      },{
      value: 12,
      text:'其他'
      }],
    remarkArrayIndex: null
  },
  outMoney(e) {
    //console.log(e);
    let outMoney = e.detail.value;
    let value = outMoney;
    if (value.includes('.')) {
        let parts = value.split('.');
        if (parts[1].length > 2) {
            value = parts[0] + '.' + parts[1].substring(0, 2);
        }
    }
    this.setData({
      inputValue:value
    });
    this.setData({
      outMoney:this.data.inputValue
    });
    if (this.data.userInfo.repaidbalance && outMoney && outMoney >= 0.3 && outMoney <= this.data.userInfo.repaidbalance) {
      if (this.data.remarkArrayIndex){
        this.setData({
          checkPass: true
        });
      }else{
        this.setData({
          checkPass: false
        });
      }
    } else {
      this.setData({
        checkPass: false
      });
    }
  },
  beginOutMoney(e) {
    if (this.data.msg) {
      wx.showModal({
        showCancel: false,
        content: this.data.msg,
        confirmColor:'#00AADD',
      });
      return;
    }
    log.info('[提现]', '[用户触发提现流程]');
    wx.showLoading({
      title: '提现中...',
      mask: true
    });
    let that = this;
    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: that.data.outMoney,
            userId: that.data.userInfo.userId,
            loginName: that.data.userInfo.loginName,
            remark: that.data.remarkArray[that.data.remarkArrayIndex].text,
            code: res.code
          });
          wx.request({
            url: getApp().globalData.postHeadAgreement +'/restapi/wechatpay/dopayTransfers',
            data: {
              //outTradeNo: new Date().getTime(), //订单号
              //totalFee: that.data.chargemoney_select, //钱
              totalFee: that.data.outMoney,
              userId: that.data.userInfo.userId,
              loginName: that.data.userInfo.loginName,
              remark: that.data.remarkArray[that.data.remarkArrayIndex].text,
              code: res.code
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
            },
            method: 'POST',
            success(res1) {
              wx.hideLoading();
              let {
                data
              } = res1;
              log.info('[提现]', '[服务端提现]', '[响应]', data);
              if (data && data.code == 200) {
                wx.navigateBack();
                wx.showModal({
                  showCancel: false,
                  content: '提现成功',
                  confirmColor:'#00AADD',
                });
                log.info('[提现]', '[服务端提现]', '[提现成功]', data);
              } else {
                wx.showModal({
                  showCancel: false,
                  content: data.msg,
                  confirmColor:'#00AADD',
                });
                log.info('[提现]', '[服务端提现]', '[提现失败data null||data.code<>200]', data);
              }
            }
          });
        } else {
          wx.hideLoading();
          console.log('登录失败！' + res.errMsg);
          log.info('[提现]', '[用户触发提现流程]', '[wx.login响应失败code null]', res);
        }
      }
    })
  },
  bindRemarkChange: function (e) {
    //console.log(e.detail.value);
    //let remarkValue = this.data.remarkArray[e.detail.value].value;
    this.setData({
      remarkArrayIndex: e.detail.value
    });

    if (this.data.userInfo.repaidbalance && this.data.outMoney && this.data.outMoney >= 0.3 && this.data.outMoney <= this.data.userInfo.repaidbalance) {
        this.setData({
          checkPass: true
        });
    }else{
      this.setData({
        checkPass: false
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    log.info('[提现]', '[加载完成]');
    let userInfo = wx.getStorageSync('userInfo');
    let isLogin = wx.getStorageSync('isLogin');
    let that = this;
    log.info('[提现]', '[同步用户数据]', '[请求]', {
      loginName: userInfo.loginName
    });
    wx.request({
      url: getApp().globalData.postHeadAgreement +'/restapi/wechat/syncUser',
      data: {
        loginName: userInfo.loginName
      },
      method: 'POST',
      success: function(res) {
        let {
          data
        } = res;
        log.info('[提现]', '[同步用户数据]', '[响应]', data);
        if (data.code && data.code != 200) {
          wx.removeStorageSync('userInfo');
          wx.removeStorageSync('isLogin');
          let url = '/pages/login/phone_login/phone_login';
          wx.redirectTo({
            url,
          });
          log.info('[提现]', '[同步用户数据]', '[失败data null||data.code<>200跳转登陆界面]', data);
        } else {
          that.setData({
            userInfo: data,
            isLogin: true
          });
          wx.setStorageSync('userInfo', data);
          wx.setStorageSync('isLogin', true);
          log.info('[提现]', '[同步用户数据]', '[成功]', data);
          log.info('[提现]', '[获取用户是否有未完成订单]', '[请求]', {
            userId: userInfo.userId
          });
          wx.request({
            url: getApp().globalData.postHeadAgreement + '/restapi/pileLog/wechatchargstatus',
            data: {
              userId: userInfo.userId
            },
            method: 'POST',
            success(res) {
              let {
                data
              } = res;
              log.info('[提现]', '[获取用户是否有未完成订单]', '[响应]', data);
              if (data && data.code == 200) {
                //有正在充电的订单
                that.setData({
                  msg: '暂时无法退款，请先完成订单！'
                });
              log.info('[提现]', '[获取用户是否有未完成订单]', '[用户有未完成订单无法体现]', data);
              } else {
                console.log(res);
                log.info('[提现]', '[获取用户是否有未完成订单]', '[用户没有未完成订单]', data);
              }
            }
          });
          log.info('[提现]', '[获取用户是否有未支付订单]', '[请求]', {
            userId: that.data.userInfo.userId
          });
          wx.request({
            url: getApp().globalData.postHeadAgreement + '/restapi/pileLog/wechatsettlement',
            data: {
              userId: that.data.userInfo.userId
            },
            method: 'POST',
            success(res) {
              let {
                data
              } = res;
              log.info('[提现]', '[获取用户是否有未支付订单]', '[响应]', data);
              let {
                result: order
              } = data;
              if (data && order && data.code == 200) {
               //有未支付的订单
                that.setData({
                  msg: '暂时无法退款，请先完成订单！'
                });
                log.info('[提现]', '[获取用户是否有未支付订单]','[用户有未支付订单无法提现]');
              } else {
                console.log(res);
                log.info('[提现]', '[获取用户是否有未支付订单]', '[用户没有未支付订单]');
              }
            }
          });
        }
      },
      fail(e) {
        console.log("用户数据同步失败");
        log.info('[提现]', '[同步用户数据]', '[fail]', e);
      }
    });


  },

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

  },

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

  },

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

  },

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

  },

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

  }
})