import memberService from '../../utils/member.js';

Page({
  data: {
    memberInfo: {},
    pointsProducts: [],
    selectedProduct: null,
    showExchangeModal: false,
    coupons: []
  },

  onLoad() {
    this.loadData();
    
    // 添加数据变化监听器
    this.memberDataListener = (memberInfo) => {
      this.loadData();
    };
    memberService.addListener(this.memberDataListener);
  },

  onUnload() {
    // 移除监听器
    if (this.memberDataListener) {
      memberService.removeListener(this.memberDataListener);
    }
  },

  onShow() {
    // 每次显示页面时刷新数据
    this.loadData();
    
    // 清理过期积分
    memberService.cleanExpiredPoints();
  },

  loadData() {
    const memberInfo = memberService.getUserMemberInfo();
    const pointsProducts = memberService.POINTS_PRODUCTS;
    const coupons = memberService.getAvailableCoupons();

    this.setData({
      memberInfo,
      pointsProducts,
      coupons
    });
  },

  // 选择商品兑换
  selectProduct(e) {
    const productId = e.currentTarget.dataset.id;
    const product = this.data.pointsProducts.find(p => p.id === productId);
    
    this.setData({
      selectedProduct: product,
      showExchangeModal: true
    });
  },

  // 关闭兑换弹窗
  closeExchangeModal() {
    this.setData({
      showExchangeModal: false,
      selectedProduct: null
    });
  },

  // 确认兑换
  confirmExchange() {
    const { selectedProduct } = this.data;
    
    if (!selectedProduct) return;
    
    wx.showLoading({
      title: '兑换中...'
    });

    const result = memberService.exchangePoints(selectedProduct.id);
    
    wx.hideLoading();
    
    if (result.success) {
      wx.showToast({
        title: '兑换成功',
        icon: 'success'
      });
      
      // 刷新数据
      this.loadData();
      this.closeExchangeModal();
      
      // 显示获得的优惠券信息
      setTimeout(() => {
        wx.showModal({
          title: '兑换成功',
          content: `恭喜您获得${result.coupon.name}，有效期${Math.ceil((new Date(result.coupon.expireDate) - new Date()) / (1000 * 60 * 60 * 24))}天`,
          showCancel: false
        });
      }, 1500);
      
    } else {
      wx.showToast({
        title: result.message,
        icon: 'none'
      });
    }
  },

  // 查看积分明细
  viewPointsHistory() {
    wx.navigateTo({
      url: '../points-history/points-history'
    });
  },

  // 查看我的优惠券
  viewMyCoupons() {
    wx.navigateTo({
      url: '../my-coupons/my-coupons'
    });
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  }
});
