import loadingManager from '../utils/loadingManager';

export default {
  data() {
    return {
      componentId: this.$options.name || 'unnamed-component'
    };
  },
  
  methods: {
    // 设置 loading 状态
    setLoading(stateKey, value) {
      // 同时更新组件本地状态和全局状态
      this[stateKey] = value;
      loadingManager.setLoading(this.componentId, stateKey, value);
    },
    
    // 获取 loading 状态
    getLoading(stateKey) {
      return loadingManager.getLoading(this.componentId, stateKey);
    }
  },
  
  mounted() {
    // 监听重置 loading 状态事件
    this._resetHandler = (event) => {
      const { componentsToUpdate } = event.detail;
      componentsToUpdate.forEach(item => {
        if (item.componentId === this.componentId) {
          this[item.stateKey] = false;
        }
      });
    };
    
    window.addEventListener('reset-loading-states', this._resetHandler);
  },
  
  beforeDestroy() {
    // 清理监听器
    window.removeEventListener('reset-loading-states', this._resetHandler);
    
    // 组件销毁时清理该组件的所有loading状态
    const componentsToUpdate = loadingManager.resetComponentLoadingStates(this.componentId);
    componentsToUpdate.forEach(item => {
      this[item.stateKey] = false;
    });
  }
};