import { ref, type Ref } from "vue";
import { message } from "ant-design-vue";

export interface UseSimpleListRequestOptions<T> {
  // 请求函数（返回数组，不是分页响应）
  requestFn: () => Promise<T[]>;
  // 错误提示信息
  errorMessage?: string;
  // 是否在挂载时自动加载
  immediate?: boolean;
}

export function useSimpleListRequest<T>(
  options: UseSimpleListRequestOptions<T>
) {
  const {
    requestFn,
    errorMessage = "获取列表失败",
    immediate = true,
  } = options;

  // 加载状态
  const loading = ref(false);

  // 数据源
  const dataSource = ref<T[]>([]) as Ref<T[]>;

  // 获取列表数据
  const fetchList = async () => {
    loading.value = true;
    try {
      const response = await requestFn();
      dataSource.value = response;
    } catch (error) {
      message.error(errorMessage);
      console.error("List request error:", error);
    } finally {
      loading.value = false;
    }
  };

  // 刷新列表
  const refresh = () => {
    fetchList();
  };

  // 如果 immediate 为 true，在组合函数被调用时自动加载
  if (immediate) {
    fetchList();
  }

  return {
    // 状态
    loading,
    dataSource,

    // 方法
    fetchList,
    refresh,
  };
}

