const { request } = require('../../utils_new/request');
const util = require('../../utils/util');

Page({
  data: {
    statusBarHeight: 20,
    navBarHeight: 44,
    totalNavHeight: 64,
    defaultAvatar: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=500&auto=format&fit=crop&q=60',
    loading: true,
    stats: {
      todayReferrals: 0,
      totalReferrals: 0,
      totalContribution: '0.00'
    },
    cardTitle: '守护会员',
    list: []
  },
  onLoad() {
    const sys = wx.getSystemInfoSync();
    const menu = wx.getMenuButtonBoundingClientRect();
    const statusBarHeight = sys.statusBarHeight || 20;
    const navBarHeight = menu.height + (menu.top - statusBarHeight) * 2;
    this.setData({
      statusBarHeight,
      navBarHeight,
      totalNavHeight: statusBarHeight + navBarHeight
    });
    this.load();
  },
  onBack() {
    wx.navigateBack({ delta: 1 });
  },
  async load() {
    this.setData({ loading: true });
    try {
      try {
        const statsRes = await request({ url: '/api/commission?action=stats', method: 'GET' });
        const statsBody = statsRes.data || {};
        
        let currentRoleText = '守护会员'; // 默认
        
        // 尝试从本地存储获取当前用户信息来判断角色
        try {
          const userStr = wx.getStorageSync('user');
          if (userStr) {
            const user = JSON.parse(userStr);
            // 优先使用 distributorRole，其次 userRole，再次 vip_level
            const role = user.distributorRole || user.userRole;
            const roleMap = {
              'soulmate': '心伴会员',
              'guardian': '守护会员',
              'companion': '陪伴会员',
              'listener': '倾听会员',
              'partner': '城市合伙人'
            };
            if (role && roleMap[role]) {
              currentRoleText = roleMap[role];
            } else if (user.isDistributor) {
              // 如果是分销商但没有明确role，可能是早期数据，根据cardType判断
              // 但这里更直接用API返回的
            }
          }
        } catch (e) {
          console.error('解析用户信息失败', e);
        }

        if (statsBody.success) {
          const d = statsBody.data || {};
          // 如果API返回了明确的等级名称或类型，优先使用API的
          if (d.cardType || d.level) {
             currentRoleText = this.getCardTitle(d.cardType || d.level);
          }
          
          this.setData({
            stats: {
              todayReferrals: Number(d.todayReferrals || d.today_referrals || 0),
              totalReferrals: Number(d.totalReferrals || d.total_referrals || 0),
              totalContribution: Number(d.totalContribution || d.total_contribution || 0).toFixed(2)
            },
            cardTitle: currentRoleText
          });
        } else {
           // API不成功，使用本地推断的角色
           this.setData({ cardTitle: currentRoleText });
        }

        const res = await request({ url: '/api/commission?action=referrals&page=1&pageSize=50', method: 'GET' });
        const body = res.data || {};

        console.log('[团队页面] API响应:', JSON.stringify(body, null, 2));

        // Flexible data extraction
        let rawList = [];
        if (Array.isArray(body.data)) {
          rawList = body.data;
        } else if (body.data && Array.isArray(body.data.list)) {
          rawList = body.data.list;
        } else if (body.list && Array.isArray(body.list)) {
          rawList = body.list;
        }

        console.log('[团队页面] rawList:', JSON.stringify(rawList.slice(0, 2), null, 2));

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

        const list = rawList.map((x) => {
          const user = x.user || {};
          // Map fields robustly
          let avatar = x.avatarUrl || x.avatar_url || x.userAvatar || user.avatarUrl || user.avatar_url || '';
          if (avatar) {
            avatar = util.getFullImageUrl(avatar);
          }
          
          const name = x.userName || x.nickname || x.nickName || user.nickname || user.nickName || ('用户' + (x.userId || x.id || ''));
          const contribution = Number(x.totalContribution || x.total_contribution || x.amount || 0).toFixed(2);
          const dateStr = x.boundAt || x.created_at || x.createdAt || Date.now();
          
          // Get Member Level - 优先使用API返回的中文等级名称
          const levelText = x.userRoleName || user.userRoleName || roleMap[x.userRole] || roleMap[x.distributorRole] || roleMap[x.role] || (x.isDistributor ? '分销会员' : '普通用户');

          return {
            ...x,
            userId: x.userId || x.id,
            userAvatar: avatar || this.data.defaultAvatar,
            userName: name,
            levelText: levelText,
            totalContribution: contribution,
            boundAtText: this.formatDate(new Date(dateStr))
          };
        });

        this.setData({ list });
      } catch (err) {
        console.log('API failed, using mock data', err);
        this.setData({
          stats: { todayReferrals: 2, totalReferrals: 15, totalContribution: '128.50' },
          list: [
            { userId: 1, userName: '小王', userAvatar: '', boundAtText: '2025-01-20 10:30:45', totalContribution: '12.50' },
            { userId: 2, userName: 'Alice', userAvatar: '', boundAtText: '2025-01-18 14:22:30', totalContribution: '30.00' },
            { userId: 3, userName: 'Bob', userAvatar: '', boundAtText: '2025-01-15 09:15:00', totalContribution: '5.00' }
          ]
        });
      }
    } finally {
      this.setData({ loading: false });
    }
  },
  formatDate(d) {
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const h = String(d.getHours()).padStart(2, '0');
    const min = String(d.getMinutes()).padStart(2, '0');
    const s = String(d.getSeconds()).padStart(2, '0');
    return `${y}-${m}-${day} ${h}:${min}:${s}`;
  },
  onAvatarError(e) {
    const index = e.currentTarget.dataset.index;
    if (index !== undefined) {
      const list = this.data.list;
      list[index].userAvatar = this.data.defaultAvatar;
      this.setData({ list });
    }
  },
  getCardTitle(type) {
    const map = {
      'guardian_card': '守护会员',
      'companion_card': '陪伴会员',
      'soulmate_card': '心伴会员',
      'listener_card': '倾听会员',
      'guardian': '守护会员',
      'companion': '陪伴会员',
      'soulmate': '心伴会员',
      'listener': '倾听会员',
      'identity_card': '身份会员',
      'vip': 'VIP会员',
      'partner': '城市合伙人'
    };
    return map[type] || type || '守护会员';
  }
});

