import type {
  FinanceBusinessReportBatchExportQuery,
  FinanceBusinessReportDetailQuery,
  FinanceBusinessReportPeriodType,
  FinanceBusinessReportStatus,
} from '#/api/finance';

/**
 * 文件职责：经营报表页面纯函数与数据转换工具。
 */

/** 构建经营报表列表查询请求。 */
export function buildReportListQueryPayload(
  storeId: string,
  periodType: FinanceBusinessReportPeriodType,
  page: number,
  pageSize: number,
) {
  return {
    storeId,
    periodType,
    page,
    pageSize,
  };
}

/** 构建经营报表详情查询请求。 */
export function buildReportDetailQueryPayload(
  storeId: string,
  reportId: string,
): FinanceBusinessReportDetailQuery {
  return {
    storeId,
    reportId,
  };
}

/** 构建经营报表批量导出查询请求。 */
export function buildReportBatchExportQueryPayload(
  storeId: string,
  periodType: FinanceBusinessReportPeriodType,
  page: number,
  pageSize: number,
): FinanceBusinessReportBatchExportQuery {
  return {
    storeId,
    periodType,
    page,
    pageSize,
  };
}

/** 报表周期文案。 */
export function resolvePeriodTypeLabel(value: FinanceBusinessReportPeriodType) {
  if (value === 'weekly') return '周报';
  if (value === 'monthly') return '月报';
  return '日报';
}

/** 报表状态标签色。 */
export function resolveReportStatusTagColor(
  status: FinanceBusinessReportStatus,
) {
  if (status === 'succeeded') return 'green';
  if (status === 'failed') return 'red';
  if (status === 'running' || status === 'queued') return 'blue';
  return 'default';
}

/** 货币格式化（人民币）。 */
export function formatCurrency(value: number, fractionDigits = 0) {
  const digits = Math.max(0, Math.min(2, fractionDigits));
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: digits,
    maximumFractionDigits: digits,
  }).format(Number.isFinite(value) ? value : 0);
}

/** 订单数格式化。 */
export function formatOrderCount(value: number) {
  return `${Math.max(0, Math.round(value || 0))}单`;
}

/** 客单价格式化。 */
export function formatAverageOrderValue(value: number) {
  return formatCurrency(value, 1);
}

/** 百分比格式化。 */
export function formatPercent(value: number, digits = 1) {
  const safeDigits = Math.max(0, Math.min(2, digits));
  const normalized = Number.isFinite(value) ? value : 0;
  return `${normalized.toFixed(safeDigits)}%`;
}

/** 数值符号格式化。 */
export function formatSignedRate(value: number, digits = 1) {
  const normalized = Number.isFinite(value) ? value : 0;
  if (normalized === 0) {
    return `${normalized.toFixed(digits)}%`;
  }

  return `${normalized > 0 ? '↑' : '↓'}${Math.abs(normalized).toFixed(digits)}%`;
}

function decodeBase64ToBlob(base64: string, mimeType: 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: mimeType });
}

/** 下载 Base64 编码文件。 */
export function downloadBase64File(
  fileName: string,
  fileContentBase64: string,
  mimeType = 'application/octet-stream',
) {
  const blob = decodeBase64ToBlob(fileContentBase64, mimeType);
  const url = URL.createObjectURL(blob);
  const anchor = document.createElement('a');
  anchor.href = url;
  anchor.download = fileName;
  anchor.click();
  URL.revokeObjectURL(url);
}
