// pages/integral-pay/integral-pay.js
import {
  getMoneyAccountDetail,
  saveMpOrder,
  wxPayOrder,
  changeMpCompaignsRewards,
  changeMpCompaignsActivity
} from '../../../../services/index.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    choose_index: '',
    money: '0.00',
    compaigns_type: {
      gift: 1,
      activity: 2
    }
  },
  /**
   * 选择付款方式
   */
  choose(e) {
    const choose_index = e.currentTarget.dataset.index;
    if (choose_index === '0' && this.data.money > this.data.moneyBalance) {
      wx.showToast({
        icon: 'none',
        title: '余额不足'
      })
      return
    }
    this.setData({
      choose_index
    })
  },
  /**
   * 微信支付
   * @actuallyMoney  支付的金额
   * pay_type 支付的方式 0：微信；1：支付宝
   */
  pay(message) {
    saveMpOrder({
      user_id: wx.getStorageSync('user_id'),
      user_token: wx.getStorageSync('user_token'),
      member_id: wx.getStorageSync('member_id'),
      compaignssettingId: this.data.id,
      compaigns_type: this.data.compaigns_type[this.data.type],
      phone: this.data.phone,
      pay_type: 0,
    }).then(res => {
      if (res.errcode === 0) {
        wxPayOrder({
          user_id: wx.getStorageSync('user_id'),
          orderId: res.data.mpMemberOrder.id
        }).then(res => {
          if (res.data.resultStr) {
            const data = JSON.parse(res.data.resultStr)[0];
            wx.showLoading({
              mask: true,
              title: '支付中...',
            })
            wx.requestPayment({
              ...data,
              success: (res) => {
                if (res.errMsg === "requestPayment:ok") {
                  wx.hideLoading();
                  wx.showModal({
                    title: message,
                    content: '您可以在兑换记录中查看详情。',
                    showCancel: false,
                    success: res => {
                      if (res.confirm) {
                        this.changePoints()
                      }
                    }
                  })
                  // wx.showToast({
                  //   mask: true,
                  //   title: '支付成功',
                  //   success: _ => {
                  //     setTimeout(() => {
                  //       wx.navigateBack({
                  //         delta: 2,
                  //       })
                  //     }, 1500)
                  //   }
                  // })
                }
              },
              fail: function(res) {
                const title = res.errMsg === 'requestPayment:fail cancel' ? '支付取消' : '支付失败，请稍后重试'
                wx.showToast({
                  mask: true,
                  icon: 'none',
                  title,
                })
              },
              complete: () => {
                wx.hideLoading()
              }
            })
          } else {
            wx.showToast({
              mask: true,
              icon: 'none',
              title: '支付失败，请稍后重试'
            })
          }
        })
      }
    })
  },
  /**
   * 获取钱包余额
   */
  getMoneyBalance() {
    getMoneyAccountDetail({
      user_id: wx.getStorageSync('user_id'),
      user_token: wx.getStorageSync('user_token'),
      member_id: wx.getStorageSync('member_id'),
    }).then(res => {
      if (res.errcode === 0) {
        this.setData({
          moneyBalance: res.data.MpMemberAccountAPI.moneyBalance.toFixed(2)
        })
      }
    })
  },
  /**
   * 兑换礼品
   */
  gift(choose_index, func) {
    changeMpCompaignsRewards({
      user_id: wx.getStorageSync('user_id'),
      user_token: wx.getStorageSync('user_token'),
      member_id: wx.getStorageSync('member_id'),
      phone: this.data.phone,
      mpCompaignsRewardSettingId: this.data.id,
      withdrawType: choose_index
    }).then(res => {
      if (res.errcode === 0) {
        if (choose_index === '1') {
          func && func(res.errmsg)
        }
        if (choose_index === '0') {
          wx.showModal({
            title: res.errmsg,
            content: '您可以在兑换记录中查看详情。',
            showCancel: false,
            success: res => {
              if (res.confirm) {
                this.changePoints()
              }
            }
          })
        }
      }
    }).catch(res => {
      setTimeout(_ => {
        wx.navigateBack({
          delta: 2
        })
      }, 1500)
    })
  },
  /**
   * 兑换活动
   */
  activity(choose_index, func) {
    changeMpCompaignsActivity({
      user_id: wx.getStorageSync('user_id'),
      user_token: wx.getStorageSync('user_token'),
      member_id: wx.getStorageSync('member_id'),
      phone: this.data.phone,
      mpCompaignsActivitySettingId: this.data.id,
      withdrawType: choose_index
    }).then(res => {
      if (res.errcode === 0) {
        if (choose_index === '1') {
          func && func(res.errmsg)
        }
        if (choose_index === '0') {
          wx.showModal({
            title: res.errmsg,
            content: '您可以在兑换记录中查看详情。',
            showCancel: false,
            success: res => {
              if (res.confirm) {
                this.changePoints()
              }
            }
          })
        }
      }
    }).catch(res => {
      setTimeout(_ => {
        wx.navigateBack({
          delta: 2
        })
      }, 1500)
    })
  },
  /**
   * 购买
   */
  buy() {
    const choose_index = this.data.choose_index;
    this[this.data.type](choose_index, this.pay)
    // if (choose_index === '3') {
    //   this[this.data.type]()
    // }
  },
  /**
   * 更改积分总额
   */
  changePoints() {
    const _pageList = getCurrentPages();
    const _page = _pageList[_pageList.length - 3]
    _page.setData({
      integral: _page.data.integral - this.data.points
    }, _ => {
      wx.navigateBack({
        delta: 2,
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 获取钱包余额
    this.getMoneyBalance();
    // 获取应当支付的金额
    if (options.money) {
      this.setData({
        money: Number(options.money).toFixed(2),
        phone: options.phone,
        id: options.id,
        type: options.type,
        points: options.points
      })
    }
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },
})