import { ref, reactive, type Ref } from "vue";
import { message } from "ant-design-vue";
import type { TableProps } from "ant-design-vue";
import type { PaginationParams, PaginationResponse } from "@/types/api";

export interface UseListRequestOptions<
  T,
  P extends Record<string, any> = Record<string, any>,
> {
  // 请求函数
  requestFn: (params: PaginationParams & P) => Promise<PaginationResponse<T>>;
  // 默认搜索参数
  defaultSearchParams?: P;
  // 默认分页大小
  defaultPageSize?: number;
  // 错误提示信息
  errorMessage?: string;
  // 是否在挂载时自动加载
  immediate?: boolean;
}

export function useListRequest<
  T,
  P extends Record<string, any> = Record<string, any>,
>(options: UseListRequestOptions<T, P>) {
  const {
    requestFn,
    defaultSearchParams = {} as P,
    defaultPageSize = 10,
    errorMessage = "获取列表失败",
    immediate = true,
  } = options;

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

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

  // 分页信息
  const pagination = reactive({
    current: 1,
    pageSize: defaultPageSize,
    total: 0,
  });

  // 搜索参数
  const searchParams = reactive<P>({ ...defaultSearchParams } as P);

  // 获取列表数据
  const fetchList = async () => {
    loading.value = true;
    try {
      const params = {
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      } as PaginationParams & P;

      const response = await requestFn(params);
      dataSource.value = response.list;
      pagination.total = response.total;
    } catch (error) {
      message.error(errorMessage);
      console.error("List request error:", error);
    } finally {
      loading.value = false;
    }
  };

  // 重置搜索并刷新
  const resetSearch = () => {
    Object.assign(searchParams, defaultSearchParams);
    pagination.current = 1;
    fetchList();
  };

  // 搜索
  const search = (params?: Partial<P>) => {
    if (params) {
      Object.assign(searchParams, params);
    }
    pagination.current = 1;
    fetchList();
  };

  // 刷新当前页
  const refresh = () => {
    fetchList();
  };

  // 表格分页变化处理
  const handleTableChange: TableProps["onChange"] = (pag) => {
    pagination.current = pag.current || 1;
    pagination.pageSize = pag.pageSize || defaultPageSize;
    fetchList();
  };

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

  return {
    // 状态
    loading,
    dataSource,
    pagination,
    searchParams,

    // 方法
    fetchList,
    resetSearch,
    search,
    refresh,
    handleTableChange,
  };
}
