/**
 * @Author: Antigravity
 * 统一定时刷新 Hook
 * 用于页面数据的静默轮询更新
 */
import { onMounted, onUnmounted } from 'vue';

/**
 * @param callback 刷新回调函数
 * @param interval 轮询时间间隔(ms)，默认为 5000ms
 * @param immediate 是否在挂载时立即执行一次回调，默认为 false (因为通常 onMounted 已经调用过一次了)
 */
export function useIntervalRefresh(callback: () => void, interval = 5000, immediate = false) {
  let timer: any = null;

  const start = () => {
    stop();
    if (immediate) {
      callback();
    }
    timer = setInterval(() => {
      callback();
    }, interval);
    console.log(`[IntervalRefresh] 已启动，频率: ${interval}ms`);
  };

  const stop = () => {
    if (timer) {
      clearInterval(timer);
      timer = null;
      console.log('[IntervalRefresh] 已停止');
    }
  };

  onMounted(() => {
    start();
  });

  onUnmounted(() => {
    stop();
  });

  return {
    start,
    stop
  };
}
