import type { KpiKey, VehicleFilters, VehicleRecord } from '../types';
import {
  formatOperateCity,
  isEmpty,
  matchKpi,
  normalizePlate,
  displayText,
  OPERATE_CITY_SEED,
  parseRegionParts,
  PARKING_REGION_MAP,
  MUNICIPALITIES,
} from './vehicle';

export interface OperateCityTreeNode {
  province: string;
  cities: string[];
}

export function applyFilters(
  records: VehicleRecord[],
  filters: VehicleFilters,
  kpiTab: KpiKey,
): VehicleRecord[] {
  return records.filter((record) => {
    if (!matchKpi(record, kpiTab)) return false;

    if (filters.plateNos.length > 0) {
      const plate = normalizePlate(record.plateNo);
      if (!filters.plateNos.some((p) => normalizePlate(p) === plate)) return false;
    }

    if (filters.operateCities.length > 0) {
      const city = formatOperateCity(record.location);
      if (!filters.operateCities.some((c) => city.includes(c) || c.includes(city))) return false;
    }

    if (filters.brand && record.brand !== filters.brand) return false;
    if (filters.model && record.model !== filters.model) return false;
    if (filters.customer && record.customer !== filters.customer) return false;
    if (filters.department && record.department !== filters.department) return false;
    if (filters.projectName && displayText(record.projectName, '') !== filters.projectName) return false;
    if (filters.projectType && record.operateStatus !== filters.projectType) return false;
    if (filters.contractNo && record.contractNo !== filters.contractNo) return false;
    if (filters.ownership && record.ownership !== filters.ownership) return false;
    if (filters.operateCompany && record.operateCompany !== filters.operateCompany) return false;
    if (filters.operateStatus && record.operateStatus !== filters.operateStatus) return false;
    if (filters.vehicleSource && record.vehicleSource !== filters.vehicleSource) return false;
    if (filters.leaseCompany && record.leaseCompany !== filters.leaseCompany) return false;
    if (filters.parking && record.parking !== filters.parking) return false;
    if (filters.commercialInsurance && record.insuranceStatus !== filters.commercialInsurance) return false;
    if (filters.compulsoryInsurance && record.insuranceStatus !== filters.compulsoryInsurance) return false;

    return true;
  });
}
export function buildOptions(records: VehicleRecord[], key: keyof VehicleRecord): string[] {
  const set = new Set<string>();
  for (const r of records) {
    const v = r[key];
    if (!isEmpty(v)) set.add(String(v));
  }
  return Array.from(set).sort((a, b) => a.localeCompare(b, 'zh-CN'));
}

function collectOperateCities(records: VehicleRecord[]): string[] {
  const set = new Set<string>();
  const add = (city: string) => {
    if (!city || city === '—') return;
    set.add(city);
  };
  Object.values(PARKING_REGION_MAP).forEach(add);
  OPERATE_CITY_SEED.forEach(add);
  for (const r of records) {
    add(formatOperateCity(r.location));
  }
  return Array.from(set).sort((a, b) => a.localeCompare(b, 'zh-CN'));
}

export function buildOperateCityOptions(records: VehicleRecord[]): string[] {
  return collectOperateCities(records);
}

export function buildOperateCityTree(records: VehicleRecord[]): OperateCityTreeNode[] {
  const provinceMap = new Map<string, Set<string>>();
  for (const full of collectOperateCities(records)) {
    const { province, city } = parseRegionParts(full);
    if (!province) continue;
    if (!provinceMap.has(province)) provinceMap.set(province, new Set());
    const cities = provinceMap.get(province)!;
    if (city) cities.add(city);
    else cities.add(province);
  }
  return Array.from(provinceMap.entries())
    .map(([province, cities]) => ({
      province,
      cities: Array.from(cities).sort((a, b) => a.localeCompare(b, 'zh-CN')),
    }))
    .sort((a, b) => a.province.localeCompare(b.province, 'zh-CN'));
}

export function toOperateCityValue(province: string, city: string): string {
  if (!province) return '';
  if (MUNICIPALITIES.includes(province)) return `${province}-${province}`;
  if (!city || city === province) return province;
  return `${province}-${city}`;
}

/** 将「省-市」选择值写回 location 字段 */
export function operateCityValueToLocation(value: string): string {
  const { province, city } = parseRegionParts(value);
  if (!province) return value;
  if (MUNICIPALITIES.includes(province)) return province;
  if (!city || city === province) return province;
  return `${province}${city}`;
}
