import type { SelfOperatedFilters, SelfOperatedKpiSummary, SelfOperatedLedgerRow } from '../types';
import { resolveSystemVehicleType } from './vehicle-ref';

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

export function isBlankDisplayValue(value: unknown): boolean {
  return value === null
    || value === undefined
    || value === ''
    || value === '—'
    || value === '-'
    || value === '/';
}

export function displayText(value: unknown): string {
  if (isBlankDisplayValue(value)) return '';
  return String(value);
}

export function displayMoney(value: number | null | undefined, treatZeroAsEmpty = false): string {
  if (value === null || value === undefined) return '';
  if (treatZeroAsEmpty && value === 0) return '';
  return formatMoney(value);
}

function roundMoney(value: number): number {
  return Math.round(value * 100) / 100;
}

/** 金额 = 单价 × 数量 */
export function computeAmount(row: SelfOperatedLedgerRow): number {
  return roundMoney(row.unitPrice * row.quantity);
}

/** 总成本 = 氢费 + 人工报销费用 + ETC + 电费 + 薪资 + 车辆费用 */
export function computeTotalCost(row: SelfOperatedLedgerRow): number {
  return roundMoney(
    row.hydrogenFee
    + row.manualReimbursement
    + row.etcFee
    + row.electricityFee
    + row.salary
    + row.vehicleFee,
  );
}

export function computeProfitLoss(row: SelfOperatedLedgerRow): number {
  return roundMoney(computeAmount(row) - computeTotalCost(row));
}

export function profitLossClassName(value: number): string {
  if (value > 0) return 'sob-val--rise';
  if (value < 0) return 'sob-val--fall';
  return '';
}

const MONTH_DISPLAY_RE = /^\d{4}-\d{2}$/;

function padMonthPart(value: string): string {
  const n = Number.parseInt(value, 10);
  if (!Number.isFinite(n) || n < 1 || n > 12) return value.padStart(2, '0');
  return String(n).padStart(2, '0');
}

function yearFromDispatchDate(dispatchDate: string): string {
  const match = /^(\d{4})-/.exec(dispatchDate);
  return match?.[1] ?? String(new Date().getFullYear());
}

/** 列表展示：导入的年份、月份两列合并为 YYYY-MM */
export function formatDisplayMonth(row: SelfOperatedLedgerRow): string {
  if (MONTH_DISPLAY_RE.test(row.month)) return row.month;
  const year = row.year?.trim() || yearFromDispatchDate(row.dispatchDate);
  const monthPart = padMonthPart(row.month);
  return `${year}-${monthPart}`;
}

export function sumSelfKpi(rows: SelfOperatedLedgerRow[]): SelfOperatedKpiSummary {
  return rows.reduce(
    (acc, row) => {
      const totalCost = computeTotalCost(row);
      const profitLoss = computeProfitLoss(row);
      return {
        count: acc.count + 1,
        amount: acc.amount + computeAmount(row),
        totalCost: acc.totalCost + totalCost,
        hydrogenFee: acc.hydrogenFee + row.hydrogenFee,
        etcFee: acc.etcFee + row.etcFee,
        profitLoss: acc.profitLoss + 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 && formatDisplayMonth(row) !== filters.month) return false;
    if (filters.businessName && row.businessName !== filters.businessName) return false;
    if (filters.systemVehicleType && resolveSystemVehicleType(row.plateNo) !== filters.systemVehicleType) 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 function buildMonthFilterOptions(rows: SelfOperatedLedgerRow[]): string[] {
  const set = new Set<string>();
  rows.forEach((row) => set.add(formatDisplayMonth(row)));
  return Array.from(set).sort((a, b) => a.localeCompare(b, 'zh-CN'));
}

export function buildSystemVehicleTypeOptions(rows: SelfOperatedLedgerRow[]): string[] {
  const set = new Set<string>();
  rows.forEach((row) => {
    const label = resolveSystemVehicleType(row.plateNo);
    if (label) set.add(label);
  });
  return Array.from(set).sort((a, b) => a.localeCompare(b, 'zh-CN'));
}
