import { couponListApi } from '../../api/other';
Page({
  data: {
    couponList: [],
    page: 1,
    pageSize: 10,
    loadingMore: false,
    noMore: false,
    refreshing: false
  },

  onLoad() {
    this.loadData(true);
  },
  async loadData(isRefresh = false) {
    if (this.data.loadingMore) return;
    let page = isRefresh ? 1 : this.data.page;
    this.setData({ loadingMore: true });
    try {
      const res = await couponListApi({ page, pageSize: this.data.pageSize });

      const statusImgMap = {
        used: '/static/image/yhx.png',   // 已核销
        unused: '/static/image/whx.png', // 未核销
      };

      const newList = res.data.list || [];
      let allList = isRefresh ? newList : [...this.data.couponList, ...newList];
      // allList = allList.map(item => ({
      //   ...item,
      //   typeText: item.type === 1 ? '菜品券' : '通用券',
      //   statusImg: statusImgMap[item.status] || '/static/image/whx.png',
      //   expireTime: item.expire_time || '--'
      // }));

      this.setData({
        couponList: allList,
        loadingMore: false,
        page: page + 1,
        noMore: allList.length >= res.data.total,
        refreshing: false
      });
    } catch (err) {
      console.error(err);
      wx.showToast({ title: '加载失败', icon: 'none' });
      this.setData({
        loadingMore: false,
        refreshing: false
      });
    }
  },
  // 上拉触底
  onReachBottom() {
    if (this.data.noMore) return;
    this.loadData();
  },

  // 下拉刷新
  onPullDownRefresh() {
    if (this.data.refreshing) return;
    this.setData({ refreshing: true, noMore: false, page: 1 });
    this.loadData(true);
  },
  goPage(e) {
    const coupon = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: `/pages/coupon-detail/coupon-detail?id=${coupon.id}`
    });
  }
});