export type SortDirection = "asc" | "desc";

export function sortRows(
  rows: Record<string, unknown>[],
  key: string,
  direction: SortDirection,
): Record<string, unknown>[] {
  const multiplier = direction === "asc" ? 1 : -1;
  return [...rows].sort((left, right) => compare(left[key], right[key]) * multiplier);
}

export function formatNumber(value: unknown, digits = 2): string {
  if (value === null || value === undefined || value === "") return "";
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed.toFixed(digits) : "";
}

export function formatAmount(value: unknown): string {
  if (value === null || value === undefined || value === "") return "";
  const parsed = Number(value);
  if (!Number.isFinite(parsed)) return "";
  return parsed >= 100_000_000
    ? `${(parsed / 100_000_000).toFixed(2)} 亿`
    : `${(parsed / 10_000).toFixed(2)} 万`;
}

export function exportCsv(filename: string, rows: string[][]): void {
  const content = rows
    .map((row) => row.map((value) => `"${value.replaceAll('"', '""')}"`).join(","))
    .join("\r\n");
  const link = document.createElement("a");
  link.href = URL.createObjectURL(new Blob(["\ufeff", content], { type: "text/csv;charset=utf-8" }));
  link.download = filename;
  link.click();
  URL.revokeObjectURL(link.href);
}

function compare(left: unknown, right: unknown): number {
  const a = Number(left);
  const b = Number(right);
  if (Number.isFinite(a) && Number.isFinite(b)) return a - b;
  return String(left ?? "").localeCompare(String(right ?? ""), "zh-CN");
}
