/**
 * 分类页面 - 带左侧导航的经典布局
 */
const api = require('../../utils/api');
const decor = require('../../utils/decor');

Page({
  data: {
    decorEnabled: false,
    decorComponents: [],
    categories: [],
    activeIndex: 0,
    currentCategory: {},
    products: [],
    page: 1,
    pageSize: 20,
    total: 0,
    loading: false,
    loadStatus: 'loading'
  },

  onLoad() {
    this.loadCategories();
    decor.init(this, 'category');
  },

  async loadCategories() {
    wx.showLoading({ title: '加载中...', mask: true });
    try {
      const cats = await api.getCategories();
      if (Array.isArray(cats) && cats.length > 0) {
        this.setData({ 
          categories: cats,
          activeIndex: 0,
          currentCategory: cats[0]
        });
        this.loadProducts(1, true);
      } else {
        this.setData({ categories: [], loadStatus: 'empty' });
      }
    } catch (err) {
      console.error('分类加载失败:', err);
      this.setData({ loadStatus: 'error' });
    } finally {
      wx.hideLoading();
    }
  },

  async loadProducts(page = 1, reset = false) {
    const { currentCategory, pageSize } = this.data;
    if (!currentCategory) return;

    if (reset) {
      this.setData({ loading: true, loadStatus: 'loading' });
      page = 1;
    }

    try {
      const result = await api.getCategoryProducts(currentCategory.id, {
        page,
        pageSize
      });

      const list = result.list || [];
      const total = result.total || 0;

      this.setData({
        products: reset ? list : this.data.products.concat(list),
        total,
        page,
        loading: false,
        loadStatus: this.data.products.length + list.length >= total ? 'nomore' : 'loading'
      });
    } catch (err) {
      this.setData({ loading: false, loadStatus: 'error' });
    }
  },

  onCategoryTap(e) {
    const { index } = e.currentTarget.dataset;
    if (index === this.data.activeIndex) return;
    const category = this.data.categories[index];
    this.setData({
      activeIndex: index,
      currentCategory: category,
      products: [],
      page: 1,
      total: 0
    });
    this.loadProducts(1, true);
  },

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

  onLoadMore() {
    const { loadStatus, page, total, products } = this.data;
    if (loadStatus === 'loading' && products.length < total) {
      this.loadProducts(page + 1);
    }
  },

  onShareAppMessage() {
    return {
      title: '省胜优铺 分类',
      path: '/pages/category/category'
    };
  },

  onDecorNav(e) {
    decor.onNav(this, e, {});
  },

  onDecorProduct(e) {
    const id = e.currentTarget.dataset.id;
    if (id) {
      if (typeof wx.getStorageSync === 'function') {
        try { wx.setStorageSync('_decor_cat_restore', this.data.decorEnabled ? true : false); } catch (q) {}
      }
      wx.navigateTo({ url: '/pages/product/product?id=' + id });
    }
  },
  onClaimCoupon(e) {
    const decor = require('../../utils/decor');
    decor.claimCoupon(this, e);
  },
  onDecorCategory(e) {
    if (typeof wx.switchTab === 'function') wx.switchTab({ url: '/pages/category/category' });
  }
});