// 全局 loading 状态管理器
class LoadingManager {
    constructor() {
      this.loadingStates = new Map(); // 存储所有 loading 状态
      this.setupListeners();
    }
  
    setupListeners() {
      // 监听网络重试完成事件
      window.addEventListener('network-retry-complete', () => {
        this.resetAllLoadingStates();
      });
    }
  
    // 设置 loading 状态
    setLoading(componentId, stateKey, value) {
      const key = `${componentId}:${stateKey}`;
      this.loadingStates.set(key, {
        value,
        timestamp: Date.now()
      });
    }
  
    // 获取 loading 状态
    getLoading(componentId, stateKey) {
      const key = `${componentId}:${stateKey}`;
      const state = this.loadingStates.get(key);
      return state ? state.value : false;
    }
    
    // 重置所有 loading 状态
    resetAllLoadingStates() {
      // 清除所有处于加载状态的组件
      const componentsToUpdate = [];
      
      this.loadingStates.forEach((state, key) => {
        if (state.value === true) {
          const [componentId, stateKey] = key.split(':');
          componentsToUpdate.push({ componentId, stateKey });
          this.loadingStates.set(key, { value: false, timestamp: Date.now() });
        }
      });
      
      // 使用事件通知各组件更新
      window.dispatchEvent(new CustomEvent('reset-loading-states', {
        detail: { componentsToUpdate }
      }));
    }
  
    // 重置特定组件的所有 loading 状态
    resetComponentLoadingStates(componentId) {
      const componentsToUpdate = [];
      
      this.loadingStates.forEach((state, key) => {
        if (key.startsWith(`${componentId}:`) && state.value === true) {
          const stateKey = key.split(':')[1];
          componentsToUpdate.push({ componentId, stateKey });
          this.loadingStates.set(key, { value: false, timestamp: Date.now() });
        }
      });
      
      return componentsToUpdate;
    }
  }
  
  // 创建单例实例
  const loadingManager = new LoadingManager();
  export default loadingManager;