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

Page({
  data: {
    memberInfo: {},
    allCoupons: [],
    availableCoupons: [],
    usedCoupons: [],
    expiredCoupons: [],
    activeTab: 'available' // available, used, expired
  },

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

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

  onShow() {
    this.loadData();
  },

  loadData() {
    const memberInfo = memberService.getUserMemberInfo();
    const allCoupons = memberInfo.coupons || [];
    const now = new Date();

    // 分类优惠券
    const availableCoupons = [];
    const usedCoupons = [];
    const expiredCoupons = [];

    allCoupons.forEach(coupon => {
      if (coupon.used) {
        usedCoupons.push(coupon);
      } else if (new Date(coupon.expireDate) <= now) {
        expiredCoupons.push(coupon);
      } else {
        availableCoupons.push(coupon);
      }
    });

    this.setData({
      memberInfo,
      allCoupons,
      availableCoupons,
      usedCoupons,
      expiredCoupons
    });
  },

  // 切换选项卡
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab
    });
  },

  // 复制优惠券码（如果有的话）
  copyCouponCode(e) {
    const couponId = e.currentTarget.dataset.id;
    wx.setClipboardData({
      data: couponId,
      success: () => {
        wx.showToast({
          title: '已复制优惠券ID',
          icon: 'success'
        });
      }
    });
  },

  // 查看优惠券详情
  viewCouponDetail(e) {
    const couponId = e.currentTarget.dataset.id;
    const coupon = this.data.allCoupons.find(c => c.id === couponId);
    
    if (coupon) {
      const expireDays = Math.ceil((new Date(coupon.expireDate) - new Date()) / (1000 * 60 * 60 * 24));
      
      wx.showModal({
        title: '优惠券详情',
        content: `优惠券：${coupon.name}\n价值：¥${coupon.value}\n状态：${coupon.used ? '已使用' : expireDays > 0 ? '可使用' : '已过期'}\n${coupon.used ? '使用时间：' + coupon.usedDate?.split('T')[0] : expireDays > 0 ? `剩余${expireDays}天` : '已过期'}\n获得时间：${coupon.createDate.split('T')[0]}`,
        showCancel: false
      });
    }
  },

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