import type { VehicleRecord } from '../types';
import { isEmpty, isShanghaiPlate } from './vehicle';

export interface LicensePhotoCert {
  photos: string[];
}

export interface DriverLicenseCert extends LicensePhotoCert {
  regDate: string;
  issueDate: string;
  scrapDate: string;
  expireDate: string;
  updateType: string;
  updateTime: string;
  updateUser: string;
  shNextEvaluation?: string;
}

export interface TransportLicenseCert extends LicensePhotoCert {
  licenseNo: string;
  issueDate: string;
  expireDate: string;
  inspectValidUntil: string;
  updateTime: string;
  updateUser: string;
}

export interface SpecialEquipDecalCert extends LicensePhotoCert {
  nextInspectDate: string;
  updateTime: string;
  updateUser: string;
}

export interface HydrogenCardCert {
  cardNo: string;
  cardType: string;
  balance: number;
  issueDate: string;
  issueUser: string;
}

export interface InspectPhotoCert extends LicensePhotoCert {
  inspectDate: string;
  nextInspectDate: string;
}

export interface VehicleLicenseBundle {
  driverLicense: DriverLicenseCert;
  transportLicense: TransportLicenseCert;
  registrationCert: LicensePhotoCert;
  specialEquipCert: LicensePhotoCert;
  specialEquipDecal: SpecialEquipDecalCert;
  hydrogenCard: HydrogenCardCert;
  safetyValve: InspectPhotoCert;
  pressureGauge: InspectPhotoCert;
}

export const LICENSE_CERT_NAV: Array<{ key: keyof VehicleLicenseBundle; label: string }> = [
  { key: 'driverLicense', label: '行驶证' },
  { key: 'transportLicense', label: '道路运输证' },
  { key: 'registrationCert', label: '登记证' },
  { key: 'specialEquipCert', label: '特种设备使用登记证' },
  { key: 'specialEquipDecal', label: '特种设备使用标识' },
  { key: 'hydrogenCard', label: '加氢卡' },
  { key: 'safetyValve', label: '安全阀' },
  { key: 'pressureGauge', label: '压力表' },
];

const SQUARE_PHOTO_SIZE = 400;

/** 方形证照样例图（原型演示） */
export function buildSquareSamplePhoto(seed: string): string {
  const safe = seed.replace(/[^a-zA-Z0-9_-]/g, '') || 'license';
  return `https://picsum.photos/seed/${safe}/${SQUARE_PHOTO_SIZE}/${SQUARE_PHOTO_SIZE}`;
}

function fillPhotoSamples(photos: string[], seed: string, defaultCount = 1): string[] {
  const count = Math.max(photos.length, defaultCount);
  return Array.from({ length: count }, (_, index) => buildSquareSamplePhoto(`${seed}-${index}`));
}

function fillLicensePhotoSamples(bundle: VehicleLicenseBundle, plateNo: string): VehicleLicenseBundle {
  const plateSeed = plateNo.replace(/[^a-zA-Z0-9]/g, '') || 'vehicle';
  bundle.driverLicense.photos = fillPhotoSamples(bundle.driverLicense.photos, `${plateSeed}-driver`, 2);
  bundle.transportLicense.photos = fillPhotoSamples(bundle.transportLicense.photos, `${plateSeed}-transport`, 1);
  bundle.registrationCert.photos = fillPhotoSamples(bundle.registrationCert.photos, `${plateSeed}-registration`, 1);
  bundle.specialEquipCert.photos = fillPhotoSamples(bundle.specialEquipCert.photos, `${plateSeed}-spec-cert`, 1);
  bundle.specialEquipDecal.photos = fillPhotoSamples(bundle.specialEquipDecal.photos, `${plateSeed}-spec-decal`, 1);
  bundle.safetyValve.photos = fillPhotoSamples(bundle.safetyValve.photos, `${plateSeed}-safety-valve`, 1);
  bundle.pressureGauge.photos = fillPhotoSamples(bundle.pressureGauge.photos, `${plateSeed}-pressure-gauge`, 1);
  return bundle;
}

