import type { SelfOperatedLedgerRow } from '../types';
import { computeAmount, computeProfitLoss, computeTotalCost } from './ledger';
import { resolveSystemVehicleType } from './vehicle-ref';

const IMPORT_DEFAULTS: Omit<SelfOperatedLedgerRow, 'id'> = {
  year: '',
  month: '',
  dispatchDate: '',
  businessName: '',
  driver: '',
  phone: '',
  plateNo: '',
  systemVehicleType: '',
  unitPrice: 0,
  quantity: 0,
  amount: 0,
  hydrogenFee: 0,
  etcFee: 0,
  salary: 0,
  electricityFee: 0,
  manualReimbursement: 0,
  dailySocialSecurityFee: 0,
  dailyTrailerServiceFee: 0,
  dailyTrailerFee: 0,
  dailyParkingFee: 0,
  dailyTireFee: 0,
  vehicleFee: 0,
  totalCost: 0,
  profitLoss: 0,
  multiTrip: '',
  routePricing: '',
  remark: '',
};

/** 导入后计算金额、总成本、盈亏（列表公式列） */
export function applyImportCalculations(draft: Partial<SelfOperatedLedgerRow>): SelfOperatedLedgerRow {
  const row: SelfOperatedLedgerRow = {
    ...IMPORT_DEFAULTS,
    ...draft,
    id: draft.id ?? `import-${Date.now()}`,
    year: String(draft.year ?? '').trim(),
    month: String(draft.month ?? '').trim(),
    unitPrice: draft.unitPrice ?? 0,
    quantity: draft.quantity ?? 0,
  };

  row.systemVehicleType = resolveSystemVehicleType(row.plateNo);
  row.amount = computeAmount(row);
  row.totalCost = computeTotalCost(row);
  row.profitLoss = computeProfitLoss(row);
  return row;
}
