import type {
  CustomerFilterQueryPayload,
  CustomerFilterState,
  CustomerListQueryPayload,
} from '../../types';

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

function normalizeTag(tag: CustomerTagFilter): CustomerTagFilter | undefined {
  return tag === 'all' ? undefined : tag;
}

function normalizeOrderCountRange(
  orderCountRange: CustomerOrderCountRangeFilter,
): CustomerOrderCountRangeFilter | undefined {
  return orderCountRange === 'all' ? undefined : orderCountRange;
}

function normalizeRegisterPeriod(
  registerPeriod: CustomerRegisterPeriodFilter,
): CustomerRegisterPeriodFilter | undefined {
  return registerPeriod === 'all' ? undefined : registerPeriod;
}

export function buildFilterPayload(
  storeId: string,
  filters: CustomerFilterState,
): CustomerFilterQueryPayload {
  return {
    storeId,
    keyword: filters.keyword.trim() || undefined,
    tag: normalizeTag(filters.tag),
    orderCountRange: normalizeOrderCountRange(filters.orderCountRange),
    registerPeriod: normalizeRegisterPeriod(filters.registerPeriod),
  };
}

export function buildQueryPayload(
  storeId: string,
  filters: CustomerFilterState,
  page: number,
  pageSize: number,
): CustomerListQueryPayload {
  return {
    ...buildFilterPayload(storeId, filters),
    page,
    pageSize,
  };
}

export function formatCurrency(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$/, '')}%`;
}

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);
}

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';
}
