// pages/payment/payment.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    paymentInfo: [{
      id: ''
    }],
    debtInfo: {},
    volume: '',
    volumeTags: [10, 20, 30, 50],
    amount: '0.00',
    amountTip: '请输入1-999之间的数字',
    numberFormat: app.$util.numberFormat
  },

  setAmount(e) {
    const {
      value
    } = e.target.dataset;
    let val = value || e.detail.value;
    const {
      price,
      totalDebt,
    } = this.data.debtInfo;
    this.setData({
      amount: (val * Number(price) + Number(totalDebt)).toFixed(2),
      volume: val || ''
    })
  },
  toOtherPage(e) {
    const {
      url
    } = e.target.dataset;
    wx.navigateTo({
      url: `/pages/payment/${url}/${url}`,
    })
  },
  submit() {
    const {
      volume,
      amount
    } = this.data;
    if (!volume) {
      wx.showToast({
        title: '请输入用水量',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (!(/^\d{1,3}$/.test(volume)) || volume < 1) {
      wx.showToast({
        title: '输入用水量格式有误',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    const self = this;
    app.$http.get('/user/getOrderInfo', {
      payfee: amount
    }).then(({
      status,
      data = {}
    }) => {
      if (status == 0) {
        const {
          nonceStr,
          outTradeNo,
          packages,
          paySign,
          signType,
          timeStamp
        } = data
        wx.requestPayment({
          timeStamp, // 时间戳从1970年1月1日00:00:00至今的秒数,即当前的时间
          nonceStr, // 随机字符串，长度为32个字符以下。
          package: packages, // 统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=*
          signType, // 签名类型，默认为MD5，支持HMAC-SHA256和MD5。注意此处需与统一下单的签名类型一致
          paySign, // 签名,具体签名方案参见微信公众号支付帮助文档;
          success: function (res) {
            app.$http.get('/user/payFee', {
              fee: amount,
              customerCode: self.data.debtInfo.accountNumber,
              outTradeNo
            }).then(({
              status,
              data = {},
              msg
            }) => {
              if (status == 0) {
                wx.showToast({
                  title: msg,
                  icon: 'success',
                  duration: 2000
                })
              } else {
                wx.showToast({
                  title: msg,
                  icon: 'none',
                  duration: 2000
                })
              }
              self.getDebtInfo();
            }).catch(() => {
              wx.showToast({
                title: '缴费失败',
                icon: 'none',
                duration: 2000
              })
            })
          },
          fail: function (res) {
            if (res.errMsg == "requestPayment:fail cancel") return;
            wx.showToast({
              title: '缴费失败',
              icon: 'none',
              duration: 2000
            })
          }
        })
      }
    })
  },
  getLastPayRecord() {
    app.$http.get('/user/getLastPayRecord').then(({
      status,
      data = {}
    }) => {
      if (status == 0) {
        if (data == "" || data.fee == "") {
          this.setData({
            amountTip: `上次缴费金额0.00元`
          })
        } else {
          data.fee = app.$util.numberFormat(data.fee, 2);
          this.setData({
            amountTip: `上次缴费金额${data.fee || 0}元`
          })
        }

      }
    })
  },
  // GET /user/getDebtInfo
  getDebtInfo() {
    app.showLoading();
    app.$http.get('/user/getDebtInfo').then(({
      status,
      data = {}
    }) => {
      if (status == 0) {
        const {
          totalDebt = 0, remaining = 0, price = 0
        } = data;
        data.remaining = app.$util.numberFormat(remaining, 2);
        data.totalDebt = app.$util.numberFormat(totalDebt, 2);
        data.volume = Math.floor(remaining / price);
        this.setData({
          debtInfo: data,
          /* amount: data.totalDebt || 0.00 */
        })
      }
      app.hideLoading();
    }).catch(() => {
      app.hideLoading();
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getDebtInfo();
  },
})