// pages/index/activity/activity.js
const { museumApi } = require('../../../utils/api.js');
const { navigateToWebview, urlImg } = require('../../../utils/util.js');

Page({
  data: {
    activeList: [],
    loading: false,
    urlImg: urlImg,
    currentPage: 1,
    pageSize: 10,
    hasMore: true,
    loadingMore: false
  },

  onLoad() {
    this.getActivityList(true);
  },

  onPullDownRefresh() {
    this.getActivityList(true);
  },

  // 页面滚动到底部时触发
  onReachBottom() {
    if (this.data.hasMore && !this.data.loadingMore) {
      this.loadMore();
    }
  },

  // 获取活动列表
  async getActivityList(isRefresh = false) {
    const page = isRefresh ? 1 : this.data.currentPage;
    
    if (isRefresh) {
      this.setData({ loading: true });
    } else {
      this.setData({ loadingMore: true });
    }
    
    try {
      const response = await museumApi.getSocialActivityList({
        pageNum: page,
        pageSize: this.data.pageSize,
        status: 1
      });
      
      console.log('活动数据:', response);
      
      // 获取活动数据并进行筛选
      let activeList = response.records || response.list || response.data || response || [];
      
      // 筛选有效的活动数据 - 确保有activityId和title
      activeList = activeList.filter(item => {
        return item && item.activityId && item.title;
      });

      if (isRefresh) {
        // 刷新时替换数据
        this.setData({
          activeList,
          currentPage: 1,
          hasMore: activeList.length >= this.data.pageSize
        });
      } else {
        // 加载更多时追加数据
        this.setData({
          activeList: [...this.data.activeList, ...activeList],
          hasMore: activeList.length >= this.data.pageSize
        });
      }
    } catch (error) {
      console.error('获取活动数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      if (isRefresh) {
        this.setData({ activeList: [] });
      }
    } finally {
      this.setData({ 
        loading: false,
        loadingMore: false
      });
      if (isRefresh) {
        wx.stopPullDownRefresh();
      }
    }
  },

  // 加载更多数据
  loadMore() {
    const nextPage = this.data.currentPage + 1;
    this.setData({ currentPage: nextPage });
    this.getActivityList(false);
  },

  // 返回首页
  goBack() {
    wx.navigateBack();
  },

  // 查看活动详情
  viewActivity(e) {
    const item = e.currentTarget.dataset.item;
    console.log('查看活动详情:', item);
    // navigateToWebview(`/allDetailsShow?isFrom=weixin&id=${item.activityId}&type=activity`);
    wx.navigateTo({
      url: `/pages/exhibition/activeDetails/index?isFrom=weixin&id=${item.activityId}&type=activity`
    });
  }
});