// pages/userCenter.js
const wxService = require('../../../../utils/wxService')

wxService.page({
  /**
   * 页面的初始数据
   */
  data: {
    query: '',
    integralCouponList: [], // 积分兑换优惠券列表
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu();
    this.initIntegralCouponList();
  },
  
  // 获取优惠券活动列表
  initIntegralCouponList(refresh) {
    wx.showLoading({
      title: '加载中'
    });

    wxService.post(`/coupon/couponCenterActivity/buyer/getValidList`).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          this.data.integralCouponList = data ? data : [];
          this.setData({
            integralCouponList: this.data.integralCouponList
          });
        }
      }

      if(refresh){
        wx.showToast({
          title: '刷新成功',
        });
        wx.stopPullDownRefresh();
      }

    }).finally(() => {
      wx.hideLoading();
    })
  },
  //立即兑换优惠券
  exchange(e) {
    wx.showLoading({
      title: '领取中..',
    });
    const { id } = e.currentTarget.dataset;
    wxService.post(`/coupon/couponCenterActivity/buyer/coupon/draw?id=${id}`).then(res => {
      wx.hideLoading();
      if(res){
        if(res.data.result == 0){
          wx.showToast({
            title: '领取成功',
          });
        }
        else{
          wx.showToast({
            title: '领取失败，请稍后再试',
            icon : 'none'
          });
        }
      }
    });
  },
  //跳转到详情
  goCouponDetail(e) {
    const { id } = e.currentTarget.dataset
    wxService.router(`/subPackage/page/pages/couponCenterInfo/couponCenterInfo?id=${id}`)
  },
  /**
  * 页面相关事件处理函数--监听用户下拉动作
  */
  onPullDownRefresh: function () { 
    this.initIntegralCouponList(true);
  },

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

  },
})