const SEED_LICENSE_DATA: Record<string, VehicleLicenseBundle> = {
  沪A03561F: {
    driverLicense: {
      photos: ['https://picsum.photos/seed/license1/600/400', 'https://picsum.photos/seed/license2/600/400'],
      regDate: '2024-06-05',
      issueDate: '2024-06-05',
      scrapDate: '2039-06-04',
      expireDate: '2027-06-30',
      updateType: '直接上传',
      updateTime: '2026-05-28 14:32:00',
      updateUser: '李明辉',
      shNextEvaluation: '2026-06-30',
    },
    transportLicense: {
      photos: ['https://picsum.photos/seed/transport/600/400'],
      licenseNo: '交字310115102345号',
      issueDate: '2024-07-12',
      expireDate: '2026-07-31',
      inspectValidUntil: '2026-07-20',
      updateTime: '2026-05-10 11:20:00',
      updateUser: '陈高伟',
    },
    registrationCert: { photos: ['https://picsum.photos/seed/regcert1/600/400'] },
    specialEquipCert: { photos: ['https://picsum.photos/seed/spec1/600/400'] },
    specialEquipDecal: {
      photos: ['https://picsum.photos/seed/spec2/600/400'],
      nextInspectDate: '2027-05-20',
      updateTime: '2026-05-20 16:45:00',
      updateUser: '系统管理员',
    },
    hydrogenCard: {
      cardNo: 'H2-9988-7766-5544',
      cardType: '中石化加氢卡',
      balance: 12850.5,
      issueDate: '2025-01-15 14:30',
      issueUser: '能源管理部-张晓',
    },
    safetyValve: {
      photos: ['https://picsum.photos/seed/valve/600/400'],
      inspectDate: '2025-10-10',
      nextInspectDate: '2026-10-09',
    },
    pressureGauge: {
      photos: ['https://picsum.photos/seed/gauge/600/400'],
      inspectDate: '2025-12-15',
      nextInspectDate: '2026-06-14',
    },
  },
};

export function createEmptyLicenseBundle(): VehicleLicenseBundle {
  return {
    driverLicense: {
      photos: [],
      regDate: '',
      issueDate: '',
      scrapDate: '',
      expireDate: '',
      updateType: '',
      updateTime: '',
      updateUser: '',
    },
    transportLicense: {
      photos: [],
      licenseNo: '',
      issueDate: '',
      expireDate: '',
      inspectValidUntil: '',
      updateTime: '',
      updateUser: '',
    },
    registrationCert: { photos: [] },
    specialEquipCert: { photos: [] },
    specialEquipDecal: { photos: [], nextInspectDate: '', updateTime: '', updateUser: '' },
    hydrogenCard: { cardNo: '', cardType: '中石化加氢卡', balance: 0, issueDate: '', issueUser: '' },
    safetyValve: { photos: [], inspectDate: '', nextInspectDate: '' },
    pressureGauge: { photos: [], inspectDate: '', nextInspectDate: '' },
  };
}

function displayLicenseValue(value: unknown): string {
  if (value === null || value === undefined || value === '' || value === '-') return '未上传';
  return String(value);
}

function mergeFromRecord(record: VehicleRecord, bundle: VehicleLicenseBundle): VehicleLicenseBundle {
  const next = JSON.parse(JSON.stringify(bundle)) as VehicleLicenseBundle;
  const dl = next.driverLicense;

  if (isEmpty(dl.regDate) && !isEmpty(record.regDate)) dl.regDate = record.regDate;
  if (isEmpty(dl.scrapDate) && !isEmpty(record.scrapDate)) dl.scrapDate = record.scrapDate;
  if (isEmpty(dl.expireDate) && !isEmpty(record.inspectExpire)) dl.expireDate = record.inspectExpire;
  if (isShanghaiPlate(record.plateNo) && isEmpty(dl.shNextEvaluation) && !isEmpty(record.ratingTime)) {
    dl.shNextEvaluation = record.ratingTime.slice(0, 10);
  }

  return next;
}

