// 好友请求管理页面
const app = getApp();
const friendAPI = require('../../../utils/friend-api.js');
const notificationManager = require('../../../utils/notification-manager.js');
const wsManager = require('../../../utils/websocket-manager-v2.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) {

    this.initSystemInfo();
    this.loadFriendRequests();
    
    // 🔥 初始化WebSocket监听
    this.initWebSocketListener();
  },

  onShow() {
    // 刷新数据
    this.loadFriendRequests();
    // 选中好友tab
    try {
      if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({ selected: 1 });
      }
    } catch (_) {}
  },

  // 初始化系统信息
  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 || [];

      // 分类请求
      let pendingRequests = requests.filter(req => req.status === 0);
      // pendingRequests = Array(20).fill(pendingRequests).flat();
      // console.log('pendingRequests-------',pendingRequests);


      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
      });

      // 同步自定义TabBar好友角标
      try {
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
          this.getTabBar().setFriendsBadge(pendingRequests.length || 0);
        }
      } catch (_) {}

      // 同步通知管理器未读计数
      try { notificationManager.setFriendsUnreadCount(pendingRequests.length || 0); } catch (_) {}

    } 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
    });  },

  // 获取当前标签页的请求列表
  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();

      // 同步自定义TabBar的好友红点：处理后尝试刷新数量
      try {
        const resp = await friendAPI.getFriendRequestCount();
        const count = (resp && (resp.code === 0 || resp.code === 200)) ? (resp.data?.count || 0) : 0;
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
          this.getTabBar().setFriendsBadge(count);
        }
        try { notificationManager.setFriendsUnreadCount(count); } catch (_) {}
      } catch (_) {}

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

  // 通知好友页面刷新
  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) {
        // 刷新好友请求数量
        if (friendsPage.loadFriendRequestsCount) {
          friendsPage.loadFriendRequestsCount();
        }
        // 刷新好友列表（因为可能新增了好友）
        if (friendsPage.loadFriends) {
          friendsPage.loadFriends();
        }
      }

    } catch (error) {
      console.error('❌ 通知好友页面失败:', error);
    }
  },

  // 🔥 初始化WebSocket监听器
  initWebSocketListener() {
    try {
      if (this._wsInited) return;
      this._wsInited = true;

      console.log('🔌 [好友请求页] 初始化WebSocket监听器');

      // 绑定处理函数到 this
      this.handleNotificationMessage = this.handleNotificationMessage.bind(this);

      // 监听通知消息
      wsManager.on('notification', this.handleNotificationMessage);

    } catch (error) {
      console.error('❌ [好友请求页] 初始化WebSocket监听器失败:', error);
    }
  },

  // 处理通知消息
  handleNotificationMessage(msg) {
    try {
      console.log('🔔 [好友请求页] 收到通知消息:', msg);
      const data = msg?.data || msg;
      
      // 判断是否为好友通知
      if (data?.type === 'friend_notification') {
        this.handleFriendNotification(data);
      } else if (data?.type === 'friend_request_notification') {
        this.handleFriendRequestNotification(data);
      }
    } catch (error) {
      console.error('❌ [好友请求页] 处理通知消息失败:', error);
    }
  },

  // 处理好友通知
  handleFriendNotification(data) {
    try {
      console.log('🆕 [好友请求页] 处理好友通知:', data);
      
      const subType = data?.subType;
      
      // 对于任何好友通知，都刷新列表
      if (subType === 'request' || subType === 'accepted' || subType === 'rejected' || subType === 'count_update') {
        // 延迟一点刷新，确保后端数据已更新
        setTimeout(() => {
          this.loadFriendRequests();
        }, 300);
      }

    } catch (error) {
      console.error('❌ [好友请求页] 处理好友通知失败:', error);
    }
  },

  // 处理连接时的待处理好友请求通知
  handleFriendRequestNotification(data) {
    try {
      console.log('📋 [好友请求页] 处理待处理好友请求通知:', data);
      const pendingCount = data?.pendingCount || 0;
      
      // 如果有待处理请求，刷新列表
      if (pendingCount > 0) {
        setTimeout(() => {
          this.loadFriendRequests();
        }, 300);
      }
    } catch (error) {
      console.error('❌ [好友请求页] 处理待处理好友请求通知失败:', error);
    }
  },



  // 格式化时间
  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';
    }
  },

  // 页面卸载
  onUnload() {
    // 移除 WebSocket 监听器
    try {
      if (this.handleNotificationMessage) {
        wsManager.off('notification', this.handleNotificationMessage);
        console.log('✅ [好友请求页] 已移除 WebSocket 监听器');
      }
    } catch (error) {
      console.error('❌ [好友请求页] 移除 WebSocket 监听器失败:', error);
    }
  }
});

