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

// 分页请求参数类型
interface PaginationParams {
  page: number;
  pageSize: number;
  [key: string]: any; // 其他查询参数
}

// 分页响应数据类型
interface PaginationResponse<T> {
  list: T[];
  total: number;
  page: number;
  pageSize: number;
}

// 分页配置选项
interface PaginationOptions<T> {
  immediate?: boolean; // 是否立即执行
  defaultParams?: Partial<PaginationParams>; // 默认参数
  requestFn: (params: PaginationParams) => Promise<PaginationResponse<T>>; // 请求函数
}

// 分页状态
interface PaginationState<T> {
  data: T[];
  loading: boolean;
  total: number;
  currentPage: number;
  pageSize: number;
  params: Record<string, any>;
}

// hooks返回类型
interface UsePaginationReturn<T> {
  paginationState: PaginationState<T>;
  fetchData: () => Promise<void>;
  handlePageChange: (page: number) => void;
  handlePageSizeChange: (pageSize: number) => void;
  handleSearch: (searchParams?: Record<string, any>) => void;
  reset: () => void;
}

/**
 * 通用分页请求hooks
 * @param options 分页配置选项
 * @returns 分页相关状态和方法
 */
export function usePagination<T>(options: PaginationOptions<T>): UsePaginationReturn<T> {
  const { immediate = true, defaultParams = {}, requestFn } = options;

  // 分页状态
  const data = ref<T[]>([]);
  const paginationState = reactive({
    data,
    loading: false,
    total: 0,
    currentPage: defaultParams.page || 1,
    pageSize: defaultParams.pageSize || 10,
    params: {
      ...defaultParams
    }
  }) as PaginationState<T>;

  /**
   * 获取数据
   */
  const fetchData = async (): Promise<void> => {
    try {
      paginationState.loading = true;
      const params: PaginationParams = {
        page: paginationState.currentPage,
        pageSize: paginationState.pageSize,
        ...paginationState.params
      };

      const response = await requestFn(params);

      paginationState.data = response.list;
      paginationState.total = response.total;

      // 更新当前页和页大小（以防接口返回不同的值）
      paginationState.currentPage = response.page;
      paginationState.pageSize = response.pageSize;
    } catch (error) {
      console.error('分页数据获取失败:', error);
      paginationState.data = [];
      paginationState.total = 0;
    } finally {
      paginationState.loading = false;
    }
  };

  /**
   * 处理页码变化
   * @param page 新的页码
   */
  const handlePageChange = (page: number): void => {
    paginationState.currentPage = page;
    fetchData();
  };

  /**
   * 处理每页数量变化
   * @param pageSize 每页数量
   */
  const handlePageSizeChange = (pageSize: number): void => {
    paginationState.pageSize = pageSize;
    paginationState.currentPage = 1; // 重置到第一页
    fetchData();
  };

  /**
   * 处理搜索
   * @param searchParams 搜索参数
   */
  const handleSearch = (searchParams?: Record<string, any>): void => {
    if (searchParams) {
      paginationState.params = {
        ...paginationState.params,
        ...searchParams
      };
    }
    paginationState.currentPage = 1; // 搜索时重置到第一页
    fetchData();
  };

  /**
   * 重置分页状态
   */
  const reset = (): void => {
    paginationState.currentPage = defaultParams.page || 1;
    paginationState.pageSize = defaultParams.pageSize || 10;
    paginationState.params = { ...defaultParams };
    paginationState.data = [];
    paginationState.total = 0;
    fetchData();
  };

  // 是否立即执行
  if (immediate) {
    onMounted(() => {
      fetchData();
    });
  }

  return {
    paginationState,
    fetchData,
    handlePageChange,
    handlePageSizeChange,
    handleSearch,
    reset
  };
}
