const app = getApp()
const httpUtils = require('../../utils/http.js')
const ui = require('../../utils/ui.js')
Page({
  data: {
    tab: 1,
    money: 100,
    deviceid: '',
    roomName: '',
    deviceCode: '',
    balance: ''
  },
  deviceid: '',
  roomName: '',
  deviceCode: '',
  balance: '',
  onLoad(options) {
    this.setData({
      deviceid: options.deviceid,
      roomName: options.roomName,
      deviceCode: options.deviceCode,
      balance: options.balance
    })
    this.deviceid = options.deviceid
    this.roomName = options.roomName
    this.deviceCode = options.deviceCode
    this.balance = options.balance
  },
  getInputName(e){
    this.setData({
      money: e.detail.value
    })
  },
  changeTab(e){
    console.log(e)
    this.setData({
      tab: e.target.dataset.info
    })
    if(e.target.dataset.info == 1){
      this.setData({
        money: 100
      })
    }else if(e.target.dataset.info == 2){
      this.setData({
        money: 200
      })
    }else if(e.target.dataset.info == 3){
      this.setData({
        money: 500
      })
    }
  },
  toRecharge(){
    let that = this
    let obj = {
      url: '/api/erp/we/wePhoneCharge',
      data: {
        deviceId: that.deviceid,
        deposit: that.data.money,
        token: wx.getStorageSync('token'),
      }
    }
    httpUtils.request(obj).then(res=>{
      console.log("pay",res)
      let payInfo = res.data.data
      // 调取后端接口后微信下单
      wx.requestPayment({
        timeStamp:payInfo.timeStamp,
        nonceStr:payInfo.nonceStr,
        package:payInfo.package,
        signType:payInfo.signType,
        paySign:payInfo.paySign,
        success (res1) {
          console.log("支付",res1)
          if(res1.errMsg == 'requestPayment:ok'){
            wx.showToast({
              title: '支付成功！',
              icon: 'success',
              duration: 2000
            })
            wx.navigateTo({
              url: '/pages/record/index?deviceid=' + that.deviceid + '&roomName=' + that.roomName + '&deviceCode=' + that.deviceCode
            })
          }
        },
        fail (res1) { 
          wx.showToast({
            title: '支付失败！',
            icon: 'error',
            duration: 2000
          })
        }
      })
    }).catch(err=>{
      console.log(err)
      wx.showToast({
        title: "创建订单失败！",
        icon: 'error',
        duration: 2000
      })
    });
  }
})
