// pages/referrals/referrals.js
const api = require('../../utils/api')
const util = require('../../utils/util')

Page({
  data: {
    // 导航栏高度
    statusBarHeight: 44,
    navBarHeight: 44,
    totalNavHeight: 88,

    // 统计数据
    stats: {
      totalReferrals: 0,
      totalContribution: 0
    },

    // 推荐用户列表
    list: [],
    defaultAvatar: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=500&auto=format&fit=crop&q=60',

    // 分页
    page: 1,
    pageSize: 20,
    total: 0,
    hasMore: true,

    // 状态
    loading: false,
    isEmpty: false,

    // 搜索与筛选
    searchKeyword: '',
    levelFilter: '',
    levelRange: [
      { label: '全部等级', value: '' },
      { label: '心伴会员', value: 'soulmate' },
      { label: '守护会员', value: 'guardian' },
      { label: '陪伴会员', value: 'companion' },
      { label: '倾听会员', value: 'listener' },
      { label: '城市合伙人', value: 'partner' }
    ],
    levelIndex: 0
  },

  onLoad(options) {
    // 计算导航栏高度
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight || 44
    const menuButton = wx.getMenuButtonBoundingClientRect()
    const navBarHeight = menuButton.height + (menuButton.top - statusBarHeight) * 2
    const totalNavHeight = statusBarHeight + navBarHeight

    this.setData({
      statusBarHeight,
      navBarHeight,
      totalNavHeight
    })

    // 加载数据
    this.loadReferrals()
  },

  /**
   * 加载推荐用户列表
   */
  async loadReferrals(page = 1) {
    if (this.data.loading) return

    this.setData({ loading: true })

    try {
      const res = await api.commission.getReferrals({
        page,
        pageSize: this.data.pageSize,
        keyword: this.data.searchKeyword,
        level: this.data.levelFilter
      })

      console.log('推荐用户列表 API 响应:', res)

      // 处理不同的响应格式
      let listData = []
      let totalCount = 0

      if (res.success && res.data) {
        // 格式1: { success: true, data: { list: [...], total: 0 } }
        listData = res.data.list || res.data || []
        totalCount = res.data.total || 0
      } else if (res.list) {
        // 格式2: { list: [...], total: 0 }
        listData = res.list || []
        totalCount = res.total || 0
      } else if (Array.isArray(res)) {
        // 格式3: [...]
        listData = res
        totalCount = res.length
      } else {
        // 未知格式，设为空数组
        console.warn('未知的 API 响应格式:', res)
        listData = []
        totalCount = 0
      }

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

      // 预处理列表数据，增加等级显示
      const listDataProcessed = listData.map(item => {
        const roleCode = item.distributorRole || item.role || '';
        
        // 处理头像
        let avatar = item.userAvatar || item.avatar || item.avatarUrl;
        if (avatar) {
          avatar = util.getFullImageUrl(avatar);
        }

        return {
          ...item,
          userAvatar: avatar || this.data.defaultAvatar,
          levelText: roleMap[roleCode] || (item.isDistributor ? '分销会员' : '普通用户')
        };
      });

      const list = page === 1 ? listDataProcessed : [...this.data.list, ...listDataProcessed];
      const hasMore = listData.length === this.data.pageSize
      const isEmpty = list.length === 0

      // 计算统计数据
      const stats = {
        totalReferrals: totalCount,
        totalContribution: this.calculateTotalContribution(list)
      }

      this.setData({
        stats,
        list,
        page,
        total: totalCount,
        hasMore,
        isEmpty,
        loading: false
      })
    } catch (error) {
      console.error('加载推荐用户列表失败:', error)
      this.setData({ loading: false })
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      })
    }
  },

  /**
   * 计算累计贡献金额
   */
  calculateTotalContribution(list) {
    return list.reduce((sum, item) => sum + (item.totalContribution || 0), 0)
  },

  /**
   * 格式化金额
   */
  formatMoney(amount) {
    return util.formatMoney(amount)
  },

  /**
   * 格式化时间
   */
  formatTime(timestamp) {
    return util.formatDate(timestamp)
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.loadReferrals(1).then(() => {
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 上拉加载更多
   */
  onReachBottom() {
    if (!this.data.hasMore || this.data.loading) return
    this.loadReferrals(this.data.page + 1)
  },

  /**
   * 返回上一页
   */
  onBack() {
    wx.navigateBack()
  },

  /**
   * 重新加载
   */
  onRetry() {
    this.loadReferrals(1)
  },

  /**
   * 搜索输入
   */
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
  },

  /**
   * 确认搜索
   */
  onSearch() {
    this.loadReferrals(1)
  },

  /**
   * 清除搜索
   */
  onClearSearch() {
    this.setData({
      searchKeyword: ''
    })
    this.loadReferrals(1)
  },

  /**
   * 等级筛选
   */
  onLevelChange(e) {
    const index = e.detail.value
    const level = this.data.levelRange[index].value
    this.setData({
      levelIndex: index,
      levelFilter: level
    })
    this.loadReferrals(1)
  },

  /**
   * 查看用户订单
   */
  viewOrders(e) {
    const item = e.currentTarget.dataset.item
    const userInfo = encodeURIComponent(JSON.stringify({
      userId: item.userId,
      name: item.userName,
      avatar: item.userAvatar,
      contribution: item.totalContribution
    }))
    wx.navigateTo({
      url: `/pages/referrals/orders/orders?userInfo=${userInfo}`
    })
  }
})
