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

Page({
  data: {
    cardList: [],
    page: 1,
    pageSize: 2,
    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 enrollRecord({ page, pageSize: this.data.pageSize });
      const statusImgMap = {
        0: '/static/image/register/wks.png',
        1: '/static/image/register/yjs.png',
        2: '/static/image/register/jxz.png'
      };

      const newList = res.data.list || [];
      let allList = isRefresh ? newList : [...this.data.cardList, ...newList];
      allList = allList.map(item => ({
        ...item,
        img: statusImgMap[item.status],
        genderText: item.gender == 0 ? '女' : '男'
      }));

      this.setData({
        cardList: 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);
  }
});