import type { SupplierFilters, SupplierKpiKey, SupplierRecord } from '../types';

export function applyFilters(
  records: SupplierRecord[],
  filters: SupplierFilters,
  kpiTab: SupplierKpiKey,
): SupplierRecord[] {
  return records.filter((record) => {
    if (kpiTab === 'cooperated' && record.coopStatus !== '已合作') return false;
    if (kpiTab === 'negotiating' && record.coopStatus !== '洽谈中') return false;
    if (kpiTab === 'terminated' && record.coopStatus !== '终止合作') return false;
    if (kpiTab === 'expired' && record.coopStatus !== '合约过期') return false;
    if (kpiTab === 'parts' && record.type !== '备件供应商') return false;
    if (kpiTab === 'insurance' && record.type !== '保险公司') return false;
    if (kpiTab === 'licenseAbnormal' && record.licenseStatus !== '异常') return false;

    if (filters.code && record.supplierCode !== filters.code) return false;
    if (filters.coopStatuses.length > 0 && !filters.coopStatuses.includes(record.coopStatus)) {
      return false;
    }
    if (filters.types.length > 0 && !filters.types.includes(record.type)) return false;
    if (filters.regions.length > 0 && !filters.regions.includes(record.region)) return false;
    if (filters.city && record.city !== filters.city) return false;
    if (filters.creator && record.creator !== filters.creator) return false;
    if (filters.nameKeyword) {
      const kw = filters.nameKeyword.trim().toLowerCase();
      if (!record.supplierName.toLowerCase().includes(kw)) return false;
    }
    return true;
  });
}

export function buildOptions(records: SupplierRecord[], key: keyof SupplierRecord): string[] {
  const set = new Set<string>();
  records.forEach((record) => {
    const value = record[key];
    if (typeof value === 'string' && value.trim()) set.add(value);
  });
  return Array.from(set).sort((a, b) => a.localeCompare(b, 'zh-CN'));
}

export function buildCodeOptions(records: SupplierRecord[]): Array<{ value: string; label: string }> {
  return records.map((record) => ({
    value: record.supplierCode,
    label: `${record.supplierCode} · ${record.supplierName}`,
  }));
}

export function countKpi(records: SupplierRecord[], key: SupplierKpiKey): number {
  if (key === 'all') return records.length;
  if (key === 'cooperated') return records.filter((r) => r.coopStatus === '已合作').length;
  if (key === 'negotiating') return records.filter((r) => r.coopStatus === '洽谈中').length;
  if (key === 'terminated') return records.filter((r) => r.coopStatus === '终止合作').length;
  if (key === 'expired') return records.filter((r) => r.coopStatus === '合约过期').length;
  if (key === 'parts') return records.filter((r) => r.type === '备件供应商').length;
  if (key === 'insurance') return records.filter((r) => r.type === '保险公司').length;
  if (key === 'licenseAbnormal') return records.filter((r) => r.licenseStatus === '异常').length;
  return 0;
}
