/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2025-06-06 14:28:09
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-06-06 14:34:33
 * @FilePath: /bi2025/src/hooks/useRefresh.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { useEffect } from 'react';
import { MODULE_CONFIG, GLOBAL_REFRESH_EVENT } from '../App';

/**
 * 刷新Hook，用于组件监听刷新事件
 * @param moduleKey 模块在MODULE_CONFIG中的键名
 * @param callback 刷新回调函数
 */
const useRefresh = (
  moduleKey: keyof typeof MODULE_CONFIG, 
  callback: () => void
) => {
  useEffect(() => {
    const module = MODULE_CONFIG[moduleKey];
    
    // 监听模块特定事件
    const moduleEventName = `refresh-module-${module.id}`;
    const handleModuleRefresh = () => {
      console.log(`${moduleKey} 模块收到特定刷新信号`);
      callback();
    };
    
    // 监听全局事件（兼容模式）
    const handleGlobalRefresh = (event: Event) => {
      const customEvent = event as CustomEvent;
      const detail = customEvent.detail || {};
      
      // 如果全局事件包含模块信息，只在匹配时执行
      if (detail.moduleId && detail.moduleId !== module.id) {
        return;
      }
      
      console.log(`${moduleKey} 模块收到全局刷新信号`);
      callback();
    };
    
    // 添加事件监听
    window.addEventListener(moduleEventName, handleModuleRefresh);
    window.addEventListener(GLOBAL_REFRESH_EVENT, handleGlobalRefresh);
    
    // 组件卸载时移除事件监听
    return () => {
      window.removeEventListener(moduleEventName, handleModuleRefresh);
      window.removeEventListener(GLOBAL_REFRESH_EVENT, handleGlobalRefresh);
    };
  }, [moduleKey, callback]);
};

export default useRefresh; 