export function resolveVehicleLicenseBundle(record: VehicleRecord): VehicleLicenseBundle {
  const seed = SEED_LICENSE_DATA[record.plateNo];
  const base = seed ? JSON.parse(JSON.stringify(seed)) as VehicleLicenseBundle : createEmptyLicenseBundle();
  const merged = mergeFromRecord(record, base);
  return fillLicensePhotoSamples(merged, record.plateNo);
}

export function formatLicenseDisplay(value: unknown): string {
  return displayLicenseValue(value);
}

export function formatLicenseBalance(balance: number): string {
  if (!balance) return '0.00';
  return balance.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

export function certHasPhotos(cert: LicensePhotoCert | InspectPhotoCert): boolean {
  return cert.photos.length > 0;
}

export function certPhotoStatus(cert: LicensePhotoCert | InspectPhotoCert): 'uploaded' | 'empty' {
  return cert.photos.length > 0 ? 'uploaded' : 'empty';
}

export type LicenseCertBadgeStatus = 'success' | 'warning' | 'error' | 'default';

const LICENSE_STATUS_REFERENCE_DATE = new Date('2026-06-01');

function startOfDay(date: Date): Date {
  const next = new Date(date);
  next.setHours(0, 0, 0, 0);
  return next;
}

function daysUntil(dateStr: string, today = LICENSE_STATUS_REFERENCE_DATE): number {
  const target = startOfDay(new Date(dateStr));
  const base = startOfDay(today);
  return Math.ceil((target.getTime() - base.getTime()) / (1000 * 60 * 60 * 24));
}

function mergeLicenseStatusTypes(a: LicenseCertBadgeStatus, b: LicenseCertBadgeStatus): LicenseCertBadgeStatus {
  const rank: Record<LicenseCertBadgeStatus, number> = {
    error: 0,
    warning: 1,
    default: 2,
    success: 3,
  };
  return rank[a] <= rank[b] ? a : b;
}

function badgeFromExpiry(dateStr: string | undefined, warnDays: number): LicenseCertBadgeStatus {
  if (!dateStr) return 'success';
  const diffDays = daysUntil(dateStr);
  if (diffDays <= 0) return 'error';
  if (diffDays <= warnDays) return 'warning';
  return 'success';
}

/** 证照索引状态点（与证照管理台账/编辑页规则一致） */
export function getLicenseCertBadgeStatus(
  bundle: VehicleLicenseBundle,
  key: keyof VehicleLicenseBundle,
): LicenseCertBadgeStatus {
  if (key === 'hydrogenCard') {
    return bundle.hydrogenCard.cardNo ? 'success' : 'default';
  }

  const item = bundle[key] as LicensePhotoCert | InspectPhotoCert | SpecialEquipDecalCert;
  if (!item.photos?.length) return 'default';

  if (key === 'driverLicense') {
    return badgeFromExpiry(bundle.driverLicense.expireDate, 90);
  }

  if (key === 'transportLicense') {
    return mergeLicenseStatusTypes(
      badgeFromExpiry(bundle.transportLicense.expireDate, 60),
      badgeFromExpiry(bundle.transportLicense.inspectValidUntil, 60),
    );
  }

  if (key === 'specialEquipDecal' || key === 'safetyValve' || key === 'pressureGauge') {
    const dateKey = 'nextInspectDate' as const;
    const cert = bundle[key] as SpecialEquipDecalCert | InspectPhotoCert;
    return badgeFromExpiry(cert[dateKey], 60);
  }

  return 'success';
}

export const LICENSE_CERT_STATUS_LEGEND = [
  { status: 'success' as const, label: '正常' },
  {
    status: 'warning' as const,
    label: '临期',
    title: '行驶证≤90天 / 道路运输证≤60天 / 特种设备标识≤60天 / 安全阀≤60天 / 压力表≤60天',
  },
  {
    status: 'error' as const,
    label: '已到期',
    title: '行驶证检验有效期到期 / 道路运输证有效期/检验时间到期 / 安全阀、压力表下次检验到期',
  },
  { status: 'default' as const, label: '未上传' },
];
