import type { TablePaginationConfig } from 'antd'

/** 后台标准列表默认每页条数（与后端 normalizePageSize 默认 20 一致） */
export const ADMIN_DEFAULT_PAGE_SIZE = 20

/**
 * 标准列表可选页大小。
 * 后端 admin normalizePageSize 上限 100，故不包含更大档位。
 */
export const ADMIN_PAGE_SIZE_OPTIONS = [10, 20, 50, 100] as const

/** kuaishou-lewan 发货记录：上游接口更适合大批量拉取 */
export const CLOUDTENTACLES_DEFAULT_PAGE_SIZE = 100
export const CLOUDTENTACLES_PAGE_SIZE_OPTIONS = [100, 200, 500, 1000] as const

export function formatAdminTotal(total: number) {
  return `共 ${total} 条`
}

/** 可复用到 Table.pagination 的标准选项（常开条数切换） */
export const ADMIN_TABLE_PAGINATION_BASE: Pick<
  TablePaginationConfig,
  'showSizeChanger' | 'pageSizeOptions' | 'showTotal'
> = {
  showSizeChanger: true,
  pageSizeOptions: [...ADMIN_PAGE_SIZE_OPTIONS],
  showTotal: formatAdminTotal,
}

/**
 * 服务端分页列表（任务/订单/用户/审计等）。
 * 始终展示 10/20/50/100，避免 antd「total ≤ 50 不显示」默认行为。
 */
export function buildAdminTablePagination(
  options: {
    current?: number
    page?: number
    pageSize?: number
    total?: number
    onChange?: TablePaginationConfig['onChange']
  } & Partial<TablePaginationConfig>,
): TablePaginationConfig {
  const { current, page, pageSize, total, onChange, ...rest } = options
  return {
    ...ADMIN_TABLE_PAGINATION_BASE,
    current: current ?? page ?? 1,
    pageSize: pageSize ?? ADMIN_DEFAULT_PAGE_SIZE,
    total: total ?? 0,
    onChange,
    ...rest,
  }
}

/** 纯前端本地表格分页 */
export function buildAdminLocalTablePagination(
  options: Partial<TablePaginationConfig> = {},
): TablePaginationConfig {
  return {
    ...ADMIN_TABLE_PAGINATION_BASE,
    pageSize: ADMIN_DEFAULT_PAGE_SIZE,
    ...options,
  }
}

/** kuaishou-lewan 发货记录分页（100–1000） */
export function buildCloudtentaclesTablePagination(
  options: {
    current?: number
    page?: number
    pageSize?: number
    total?: number
    onChange?: TablePaginationConfig['onChange']
  } & Partial<TablePaginationConfig>,
): TablePaginationConfig {
  const { current, page, pageSize, total, onChange, ...rest } = options
  return {
    showSizeChanger: true,
    pageSizeOptions: [...CLOUDTENTACLES_PAGE_SIZE_OPTIONS],
    showTotal: formatAdminTotal,
    current: current ?? page ?? 1,
    pageSize: pageSize ?? CLOUDTENTACLES_DEFAULT_PAGE_SIZE,
    total: total ?? 0,
    onChange,
    ...rest,
  }
}

export function resolveAdminPageSize(
  raw: unknown,
  fallback: number = ADMIN_DEFAULT_PAGE_SIZE,
): number {
  const parsed = Number(raw)
  if (!Number.isFinite(parsed) || parsed <= 0) {
    return fallback
  }
  return Math.min(100, Math.floor(parsed))
}
