/**
 * 首页
 */
const api = require('../../utils/api');

Page({
  data: {
    banners: [],
    recommendProducts: [],
    seckillList: [],
    decorEnabled: false,
    decorComponents: [],
    seckillCountdown: '',
    loadingProducts: false,
    navItems: [
      { icon: '🏷️', label: '促销中心', page: 'promotion' },
      { icon: '🤝', label: '拼团', page: 'group-buy' },
      { icon: '⚡', label: '秒杀', page: 'seckill' },
      { icon: '👑', label: '会员', page: 'membership' },
      { icon: '✅', label: '签到', page: 'checkin' },
      { icon: '📄', label: '优惠券', page: 'coupon' },
      { icon: '🎁', label: '积分兑换', page: 'exchange' },
      { icon: '💰', label: '余额充值', page: 'recharge' },
      { icon: '📢', label: '分销', page: 'distribution' }
    ]
  },

  onLoad() {
    this.loadData();
    this.loadDecor();
  },

  onShow() {
    // 页面显示时刷新购物车角标
    this.updateCartBadge();
  },

  async loadData() {
    wx.showLoading({ title: '加载中...', mask: true });
    try {
      const [banners, recommend, seckill] = await Promise.all([
        api.getBanners().catch(() => []),
        api.getRecommendProducts().catch(() => []),
        api.getSeckillList().catch(() => [])
      ]);
      this.setData({
        banners: Array.isArray(banners) ? banners : [],
        recommendProducts: Array.isArray(recommend) ? recommend.slice(0, 6) : [],
        seckillList: Array.isArray(seckill) ? seckill : []
      });
      if (seckill.length > 0) {
        this.startSeckillCountdown(seckill[0]);
      }
    } catch (err) {
      console.error('首页加载失败:', err);
    } finally {
      wx.hideLoading();
    }
  },

  async loadDecor() {
    try {
      const r = await api.get('/design/render/miniapp', { page: 'home' });
      if (r && r.code === 0 && r.data && r.data.enabled) {
        const comps = (r.data.components || []).map(c => ({ ...c, props: c.props || {}, products: [] }));
        this.setData({ decorEnabled: true, decorComponents: comps });
        this.fetchDecorGoods();
      } else {
        this.setData({ decorEnabled: false });
      }
    } catch (e) {
      this.setData({ decorEnabled: false });
    }
  },
  async fetchDecorGoods() {
    const decor = require('../../utils/decor');
    await decor.fetchGoods(this);
    this.startAllCountdowns();
  },
  // v1.8: 所有倒计时横幅启动
  startAllCountdowns() {
    const comps = this.data.decorComponents || [];
    comps.forEach((c) => {
      if (c.type === 'countdownBanner' && c.props.endTime && !c._timing) {
        c._timing = true;
        const end = new Date(String(c.props.endTime)).getTime();
        const update = () => {
          if (!this.data.decorComponents) return;
          const diff = Math.max(0, Math.floor((end - Date.now()) / 1000));
          const pad = (n) => (n < 10 ? '0' + n : '' + n);
          c.props.d = pad(Math.floor(diff / 86400));
          c.props.h = pad(Math.floor(diff % 86400 / 3600));
          c.props.m = pad(Math.floor(diff % 3600 / 60));
          c.props.s = pad(diff % 60);
          if (this.setData) this.setData({ decorComponents: comps });
        };
        if (this._cdbTimer) clearInterval(this._cdbTimer);
        update();
        this._cdbTimer = setInterval(update, 1000);
      }
    });
  },
  onDecorProduct(e) {
    const id = e.currentTarget.dataset.id;
    if (id) this.goProduct({ currentTarget: { dataset: { id } } });
  },
  onClaimCoupon(e) {
    const decor = require('../../utils/decor');
    decor.claimCoupon(this, e);
  },
  onDecorCategory(e) {
    wx.switchTab({ url: '/pages/category/category' });
  },
  onDecorNav(e) {
    const link = e.currentTarget.dataset.link || '';
    if (!link) return;
    this.onNavTap({ currentTarget: { dataset: { index: this.data.navItems.findIndex(n => n.page === link.replace('/', '')) } } });
  },

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

  updateCartBadge() {
    const app = getApp();
    const token = api.getToken();
    if (!token) return;
    api.getCartList().then(list => {
      const count = Array.isArray(list) ? list.reduce((s, c) => s + (c.quantity || 1), 0) : 0;
      app.globalData.cartCount = count;
      if (count > 0) {
        wx.setTabBarBadge({ index: 2, text: String(count > 99 ? '99+' : count) });
      } else {
        wx.removeTabBarBadge({ index: 2 });
      }
    }).catch(() => {});
  },

  onSearch() {
    wx.navigateTo({ url: '/pages/category/category' });
  },

  onNavTap(e) {
    const { index } = e.currentTarget.dataset;
    const item = this.data.navItems[index];
    if (!item || !item.page) {
      wx.showToast({ title: '功能开发中', icon: 'none' });
      return;
    }
    const urlMap = {
      promotion: '/pages/promotion/promotion',
      seckill: '/pages/seckill/seckill',
      coupon: '/pages/coupon/coupon',
      'group-buy': '/pages/group-buy/group-buy',
      membership: '/pages/membership/membership',
      checkin: '/pages/checkin/checkin',
      exchange: '/pages/exchange/exchange',
      recharge: '/pages/recharge/recharge',
      distribution: '/pages/distribution/distribution'
    };
    const app = getApp();
    const needLogin = ['checkin', 'exchange', 'recharge', 'distribution'];
    if (needLogin.includes(item.page) && !app.checkLogin()) {
      app.requireLogin();
      return;
    }
    const url = urlMap[item.page];
    if (url) wx.navigateTo({ url });
  },

  goSeckill() {
    wx.navigateTo({ url: '/pages/seckill/seckill' });
  },

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

  onSwiperChange(e) {},

  onBannerError(e) {},

  onShareAppMessage() {
    return {
      title: '省胜优铺 轻商城 - 精选好货',
      path: '/pages/index/index'
    };
  },

  onPullDownRefresh() {
    this.loadData().then(() => wx.stopPullDownRefresh());
  },

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