import { storeList } from '../../api/other';

Page({
  data: {
    list: [],          // 门店列表
    page: 1,           // 当前页
    pageSize: 10,      // 每页条数
    loadingMore: false,// 是否正在加载
    noMore: false,     // 是否已没有更多数据
    refreshing: false  // 下拉刷新状态
  },

  onLoad() {
    // this.loadData(true);
  },

  // 请求数据
  async loadData(isRefresh = false) {
    if (this.data.loadingMore) return;
    this.setData({ loadingMore: true });
    const page = isRefresh ? 1 : this.data.page;
    try {
      const res = await storeList({ page, pageSize: this.data.pageSize });
      const newList = res.data.list || [];
      const allList = isRefresh ? newList : [...this.data.list, ...newList];
      this.setData({
        list: allList,
        loadingMore: false,
        page: page + 1,
        noMore: allList.length >= res.data.total,
        refreshing: false
      });
    } catch (err) {
      console.error(err);
      this.setData({ loadingMore: false, refreshing: false });
      wx.showToast({ title: '加载失败', icon: 'none' });
    }
  },
  // 页面触底事件
  onReachBottom() {
    if (!this.data.noMore) {
      this.loadData();
    }
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.loadData(true);
  },

  // 点击门店
  goDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/storeDetail/storeDetail?id=${id}`
    });
  },

  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({ selected: 1 });
    }
  }
});