import { ref } from 'vue';

/**
 * Loading控制Hook
 * @returns loading（加载状态）、startLoading（开始加载）、stopLoading（停止加载）、withLoading（包装异步函数）
 */
export function useLoading(initialLoading = false) {
  const loading = ref(initialLoading);

  const startLoading = () => {
    loading.value = true;
  };

  const stopLoading = () => {
    loading.value = false;
  };

  /**
   * 包装异步函数，自动控制loading状态
   * @param fn 异步函数
   * @returns 包装后的函数
   */
  const withLoading = <T extends (...args: any[]) => Promise<any>>(fn: T): T => {
    return (async (...args: any[]) => {
      startLoading();
      try {
        const result = await fn(...args);
        return result;
      } finally {
        stopLoading();
      }
    }) as T;
  };

  return {
    loading,
    startLoading,
    stopLoading,
    withLoading
  };
}