mall.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. import memberService from '../../utils/member.js';
  2. Page({
  3. data: {
  4. memberInfo: {},
  5. pointsProducts: [],
  6. selectedProduct: null,
  7. showExchangeModal: false,
  8. coupons: []
  9. },
  10. onLoad() {
  11. this.loadData();
  12. // 添加数据变化监听器
  13. this.memberDataListener = (memberInfo) => {
  14. this.loadData();
  15. };
  16. memberService.addListener(this.memberDataListener);
  17. },
  18. onUnload() {
  19. // 移除监听器
  20. if (this.memberDataListener) {
  21. memberService.removeListener(this.memberDataListener);
  22. }
  23. },
  24. onShow() {
  25. if (typeof this.getTabBar === 'function' && this.getTabBar()) {
  26. this.getTabBar().setData({
  27. selected: 2
  28. });
  29. }
  30. // 每次显示页面时刷新数据
  31. this.loadData();
  32. // 清理过期积分
  33. memberService.cleanExpiredPoints();
  34. },
  35. loadData() {
  36. const memberInfo = memberService.getUserMemberInfo();
  37. const pointsProducts = memberService.POINTS_PRODUCTS;
  38. const coupons = memberService.getAvailableCoupons();
  39. this.setData({
  40. memberInfo,
  41. pointsProducts,
  42. coupons
  43. });
  44. },
  45. // 选择商品兑换
  46. selectProduct(e) {
  47. const productId = e.currentTarget.dataset.id;
  48. const product = this.data.pointsProducts.find(p => p.id === productId);
  49. this.setData({
  50. selectedProduct: product,
  51. showExchangeModal: true
  52. });
  53. },
  54. // 关闭兑换弹窗
  55. closeExchangeModal() {
  56. this.setData({
  57. showExchangeModal: false,
  58. selectedProduct: null
  59. });
  60. },
  61. // 确认兑换
  62. confirmExchange() {
  63. const { selectedProduct } = this.data;
  64. if (!selectedProduct) return;
  65. wx.showLoading({
  66. title: '兑换中...'
  67. });
  68. const result = memberService.exchangePoints(selectedProduct.id);
  69. wx.hideLoading();
  70. if (result.success) {
  71. wx.showToast({
  72. title: '兑换成功',
  73. icon: 'success'
  74. });
  75. // 刷新数据
  76. this.loadData();
  77. this.closeExchangeModal();
  78. // 显示获得的优惠券信息
  79. setTimeout(() => {
  80. wx.showModal({
  81. title: '兑换成功',
  82. content: `恭喜您获得${result.coupon.name},有效期${Math.ceil((new Date(result.coupon.expireDate) - new Date()) / (1000 * 60 * 60 * 24))}天`,
  83. showCancel: false
  84. });
  85. }, 1500);
  86. } else {
  87. wx.showToast({
  88. title: result.message,
  89. icon: 'none'
  90. });
  91. }
  92. },
  93. // 查看积分明细
  94. viewPointsHistory() {
  95. wx.navigateTo({
  96. url: '../points-history/points-history'
  97. });
  98. },
  99. // 查看我的优惠券
  100. viewMyCoupons() {
  101. wx.navigateTo({
  102. url: '../my-coupons/my-coupons'
  103. });
  104. }
  105. })