import { globalTimChatManager } from './tim-chat.js';

/**
 * 全局未读消息监听管理器
 * 负责监听会话列表更新和消息接收事件，实时更新 tabBar 徽章
 */
class GlobalUnreadListenerManager {
  constructor() {
    this.isInitialized = false;
    this.callbackChain = {
      onConversationListUpdated: [],
      onMessageReceived: []
    };
    this.updateTimer = null; // 防抖定时器
  }

  /**
   * 初始化全局未读消息监听
   * 监听会话列表更新、消息接收和消息已读事件
   */
  setup() {
    if (this.isInitialized) {
      console.warn('全局未读消息监听已初始化，跳过重复初始化');
      return;
    }
    if (!globalTimChatManager) {
      console.warn('globalTimChatManager 未初始化');
      return;
    }

    // 保存原始回调到回调链
    const originalConversationListCallback = globalTimChatManager.callbacks.onConversationListUpdated;
    const originalMessageReceivedCallback = globalTimChatManager.callbacks.onMessageReceived;

    if (originalConversationListCallback && typeof originalConversationListCallback === 'function') {
      this.callbackChain.onConversationListUpdated.push(originalConversationListCallback);
    }
    if (originalMessageReceivedCallback && typeof originalMessageReceivedCallback === 'function') {
      this.callbackChain.onMessageReceived.push(originalMessageReceivedCallback);
    }

    console.log('全局未读监听初始化，回调链长度:', {
      onConversationListUpdated: this.callbackChain.onConversationListUpdated.length,
      onMessageReceived: this.callbackChain.onMessageReceived.length
    });

    // 监听会话列表更新事件（包括消息接收和已读状态变化）
    globalTimChatManager.setCallback('onConversationListUpdated', (eventData) => {
      console.log('【全局未读监听】onConversationListUpdated 触发，回调链长度:', this.callbackChain.onConversationListUpdated.length);
      
      // 执行回调链中的所有回调
      this.callbackChain.onConversationListUpdated.forEach((callback, index) => {
        try {
          console.log(`【全局未读监听】执行回调链 #${index + 1}`);
          callback(eventData);
        } catch (error) {
          console.error(`【全局未读监听】执行 onConversationListUpdated 回调 #${index + 1} 失败:`, error);
        }
      });
      
      // 防抖更新 tabBar 徽章
      this.debouncedUpdateTabBarBadge();
    });

    // 监听消息接收事件
    globalTimChatManager.setCallback('onMessageReceived', (message) => {
      console.log('【全局未读监听】onMessageReceived 触发，回调链长度:', this.callbackChain.onMessageReceived.length);
      
      // 执行回调链中的所有回调
      this.callbackChain.onMessageReceived.forEach((callback, index) => {
        try {
          console.log(`【全局未读监听】执行回调链 #${index + 1}`);
          callback(message);
        } catch (error) {
          console.error(`【全局未读监听】执行 onMessageReceived 回调 #${index + 1} 失败:`, error);
        }
      });
      
      // 防抖更新 tabBar 徽章
      this.debouncedUpdateTabBarBadge();
    });

    this.isInitialized = true;
    console.log('全局未读消息监听已设置');
    
    // 初始化时立即更新一次徽章
    this.updateTabBarBadge();
  }

  /**
   * 防抖更新 tabBar 徽章
   * 避免频繁更新导致性能问题
   */
  debouncedUpdateTabBarBadge() {
    if (this.updateTimer) {
      clearTimeout(this.updateTimer);
    }
    this.updateTimer = setTimeout(() => {
      this.updateTabBarBadge();
    }, 200); // 减少到 200ms 防抖延迟，提高响应速度
  }

  /**
   * 更新 tabBar 徽章
   * 获取所有群聊会话的未读数，并更新对应的 tabBar 徽章
   */
  async updateTabBarBadge() {
    try {
      if (!globalTimChatManager || !globalTimChatManager.tim) {
        console.warn('【全局未读监听】globalTimChatManager 或 tim 未初始化');
        return;
      }

      const response = await globalTimChatManager.tim.getConversationList();

      if (!response || !response.data || !response.data.conversationList) {
        console.warn('【全局未读监听】获取会话列表返回数据异常');
        return;
      }

      const totalUnreadCount = this.calculateGroupUnreadCount(response.data.conversationList);
      console.log('【全局未读监听】计算总未读数:', totalUnreadCount);
      this.setTabBarBadge(totalUnreadCount);
    } catch (error) {
      console.error('【全局未读监听】更新 tabBar 徽章失败:', error);
    }
  }

  /**
   * 计算群聊会话的总未读数
   * @param {Array} conversationList - 会话列表
   * @returns {number} 总未读数
   */
  calculateGroupUnreadCount(conversationList) {
    return conversationList
      .filter((conv) => conv.conversationID && conv.conversationID.startsWith('GROUP'))
      .reduce((sum, conv) => sum + (conv.unreadCount || 0), 0);
  }

  /**
   * 设置 tabBar 徽章
   * @param {number} count - 未读数
   * @param {number} tabIndex - tabBar 索引，默认为 1（消息页）
   */
  setTabBarBadge(count, tabIndex = 1) {
    if (count > 0) {
      uni.setTabBarBadge({
        index: tabIndex,
        text: count > 99 ? '99+' : String(count)
      });
      console.log(`✓ 已更新 tabBar 徽章（索引 ${tabIndex}）:`, count);
    } else {
      uni.removeTabBarBadge({
        index: tabIndex
      });
      console.log(`✓ 已移除 tabBar 徽章（索引 ${tabIndex}）`);
    }
  }

  /**
   * 手动刷新徽章
   * 用于页面显示时强制刷新
   */
  async refreshBadge() {
    console.log('手动刷新 tabBar 徽章');
    await this.updateTabBarBadge();
  }

  /**
   * 添加回调到回调链
   * @param {string} eventName - 事件名称
   * @param {Function} callback - 回调函数
   */
  addCallback(eventName, callback) {
    if (this.callbackChain[eventName] && typeof callback === 'function') {
      // 避免重复添加同一个回调
      if (!this.callbackChain[eventName].includes(callback)) {
        this.callbackChain[eventName].push(callback);
        console.log(`✓ 已添加回调到 ${eventName} 回调链，当前链长度:`, this.callbackChain[eventName].length);
      } else {
        console.log(`⚠️ 回调已存在于 ${eventName} 回调链中，跳过添加`);
      }
    }
  }

  /**
   * 从回调链中移除回调
   * @param {string} eventName - 事件名称
   * @param {Function} callback - 回调函数
   */
  removeCallback(eventName, callback) {
    if (this.callbackChain[eventName]) {
      const index = this.callbackChain[eventName].indexOf(callback);
      if (index > -1) {
        this.callbackChain[eventName].splice(index, 1);
        console.log(`✓ 已从 ${eventName} 回调链移除回调，当前链长度:`, this.callbackChain[eventName].length);
      }
    }
  }

  /**
   * 清除监听（可选）
   */
  destroy() {
    if (this.updateTimer) {
      clearTimeout(this.updateTimer);
      this.updateTimer = null;
    }
    this.callbackChain = {
      onConversationListUpdated: [],
      onMessageReceived: []
    };
    this.isInitialized = false;
    console.log('全局未读消息监听已清除');
  }
}

// 导出单例
export const globalUnreadListenerManager = new GlobalUnreadListenerManager();
