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

  /**
   * 页面的初始数据
   */
  data: {
    chargPile: null,
    orderid: null,
    userId: null,
    repaidbalance: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    wx.getStorage({
      key: 'scan_chargpile',
      success: function (res) {
        //console.log(res);
        //console.log(res.data);
        var chargPile = res.data;
        chargPile.sharpTotalPrice = (chargPile.sharpChargPrice + chargPile.sharpServicePrice).toFixed(4);
        chargPile.peakTotalPrice = (chargPile.peakChargPrice + chargPile.peakServicePrice).toFixed(4);
        chargPile.flatTotalPrice = (chargPile.flatChargPrice + chargPile.flatServicePrice).toFixed(4);
        chargPile.valleyTotalPrice = (chargPile.valleyChargPrice + chargPile.valleyServicePrice).toFixed(4);
        chargPile.totalprice = (chargPile.chargprice + chargPile.serviceprice).toFixed(4);
        that.setData({
          chargPile
        });
        //console.log(chargPile);
        wx.removeStorage({
          key: 'scan_chargpile',
          success(res) {
            console.log(res);
          }
        });
        log.info('[扫码]', '[加载完成]', '[参数]', res.data);
		let userInfo = wx.getStorageSync('userInfo');
		wx.request({
		  url: getApp().globalData.postHeadAgreement + '/restapi/wechat/syncUser',
		  data: {
			loginName: userInfo.loginName
		  },
		  method: 'POST',
		  success: function (res) {
			let {
			  data
			} = res;
			log.info('[扫码]', '[同步用户数据]', '[响应]', data);
			console.info('[扫码]', '[同步用户数据]', '[响应]', data);
			if (data.code && data.code != 200) {
			  log.info('[扫码]', '[同步用户数据]', '[失败data null||data.code<>200跳转登陆界面]', data);
			} else {
			  that.setData({
				repaidbalance:data.repaidbalance
			  });
			}
		  },
		  fail(e) {
			console.log("用户数据同步失败");
			log.info('[扫码]', '[同步用户数据]', '[fail]', e);
		  }
		});

      }
    });
  },
  beginCharge(e) {
    
    let userInfo = wx.getStorageSync('userInfo');
    let isLogin = wx.getStorageSync('isLogin');
    wx.showLoading({
      title: '开启充电中...',
      mask: true
    });
    log.info('[扫码]', '[开始充电流程]');
    //同步用户数据
    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) {
        wx.hideLoading();
        let {
          data
        } = res;


        log.info('[扫码]', '[同步用户数据]', '[响应]', data);
        console.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 {
          wx.setStorageSync('userInfo', data);
          wx.setStorageSync('isLogin', true);
          let repaidbalance = data.repaidbalance;
          that.setData({
            repaidbalance
          });
          console.info("sssssss   " + data.repaidbalance)
          //开始充电
          if(data.bindingPhone==0){
            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
                  })
                }
              }
            });
            log.info('[扫码]', '[同步用户数据]', '[未绑定手机号]', data);
          }else if (!data.repaidbalance || data.repaidbalance <= 0) {
            wx.showModal({
              showCancel: false,
              content: '余额不足,请充值！',
              success: function (res) {
                if (res.confirm) {
                  let url = "/pages/chargemoney/chargemoney";
                  wx.navigateTo({
                    url
                  });
                }
              }
            });
            log.info('[扫码]', '[同步用户数据]', '[data.repaidbalance null||data.repaidbalance<=0余额不足跳转充值界面]', data);
          } else if (data.repaidbalance > 0 && data.repaidbalance <= 15) {
            wx.showModal({
              title: '余额：' + data.repaidbalance + '元',
              showCancel: false,
              confirmText: "去充值",
              confirmColor:'#00AADD',
              content: '余额过低,请尽快充值！',
              success: function (res) {
                if (res.confirm) {
                  let url = "/pages/chargemoney/chargemoney";
                  wx.navigateTo({
                    url
                  });
                }
              }
            });
            log.info('[扫码]', '[同步用户数据]', '[0<data.repaidbalance<=15余额过低]', data);

            // wx.showModal({
            //   title:'请选择',
            //   showCancel: true,
            //   confirmText:"继续充电",
            //   cancelText:"去充值",
            //   content: '余额过低,请尽快充值！',
            //   success: function (res) {
            //     if (res.confirm) {

            //       that.beginCharge_satrt();
            //     } else if (res.cancel) {
            //       let url = "/pages/chargemoney/chargemoney";
            //       wx.navigateTo({
            //         url
            //       });
            //     }
            //   }
            // });
          } else if (data.repaidbalance > 15) {
            log.info('[扫码]', '[同步用户数据]', '[余额充足开始充电]', data);
            that.beginCharge_satrt();
          }
        }
      },
      fail(e) {
        console.log("用户数据同步失败");
        log.info('[扫码]', '[同步用户数据]', '[fail]', e);
      }
    });


  },
  beginCharge_satrt() {
    wx.showLoading({
      title: '开启充电中...',
      mask: true
    });

    let that = this;
    let terminalNum = this.data.chargPile.chargPileId;

    let userInfo = wx.getStorageSync('userInfo');
    let isLogin = wx.getStorageSync('isLogin');

    console.log(terminalNum);
    let userId = userInfo.userId;
    let chargstarttime = new Date().getTime();
    console.log(chargstarttime);
    log.info('[扫码]', '[开始充电]', '[请求]', {
      //chargPileId: '201811010000004202',
      chargPileId: terminalNum,
      userId: userId,
      chargstarttime: chargstarttime
    });
    wx.request({
      url: getApp().globalData.postHeadAgreement + '/restapi/pileLog/miniprogramadd',
      data: {
        //chargPileId: '201811010000004202',
        chargPileId: terminalNum,
        userId: userId,
        chargstarttime: chargstarttime
      },
      method: 'POST',
      fail(e) {
        wx.hideLoading();
        //开启充电失败，提示用户
        wx.showModal({
          showCancel: false,
          content: '开启充电失败'
        });
        log.info('[扫码]', '[开始充电]', '[fail]', e);
      },
      success(res) {
        wx.hideLoading();
        let {
          data
        } = res;
        log.info('[扫码]', '[开始充电]', '[响应]', data);
        if (data && data.code == 200) {
          //if (data && data.code == 200 && data.orderid) {
          //开启充电成功，跳转到正在充电界面
          let {
            orderid
          } = data;
          log.info('[扫码]', '[开始充电]', '[成功,跳转充电中页面]', data);
          //console.log(this.data.city);
          let url = `/pages/charging/charging?orderid=${orderid}&userId=${userId}&chargPileId=${terminalNum}`;
          wx.redirectTo({
            url
          });
        } else if (data && data.code == 501) {
          //开启充电失败，提示用户
          wx.showModal({
            showCancel: false,
            content: '余额不足,请充值！'
          });
          log.info('[扫码]', '[开始充电]', '[失败data.code=501余额不足]', data);
        } else if (data && data.code == 502) {
          //开启充电失败，提示用户
          wx.showModal({
            showCancel: false,
            content: data.message
          });
          log.info('[扫码]', '[开始充电]', '[失败data.code=502' + data.message + ']', data);
        } else {
          //开启充电失败，提示用户
          wx.showModal({
            showCancel: false,
            content: '开启充电失败'
          });
          log.info('[扫码]', '[开始充电]', '[失败]', data);
        }
      }
    });
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})