import type { OrderAllFilterState, OrderAllQueryPayload } from '../../types';

import type {
  OrderAllChannelFilter,
  OrderAllPaymentFilter,
  OrderAllStatusFilter,
} from '#/api/order';

export function getTodayDateString() {
  const now = new Date();
  const year = now.getFullYear();
  const month = `${now.getMonth() + 1}`.padStart(2, '0');
  const day = `${now.getDate()}`.padStart(2, '0');
  return `${year}-${month}-${day}`;
}

function normalizeStatus(
  status: OrderAllStatusFilter,
): OrderAllStatusFilter | undefined {
  return status === 'all' ? undefined : status;
}

function normalizeChannel(
  channel: OrderAllChannelFilter,
): OrderAllChannelFilter | undefined {
  return channel === 'all' ? undefined : channel;
}

function normalizePayment(
  paymentMethod: OrderAllPaymentFilter,
): OrderAllPaymentFilter | undefined {
  return paymentMethod === 'all' ? undefined : paymentMethod;
}

export function buildQueryPayload(
  storeId: string,
  filters: OrderAllFilterState,
  page: number,
  pageSize: number,
): OrderAllQueryPayload {
  return {
    storeId,
    page,
    pageSize,
    startDate: filters.startDate || undefined,
    endDate: filters.endDate || undefined,
    status: normalizeStatus(filters.status),
    channel: normalizeChannel(filters.channel),
    paymentMethod: normalizePayment(filters.paymentMethod),
    keyword: filters.keyword.trim() || undefined,
  };
}

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 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 isDateRangeInvalid(filters: OrderAllFilterState) {
  if (!filters.startDate || !filters.endDate) {
    return false;
  }

  return filters.startDate > filters.endDate;
}
