// 好友请求管理页面
const app = getApp();
const friendAPI = require('../../../utils/friend-api.js');

Page({
  data: {
    // 请求列表
    friendRequests: [],
    pendingRequests: [],
    processedRequests: [],
    loading: true,
    refreshing: false,
    
    // 统计
    pendingCount: 0,
    processedCount: 0,
    
    // 系统信息
    statusBarHeight: 0,
    navBarHeight: 0,
    
    // 标签页
    activeTab: 'pending', // pending, processed
    tabs: [
      { key: 'pending', label: '待处理', count: 0 },
      { key: 'processed', label: '已处理', count: 0 }
    ]
  },

  onLoad(options) {
    console.log('好友请求页面加载');
    this.initSystemInfo();
    this.loadFriendRequests();
  },

  onShow() {
    // 刷新数据
    this.loadFriendRequests();
  },

  // 初始化系统信息
  initSystemInfo() {
    const systemInfo = wx.getSystemInfoSync();
    const menuButton = wx.getMenuButtonBoundingClientRect();
    
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight,
      navBarHeight: menuButton.bottom + 10
    });
  },

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

  // 加载好友请求
  async loadFriendRequests() {
    try {
      this.setData({ loading: true });

      const response = await friendAPI.getFriendRequests();
      
      // 从API响应中提取数据数组
      const requests = response.data || [];
      
      // 分类请求
      const pendingRequests = requests.filter(req => req.status === 0);
      const processedRequests = requests.filter(req => req.status !== 0);
      
      // 更新标签页计数
      const updatedTabs = this.data.tabs.map(tab => ({
        ...tab,
        count: tab.key === 'pending' ? pendingRequests.length : processedRequests.length
      }));

      this.setData({
        friendRequests: requests,
        pendingRequests: pendingRequests,
        processedRequests: processedRequests,
        pendingCount: pendingRequests.length,
        processedCount: processedRequests.length,
        tabs: updatedTabs,
        loading: false,
        refreshing: false
      });

    } catch (error) {
      console.error('加载好友请求失败:', error);
      this.setData({
        loading: false,
        refreshing: false
      });
      
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  // 下拉刷新
  onRefresh() {
    this.setData({ refreshing: true });
    this.loadFriendRequests();
    // 刷新后也通知好友页面更新数量
    setTimeout(() => {
      this.notifyFriendsPageRefresh();
    }, 500); // 延迟一点确保数据加载完成
  },

  // 切换标签页
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab
    });
    
    console.log('切换到标签页:', tab);
    console.log('待处理请求数量:', this.data.pendingRequests?.length || 0);
    console.log('已处理请求数量:', this.data.processedRequests?.length || 0);
  },

  // 获取当前标签页的请求列表
  getCurrentRequests() {
    const { friendRequests, activeTab } = this.data;
    
    if (activeTab === 'pending') {
      return friendRequests.filter(req => req.status === 0);
    } else {
      return friendRequests.filter(req => req.status !== 0);
    }
  },

  // 处理好友请求
  async handleRequest(e) {
    const { requestId, accept } = e.currentTarget.dataset;
    const actionText = accept === 'true' ? '接受' : '拒绝';
    
    try {
      wx.showLoading({ title: `${actionText}中...` });

      await friendAPI.handleFriendRequest(requestId, accept === 'true');

      wx.hideLoading();
      wx.showToast({
        title: `已${actionText}`,
        icon: 'success'
      });

      // 刷新列表
      this.loadFriendRequests();
      
      // 通知好友页面刷新请求数量
      this.notifyFriendsPageRefresh();

    } catch (error) {
      wx.hideLoading();
      console.error('处理好友请求失败:', error);
      wx.showToast({
        title: error.message || `${actionText}失败`,
        icon: 'none'
      });
    }
  },

  // 查看用户详情
  viewUserDetail(e) {
    const { customId } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/social/user-detail/user-detail?customId=${customId}`
    });
  },

  // 通知好友页面刷新
  notifyFriendsPageRefresh() {
    try {
      // 通过全局事件通知好友页面刷新
      const app = getApp();
      if (app.globalData) {
        app.globalData.needRefreshFriendRequests = true;
      }
      
      // 也可以通过页面栈找到好友页面并直接调用刷新方法
      const pages = getCurrentPages();
      const friendsPage = pages.find(page => page.route === 'pages/social/friends/friends');
      if (friendsPage && friendsPage.loadFriendRequestsCount) {
        friendsPage.loadFriendRequestsCount();
      }
      
      console.log('✅ 已通知好友页面刷新请求数量');
    } catch (error) {
      console.error('❌ 通知好友页面失败:', error);
    }
  },

  // 发送消息
  sendMessage(e) {
    const { customId, nickname } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/message/chat/chat?targetId=${customId}&name=${encodeURIComponent(nickname)}&chatType=0`
    });
  },

  // 格式化时间
  formatTime(timeStr) {
    const time = new Date(timeStr);
    const now = new Date();
    const diff = now - time;
    
    const minute = 60 * 1000;
    const hour = 60 * minute;
    const day = 24 * hour;
    const week = 7 * day;
    
    if (diff < minute) {
      return '刚刚';
    } else if (diff < hour) {
      return `${Math.floor(diff / minute)}分钟前`;
    } else if (diff < day) {
      return `${Math.floor(diff / hour)}小时前`;
    } else if (diff < week) {
      return `${Math.floor(diff / day)}天前`;
    } else {
      return time.toLocaleDateString();
    }
  },

  // 获取状态文本
  getStatusText(status) {
    switch (status) {
      case 0: return '待处理';
      case 1: return '已接受';
      case 2: return '已拒绝';
      default: return '未知';
    }
  },

  // 获取状态样式类
  getStatusClass(status) {
    switch (status) {
      case 0: return 'pending';
      case 1: return 'accepted';
      case 2: return 'rejected';
      default: return 'unknown';
    }
  }
});
