import memberService from '../../utils/member.js';

Page({
  data: {
    memberInfo: {},
    pointsHistory: [],
    filteredHistory: [],
    filterType: 'all' // all, earn, exchange, upgrade
  },

  onLoad() {
    this.loadData();
    
    // 添加数据变化监听器
    this.memberDataListener = (memberInfo) => {
      this.loadData();
    };
    memberService.addListener(this.memberDataListener);
  },

  onUnload() {
    // 移除监听器
    if (this.memberDataListener) {
      memberService.removeListener(this.memberDataListener);
    }
  },

  loadData() {
    const memberInfo = memberService.getUserMemberInfo();
    const pointsHistory = memberInfo.pointsHistory || [];

    this.setData({
      memberInfo,
      pointsHistory,
      filteredHistory: pointsHistory
    });
  },

  // 筛选历史记录
  filterHistory(e) {
    const type = e.currentTarget.dataset.type;
    const { pointsHistory } = this.data;
    
    let filteredHistory = pointsHistory;
    
    if (type !== 'all') {
      filteredHistory = pointsHistory.filter(item => item.type === type);
    }
    
    this.setData({
      filterType: type,
      filteredHistory
    });
  },

  // 格式化日期
  formatDate(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (days === 0) {
      return '今天';
    } else if (days === 1) {
      return '昨天';
    } else if (days < 30) {
      return `${days}天前`;
    } else {
      return date.toLocaleDateString();
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  }
});
