/**
 * 促销中心
 * 聚合秒杀/拼团/砍价/预售/领券, 后端 /api/marketing/promotion-center
 * 优惠券可直接领取(需登录)
 */
const api = require('../../utils/api');

Page({
  data: {
    loading: true,
    activeTab: 'all',
    tabs: [
      { v: 'all', label: '全部' },
      { v: 'seckill', label: '秒杀' },
      { v: 'groupon', label: '拼团' },
      { v: 'bargain', label: '砍价' },
      { v: 'presale', label: '预售' },
      { v: 'coupon', label: '领券' }
    ],
    list: [],
    filtered: []
  },

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

  async loadList() {
    this.setData({ loading: true });
    const data = await api.getPromotionCenter().catch(() => null);
    const list = (data && data.list) ? data.list.map(it => ({
      ...it,
      price_fmt: this.money(it.price),
      origin_fmt: this.money(it.origin_price),
      min_amount_fmt: this.money(it.min_amount),
      value_fmt: this.money(it.value)
    })) : [];
    this.setData({ list, loading: false });
    this.applyFilter();
  },

  money(v) {
    const n = Number(v) || 0;
    return n.toFixed(2);
  },

  switchTab(e) {
    const v = e.currentTarget.dataset.v;
    this.setData({ activeTab: v });
    this.applyFilter();
  },

  applyFilter() {
    const { list, activeTab } = this.data;
    const filtered = activeTab === 'all' ? list : list.filter(it => it.type === activeTab);
    this.setData({ filtered });
  },

  goActivity(e) {
    const type = e.currentTarget.dataset.type;
    const pid = e.currentTarget.dataset.pid;
    if (pid) {
      wx.navigateTo({ url: '/pages/product/product?id=' + pid });
    } else if (type) {
      const url = { seckill: '/pages/seckill/seckill', groupon: '/pages/group-buy/group-buy', bargain: '/pages/bargain/bargain', presale: '/pages/presale/presale' }[type];
      if (url) wx.navigateTo({ url });
    }
  },

  receiveCoupon(e) {
    const id = e.currentTarget.dataset.id;
    if (!id) return;
    if (!wx.getStorageSync('token')) {
      wx.navigateTo({ url: '/pages/login/login' });
      return;
    }
    const self = this;
    api.receiveCoupon(id).then(res => {
      if (res && (res.code === 0 || res.code === 200)) {
        wx.showToast({ title: '领取成功', icon: 'success' });
        self.loadList();
      } else {
        wx.showToast({ title: (res && res.message) || '领取失败', icon: 'none' });
      }
    }).catch(() => {
      wx.showToast({ title: '网络错误', icon: 'none' });
    });
  }
});
