import type {
  CustomerOrderCountRangeFilter,
  CustomerRegisterPeriodFilter,
  CustomerTagFilter,
} from '#/api/customer';

function toStringValue(value: unknown) {
  if (Array.isArray(value)) {
    return String(value[0] || '');
  }
  if (typeof value === 'number' || typeof value === 'string') {
    return String(value);
  }
  return '';
}

export function parseRouteQueryValue(value: unknown) {
  return toStringValue(value).trim();
}

export function normalizeTagFilter(tag: CustomerTagFilter) {
  return tag === 'all' ? undefined : tag;
}

export function normalizeOrderCountRangeFilter(
  range: CustomerOrderCountRangeFilter,
) {
  return range === 'all' ? undefined : range;
}

export function normalizeRegisterPeriodFilter(
  period: CustomerRegisterPeriodFilter,
) {
  return period === 'all' ? undefined : period;
}

export function buildRouteQuery(
  currentQuery: Record<string, unknown>,
  storeId: string,
  customerKey: string,
) {
  const nextQuery: Record<string, string> = {};
  for (const [key, value] of Object.entries(currentQuery)) {
    if (key === 'storeId' || key === 'customerKey') {
      continue;
    }
    const normalized = parseRouteQueryValue(value);
    if (!normalized) {
      continue;
    }
    nextQuery[key] = normalized;
  }
  if (storeId) {
    nextQuery.storeId = storeId;
  }
  if (customerKey) {
    nextQuery.customerKey = customerKey;
  }
  return nextQuery;
}

export function formatCurrency(value: number) {
  return new Intl.NumberFormat('zh-CN', {
    currency: 'CNY',
    maximumFractionDigits: 2,
    minimumFractionDigits: 2,
    style: 'currency',
  }).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 resolveAvatarText(name: string) {
  const normalized = String(name || '').trim();
  return normalized ? normalized.slice(0, 1) : '客';
}

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 resolveDeliveryTagColor(deliveryType: string) {
  if (deliveryType.includes('外卖')) return 'blue';
  if (deliveryType.includes('自提')) return 'green';
  if (deliveryType.includes('堂食')) return 'orange';
  return 'default';
}

export function resolveOrderStatusClass(status: string) {
  if (status.includes('完成')) return 'success';
  if (status.includes('取消') || status.includes('流失')) return 'danger';
  if (status.includes('配送') || status.includes('制作')) return 'processing';
  return 'default';
}
