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

Page({
  data: {
    statusBarHeight: 20,
    navHeight: 64,
    loading: false,
    list: [],
    page: 1,
    pageSize: 20,
    hasMore: true,
    individualPerformance: '0',
    teamTotalPerformance: '0',
    pendingAmount: '210.00',
    levelName: '',
    defaultAvatar: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=500&auto=format&fit=crop&q=60',
    currentTab: 'individual' // 'individual' | 'team'
  },

  onLoad() {
    console.log('[Performance] Page onLoad');
    this.loadStats()
    this.loadRecords()
  },

  onShow() {
    // 隐藏系统默认 TabBar
    wx.hideTabBar({ animation: false });
  },

  onPullDownRefresh() {
    this.setData({
      page: 1,
      hasMore: true,
      list: []
    }, () => {
      Promise.all([
        this.loadStats(),
        this.loadRecords()
      ]).then(() => {
        wx.stopPullDownRefresh()
      })
    })
  },

  onReachBottom() {
    if (this.data.loading || !this.data.hasMore) return
    this.setData({
      page: this.data.page + 1
    }, () => {
      this.loadRecords()
    })
  },

  async loadStats() {
    try {
      console.log('[Performance] Loading stats...');
      const res = await api.commission.getStats()
      console.log('[Performance] Stats response:', res);
      if (res.success && res.data) {
        const data = res.data
        // Mapping levels
        const roleMap = {
          'soulmate': '心伴会员',
          'guardian': '守护会员',
          'companion': '陪伴会员',
          'listener': '倾听会员',
          'partner': '城市合伙人'
        };
        
        const individual = Number(data.individualPerformance || data.individual_performance || 0);
        const team = Number(data.teamTotalPerformance || data.team_total_performance || 0);
        
        this.setData({
          individualPerformance: this.formatAmount(individual),
          teamTotalPerformance: this.formatAmount(individual + team), // 总业绩 = 个人 + 团队
          pendingAmount: Number(data.pendingAmount || data.pending_amount || 0).toFixed(2),
          totalCommission: Number(data.totalCommission || data.total_commission || 0).toFixed(2),
          levelName: roleMap[data.distributorRole || data.role] || data.distributorRoleName || '分销会员',
          isSoulmate: (data.distributorRole || data.role) === 'soulmate'
        })
      }
    } catch (err) {
      console.error('加载统计失败', err)
    }
  },

  /**
   * 格式化金额，超过一万显示为“x.x万”
   * @param {number|string} val 
   */
  formatAmount(val) {
    const num = Number(val || 0);
    if (num >= 10000) {
      return (num / 10000).toFixed(1) + '万';
    }
    return num.toFixed(2);
  },

  async loadRecords() {
    if (this.data.loading) return
    this.setData({ loading: true })

    try {
      console.log('[Performance] Loading records...', { page: this.data.page, scope: this.data.currentTab });
      const res = await api.commission.getRecords({
        page: this.data.page,
        limit: this.data.pageSize,
        scope: this.data.currentTab // Suggesting this parameter to backend
      })
      console.log('[Performance] Records response:', res);

      if (res.success && res.data) {
        const records = (res.data.list || res.data || []).map(record => this.transformRecord(record))
        
        this.setData({
          list: this.data.page === 1 ? records : [...this.data.list, ...records],
          hasMore: records.length === this.data.pageSize
        })
      }
    } catch (err) {
      console.error('加载记录失败', err)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    if (tab === this.data.currentTab) return
    
    this.setData({
      currentTab: tab,
      page: 1,
      list: [],
      hasMore: true
    }, () => {
      this.loadRecords()
    })
  },

  transformRecord(record) {
    const dateObj = new Date(record.created_at || record.createdAt)
    const fmtTime = util.formatTime(dateObj)

    let avatar = record.fromUserAvatar || record.userAvatar || record.avatar || '';
    if (avatar) {
      avatar = util.getFullImageUrl(avatar);
    }

    const roleMap = {
      'soulmate': '心伴会员',
      'guardian': '守护会员',
      'companion': '陪伴会员',
      'listener': '倾听会员',
      'partner': '城市合伙人'
    };

    // 优先使用API返回的中文等级名称
    const userLevel = record.fromUserRoleName || record.userRoleName || roleMap[record.fromUserRole] || roleMap[record.userRole] || record.levelText || '普通用户';

    return {
      id: record.id,
      orderNo: record.orderNo || record.order_no || record.id || '---',
      userName: record.fromUserName || record.userName || '匿名用户',
      userAvatar: avatar || this.data.defaultAvatar,
      productName: this.getOrderTypeText(record.orderType || record.type),
      userLevel: userLevel,
      orderAmount: record.orderAmount ? Number(record.orderAmount).toFixed(2) : (record.amount ? Number(record.amount).toFixed(2) : '0.00'),
      time: fmtTime
    }
  },

  onAvatarError(e) {
    const index = e.currentTarget.dataset.index;
    if (index !== undefined) {
      const list = this.data.list;
      list[index].userAvatar = '/images/default-avatar.svg';
      this.setData({ list });
    }
  },

  getOrderTypeText(type) {
    const map = {
      'recharge': '充值',
      'vip': 'VIP会员',
      'identity_card': '身份卡',
      'agent_purchase': '智能体购买',
      'companion_chat': '陪聊'
    }
    return map[type] || '推广订单'
  },

  goTeam() {
    wx.navigateTo({
      url: '/pages/team/team'
    })
  },

  onBack() {
    wx.navigateBack({
      delta: 1,
      fail: (err) => {
        console.error('[Performance] Back failed, navigating to profile', err);
        wx.switchTab({ url: '/pages/profile/profile' });
      }
    });
  }
})
