import { cleanup, render, screen, waitFor } from '@testing-library/react';
import { afterEach, expect, test, vi } from 'vitest';
import { Mileage } from '../pages/Mileage';

afterEach(() => {
  cleanup();
  vi.restoreAllMocks();
});

test('renders date-range mileage summary, trend and daily detail list', async () => {
  const fetchMock = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
    const path = String(input);
    const data = path.includes('/api/v2/statistics/mileage')
      ? {
          dateFrom: '2026-07-01', dateTo: '2026-07-03', vehicleCount: 1, recordCount: 3, sourceCount: 1,
          periodMileageKm: 210.5, fleetLatestMileageKm: 48000, averageMileagePerVin: 210.5,
          averageDailyMileageKm: 70.2, trend: [
            { date: '2026-07-01', mileageKm: 60, vehicles: 1 },
            { date: '2026-07-02', mileageKm: 70, vehicles: 1 },
            { date: '2026-07-03', mileageKm: 80.5, vehicles: 1 }
          ], ranking: [], asOf: '2026-07-04 00:05:00', evidence: 'vehicle_daily_mileage'
        }
      : {
          items: [{ vin: 'VIN-MILEAGE-001', plate: '粤A12345', date: '2026-07-03', startMileageKm: 47919.5, endMileageKm: 48000, dailyMileageKm: 80.5, source: 'JT808' }],
          total: 1, limit: 20, offset: 0
        };
    return { ok: true, json: async () => ({ data, traceId: 'trace-mileage', timestamp: Date.now() }) } as Response;
  });

  render(
    <Mileage
      initialVin="粤A12345"
      initialProtocol="JT808"
      initialFilters={{ dateFrom: '2026-07-01', dateTo: '2026-07-03' }}
      onOpenVehicle={() => undefined}
    />
  );

  expect(screen.getByRole('heading', { name: '车辆里程统计' })).toBeInTheDocument();
  expect(await screen.findByLabelText('每日里程趋势图')).toBeInTheDocument();
  expect((await screen.findAllByText('210.5 km')).length).toBeGreaterThanOrEqual(1);
  expect(screen.getByText('粤A12345')).toBeInTheDocument();
  expect(screen.getAllByText('80.5').length).toBeGreaterThanOrEqual(1);
  await waitFor(() => expect(fetchMock).toHaveBeenCalledWith(expect.stringContaining('dateFrom=2026-07-01'), { signal: expect.any(AbortSignal) }));
  expect(fetchMock).toHaveBeenCalledWith(expect.stringContaining('keyword=%E7%B2%A4A12345'), { signal: expect.any(AbortSignal) });
});
