// pages/rechargeWay/index.js
import { requestRecharge } from "../../service/recharge";
import { alertInfo } from "../../utils/index";
import request from '../../utils/request';
const { OK } = request;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    money: 0,
    address: "",
    rechargeWay: 0,
    id: "",
    tenement: "",
    park: "",
    rechargeLoading: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { money, address, id, tenement, park } = options
    this.setData({ money: Number(money), address, id, tenement, park })
  },
  onChangeRechargeWay(e) {
    this.setData({ rechargeWay: e.detail })
  },
  onClickCell(e) {
    const { name } = e.currentTarget.dataset;
    this.setData({ rechargeWay: name })
  },
  async recharge() {
    const { rechargeWay } = this.data;
    await this.setLoading(true)
    try {
      switch(rechargeWay) {
        case 1:
          alertInfo("开发中")
          break;
        default:
          await this.wxRecharge();
          break;
      }
    } catch(err) {

    } finally {
      await this.setLoading(false)
    }    
  },
  async wxRecharge() {
    const { money, id, tenement, park } = this.data;
    const { code, message, data } = await requestRecharge({ money: Number(money), id, tenement, park })
    if (code !== OK) {
      alertInfo(message)
      return;
    }
    wx.requestPayment({
      timeStamp: data?.time,
      nonceStr: data?.nonceStr,
      package: "prepay_id=" + data?.prepay_id,
      paySign: data?.paySign,
      signType: 'RSA',
      success: (res) => {
        alertSuccess("充值成功")
        that.setData({
          money: null
        })
      },
      fail: (res) => {
        alertInfo("请稍后重试")
      },
      complete: (res) => {
        that.handleGetMeterDetail(meter.id)
      }
    })
  },
  async setLoading(flag) {
    return new Promise((res) => {
      this.setData({
        rechargeLoading: flag,
      }, () => {
        res()
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})