const api = require('../../utils/api');
const util = require('../../utils/util');

Page({
  data: {
    activeTab: 'upcoming', // upcoming | ended
    activities: [],
    loading: false,
    hasMore: true,
    page: 1,
    limit: 20,
    statusBarHeight: 20
  },

  onLoad() {
    this.setData({
      statusBarHeight: wx.getSystemInfoSync().statusBarHeight
    });
    this.loadActivities(true);
  },

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

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadActivities(false);
    }
  },

  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    if (tab === this.data.activeTab) return;
    
    this.setData({
      activeTab: tab,
      activities: [],
      page: 1,
      hasMore: true
    }, () => {
      this.loadActivities(true);
    });
  },

  async loadActivities(isRefresh = false) {
    if (this.data.loading) return;
    
    this.setData({ loading: true });
    if (isRefresh) {
      this.setData({ page: 1, hasMore: true });
    }

    try {
      // 映射 tab 到 API 的 time_status
      const timeStatusMap = {
        'upcoming': 'upcoming',
        'ended': 'finished'
      };

      const res = await api.activity.getMyRegistrations({
        page: this.data.page,
        limit: this.data.limit,
        time_status: timeStatusMap[this.data.activeTab]
      });

      if (res.success && res.data) {
        const newList = res.data.list.map(item => {
          // 格式化日期和图片
          return {
            ...item,
            cover_image: util.getFullImageUrl(item.cover_image || item.coverImage),
            date_display: item.start_date || item.activityDate,
            // 映射时间状态文字
            time_status_text: this.getTimeStatusText(item.activity_time_status),
            time_status_class: item.activity_time_status
          };
        });

        this.setData({
          activities: isRefresh ? newList : [...this.data.activities, ...newList],
          page: this.data.page + 1,
          hasMore: newList.length === this.data.limit
        });
      }
    } catch (err) {
      console.error('Load my activities failed', err);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  getTimeStatusText(status) {
    const map = {
      'pending': '待开始',
      'started': '进行中',
      'finished': '已结束'
    };
    return map[status] || '';
  },

  goDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/activity-detail/activity-detail?id=${id}`
    });
  },

  goBack() {
    wx.navigateBack();
  }
});
