import type { SelfOperatedFilters, SelfOperatedKpiSummary, SelfOperatedLedgerRow } from '../types';

export function formatMoney(value: number): string {
  return value.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

export function sumSelfKpi(rows: SelfOperatedLedgerRow[]): SelfOperatedKpiSummary {
  return rows.reduce(
    (acc, row) => ({
      count: acc.count + 1,
      amount: acc.amount + row.amount,
      totalCost: acc.totalCost + row.totalCost,
      hydrogenFee: acc.hydrogenFee + row.hydrogenFee,
      etcFee: acc.etcFee + row.etcFee,
      profitLoss: acc.profitLoss + row.profitLoss,
    }),
    { count: 0, amount: 0, totalCost: 0, hydrogenFee: 0, etcFee: 0, profitLoss: 0 },
  );
}

export function applySelfFilters(rows: SelfOperatedLedgerRow[], filters: SelfOperatedFilters): SelfOperatedLedgerRow[] {
  return rows.filter((row) => {
    if (filters.month && row.month !== filters.month) return false;
    if (filters.businessName && row.businessName !== filters.businessName) return false;
    if (filters.vehicleUndertaker && row.vehicleUndertaker !== filters.vehicleUndertaker) return false;
    if (filters.brand && row.brand !== filters.brand) return false;
    if (filters.model && row.model !== filters.model) return false;
    if (filters.maintainerName && row.maintainerName !== filters.maintainerName) return false;
    if (filters.plateNos.length > 0 && !filters.plateNos.includes(row.plateNo)) return false;
    if (filters.dispatchFrom && row.dispatchDate < filters.dispatchFrom) return false;
    if (filters.dispatchTo && row.dispatchDate > filters.dispatchTo) return false;
    return true;
  });
}

export function buildSelfOptions(rows: SelfOperatedLedgerRow[], key: keyof SelfOperatedLedgerRow): string[] {
  const set = new Set<string>();
  rows.forEach((row) => {
    const value = row[key];
    if (typeof value === 'string' && value.trim()) set.add(value);
  });
  return Array.from(set).sort((a, b) => a.localeCompare(b, 'zh-CN'));
}

export const UNDERTAKER_OPTIONS = ['我司', '第三方车队'];

export const BRAND_MODEL_MAP: Record<string, string[]> = {
  现代: ['帕力安牌4.5吨冷链车', '帕力安牌18吨双飞翼货车'],
  飞驰: ['49吨牵引车头'],
  苏龙: ['海格牌KLQ5180XYKFCEV'],
};
