/**
 * 秒杀页面
 */
const api = require('../../utils/api');

Page({
  data: {
    list: [],
    countdown: '00:00:00',
    loading: true
  },

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

  async loadSeckill() {
    this.setData({ loading: true });
    try {
      const list = await api.getSeckillList();
      this.setData({ list: Array.isArray(list) ? list : [] });
      if (list.length > 0) {
        this.startCountdown(list[0]);
      }
    } catch (err) {
      console.error('秒杀加载失败:', err);
    } finally {
      this.setData({ loading: false });
    }
  },

  startCountdown(seckill) {
    const endTime = new Date(seckill.end_time).getTime();
    const update = () => {
      const diff = endTime - Date.now();
      if (diff <= 0) {
        this.setData({ countdown: '已结束' });
        return;
      }
      const h = Math.floor(diff / 3600000);
      const m = Math.floor((diff % 3600000) / 60000);
      const s = Math.floor((diff % 60000) / 1000);
      this.setData({ countdown: `${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}` });
      this._timer = setTimeout(update, 1000);
    };
    update();
  },

  goProduct(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({ url: `/pages/product/product?id=${id}` });
  },

  onUnload() {
    if (this._timer) clearTimeout(this._timer);
  }
});
