export function formatCurrency(value: number) {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: 0,
    maximumFractionDigits: 2,
  }).format(Number.isFinite(value) ? value : 0);
}

export function formatCurrencyWithFraction(value: number) {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(Number.isFinite(value) ? value : 0);
}

export function formatInteger(value: number) {
  return new Intl.NumberFormat('zh-CN', {
    maximumFractionDigits: 0,
  }).format(Number.isFinite(value) ? value : 0);
}

export function formatPercent(value: number) {
  if (!Number.isFinite(value)) {
    return '0%';
  }
  return `${value.toFixed(1).replace(/\.0$/, '')}%`;
}

export function formatSignedPercent(value: number) {
  const normalized = Number.isFinite(value) ? value : 0;
  const sign = normalized > 0 ? '+' : '';
  return `${sign}${formatPercent(normalized)}`;
}

export function resolveTagColor(tone: string) {
  if (tone === 'orange') return 'orange';
  if (tone === 'green') return 'green';
  if (tone === 'gray') return 'default';
  if (tone === 'red') return 'red';
  return 'blue';
}

export function resolveRfmCellToneClass(tone: string) {
  if (tone === 'hot') return 'hot';
  if (tone === 'warm') return 'warm';
  if (tone === 'cool') return 'cool';
  return 'cold';
}

export function resolveCompositionToneColor(tone: string) {
  if (tone === 'green') return '#52c41a';
  if (tone === 'orange') return '#fa8c16';
  if (tone === 'gray') return '#e5e7eb';
  return '#1677ff';
}

export function resolveDistributionColor(index: number) {
  const palette = ['#7fb4ff', '#4a95ff', '#1677ff', '#1061d6', '#0a4eaf'];
  return palette[Math.max(0, Math.min(index, palette.length - 1))] ?? '#1677ff';
}

export function resolveAvatarText(name: string) {
  const normalized = String(name || '').trim();
  return normalized ? normalized.slice(0, 1) : '客';
}

function decodeBase64ToBlob(base64: string) {
  const binary = atob(base64);
  const bytes = new Uint8Array(binary.length);
  for (let index = 0; index < binary.length; index += 1) {
    bytes[index] = binary.codePointAt(index) ?? 0;
  }
  return new Blob([bytes], { type: 'text/csv;charset=utf-8;' });
}

export function downloadBase64File(
  fileName: string,
  fileContentBase64: string,
) {
  const blob = decodeBase64ToBlob(fileContentBase64);
  const url = URL.createObjectURL(blob);
  const anchor = document.createElement('a');
  anchor.href = url;
  anchor.download = fileName;
  anchor.click();
  URL.revokeObjectURL(url);
}
