/**
 * 优惠券页面
 */
const api = require('../../utils/api');

Page({
  data: {
    tab: 'available',
    myTab: 'unused',
    availableCoupons: [],
    myCoupons: [],
    loading: true
  },

  onLoad() {
    this.loadAvailable();
  },

  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ tab });
    if (tab === 'available' && this.data.availableCoupons.length === 0) {
      this.loadAvailable();
    } else if (tab === 'my' && this.data.myCoupons.length === 0) {
      this.loadMyCoupons();
    }
  },

  switchMyTab(e) {
    this.setData({ myTab: e.currentTarget.dataset.tab });
    this.loadMyCoupons();
  },

  async loadAvailable() {
    this.setData({ loading: true });
    try {
      const list = await api.getCoupons();
      this.setData({ availableCoupons: Array.isArray(list) ? list : [] });
    } catch (err) {
      console.error('优惠券加载失败:', err);
    } finally {
      this.setData({ loading: false });
    }
  },

  async loadMyCoupons() {
    this.setData({ loading: true });
    try {
      const list = await api.getMyCoupons({ status: this.data.myTab });
      this.setData({ myCoupons: Array.isArray(list) ? list : [] });
    } catch (err) {
      console.error('我的优惠券加载失败:', err);
    } finally {
      this.setData({ loading: false });
    }
  },

  couponTypeValue(coupon) {
    if (coupon.type === 'fixed') return coupon.value;
    if (coupon.type === 'percent') return coupon.value + '%';
    if (coupon.type === 'shipping') return '免邮';
    return coupon.value || 0;
  },

  couponValue(coupon) {
    return coupon.value || 0;
  },

  async onReceive(e) {
    const id = e.currentTarget.dataset.id;
    const index = e.currentTarget.dataset.index;
    try {
      await api.receiveCoupon(id);
      wx.showToast({ title: '领取成功', icon: 'success' });
      // 标记已领取
      const key = `availableCoupons[${index}].received`;
      this.setData({ [key]: true });
    } catch (err) {}
  }
});
