import { useResetData } from '@/hooks'
import type { BackendServicePageResult, BackendServiceResult } from '@/utils/request/types'

/**
 * 分页搜索参数基础类型
 */
export type PageSearchParamValue = string | number | string[] | number[] | undefined | null

/**
 * 分页搜索参数
 */
export interface PageSearchParams {
  current?: number
  size?: number
  [key: string]: PageSearchParamValue
}

/**
 * 分页搜索配置
 */
export interface PageSearchConfig<T extends PageSearchParams = PageSearchParams> {
  /** 是否立即执行搜索 */
  immediate?: boolean
  /** 默认页码 */
  defaultCurrent?: number
  /** 默认页大小 */
  defaultSize?: number
  /** 初始搜索参数 */
  defaultParams?: Omit<T, 'current' | 'size'>
  /** 页码字段名（用于适配不同后端接口） */
  pageField?: keyof T
  /** 页大小字段名 */
  pageSizeField?: keyof T
  /** 格式化列表数据 */
  formatList?: (list: any[]) => any[]
  /** 成功回调 */
  success?: (list: Ref<any[]>) => void
  /** 失败回调 */
  error?: (error: unknown) => void
}

/**
 * 分页搜索 Hook - 自动类型推断版本
 */
export function usePageSearch<
  TSearchApi extends (params: any) => Promise<BackendServiceResult<BackendServicePageResult<any>>>,
>(searchApi: TSearchApi, config: PageSearchConfig = {}) {
  // 从 searchApi 推断参数类型和返回数据类型
  type TParams = Parameters<TSearchApi>[0]
  type TData = TSearchApi extends (
    params: any,
  ) => Promise<BackendServiceResult<BackendServicePageResult<infer U>>>
    ? U
    : never

  const {
    immediate = true,
    defaultCurrent = 1,
    defaultSize = 10,
    defaultParams = {} as Omit<TParams, 'current' | 'size'>,
    pageField = 'current' as keyof TParams,
    pageSizeField = 'size' as keyof TParams,
    formatList = (list: any[]) => list,
    success = () => {},
    error: onError = () => {},
  } = config

  const loading = shallowRef(false)
  const list = ref<TData[]>([])
  const total = ref(0)

  // 构建初始搜索参数
  const initialParams = {
    [pageField]: defaultCurrent,
    [pageSizeField]: defaultSize,
    ...defaultParams,
  } as TParams
  const [searchParams, resetSearchParams] = useResetData(initialParams)

  const search = async (params?: Partial<TParams>) => {
    loading.value = true
    try {
      const searchData = params ? { ...searchParams.value, ...params } : searchParams.value
      const { data } = await searchApi(searchData as TParams)

      list.value = formatList(data.list || [])
      total.value = data.total || 0
      success?.(list)
    } catch (error) {
      list.value = []
      total.value = 0
      console.log(error,'分页查询失败')
      onError(error)
    } finally {
      loading.value = false
    }
  }

  const reset = async () => {
    resetSearchParams()
    await search()
  }

  const goToPage = async (page: number) => {
    searchParams.value[pageField] = page
    await search()
  }

  const changePageSize = async (size: number) => {
    searchParams.value[pageField] = 1
    searchParams.value[pageSizeField] = size
    await search()
  }

  const refresh = async () => {
    searchParams.value[pageField] = 1
    await search()
  }

  // 清空搜索数据和列表
  const clear = () => {
    list.value = []
    total.value = 0
    resetSearchParams()
  }

  if (immediate) {
    onMounted(search)
  }

  return {
    list,
    total: readonly(total),
    loading,
    searchParams,
    search,
    reset,
    goToPage,
    changePageSize,
    refresh,
    clear,
  }
}
