import { ref, onMounted, onActivated } from 'vue';

/**
 * 列表页 mount / KeepAlive activated 生命周期：有缓存则后台静默刷新，无缓存则显示 loading。
 */
export function useStaleListLifecycle(
  hasData: () => boolean,
  loadFn: () => void | Promise<void>,
) {
  const loading = ref(false);

  async function runLoad(showSpinner: boolean) {
    if (showSpinner) loading.value = true;
    try {
      await loadFn();
    } finally {
      loading.value = false;
    }
  }

  onMounted(() => void runLoad(!hasData()));
  onActivated(() => {
    if (hasData()) void runLoad(false);
  });

  return { loading, runLoad };
}
