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

  /**
   * 页面的初始数据
   */
  data: {
    paymentInfo: [{
      id: ''
    }],
    amount: '',
    amountTags: [50, 100, 150, 200],
    debtInfo: {},
    activeAmount: '',
    amountTip: '请输入金额',
    numberFormat: app.$util.numberFormat
  },

  setAmount(e) {
    const {
      value
    } = e.target.dataset;
    this.setData({
      amount: value || e.detail.value,
      activeAmount: value || ''
    })
  },
  toOtherPage(e) {
    const {
      url
    } = e.target.dataset;
    wx.navigateTo({
      url: `/pages/payment/${url}/${url}`,
    })
  },
  submit() {
    const {amount} = this.data;
    if(!amount) {
      wx.showToast({
        title: '请输入金额',
        icon:'none',
        duration: 2000
      })
      return;
    }
    if(!(/^\d{1,8}$|^\d{1,6}[.]\d{1,2}$/.test(amount))) {
      wx.showToast({
        title: '输入金额格式有误',
        icon:'none',
        duration: 2000
      })
      return;
    }
    if(amount < this.data.debtInfo.totalDebt) {
      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) {
        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 = JSON.parse(JSON.stringify(data.totalDebt));
        data.receFee = app.$util.numberFormat(data.receFee, 2);
        data.totalDebt = app.$util.numberFormat(data.totalDebt, 2);
        this.setData({
          debtInfo: data,
          amount: totalDebt || ''
        })
        if(totalDebt == 0) {
          this.getLastPayRecord();
        }
      }
      app.hideLoading();
    }).catch(() => {
      app.hideLoading();
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getDebtInfo();
  },
})