import type { CustomerFilters, CustomerRecord } from '../types';

function parseDate(value: string): number | null {
  if (!value) return null;
  const ts = Date.parse(value.replace(' ', 'T'));
  return Number.isNaN(ts) ? null : ts;
}

function inDateRange(createTime: string, from: string, to: string): boolean {
  const recordTs = parseDate(createTime);
  if (recordTs == null) return true;
  const fromTs = from ? parseDate(`${from}T00:00:00`) : null;
  const toTs = to ? parseDate(`${to}T23:59:59`) : null;
  if (fromTs != null && recordTs < fromTs) return false;
  if (toTs != null && recordTs > toTs) return false;
  return true;
}

export function applyFilters(records: CustomerRecord[], filters: CustomerFilters): CustomerRecord[] {
  return records.filter((record) => {
    if (filters.code && record.code !== filters.code) return false;
    if (filters.name && record.name !== filters.name) return false;
    if (filters.region && record.region !== filters.region) return false;
    if (filters.labels.length > 0 && !filters.labels.some((tag) => record.labels.includes(tag))) {
      return false;
    }
    if (filters.statuses.length > 0 && !filters.statuses.includes(record.status)) return false;
    if (filters.departments.length > 0 && !filters.departments.includes(record.department)) {
      return false;
    }
    if (filters.managers.length > 0 && !filters.managers.includes(record.manager)) return false;
    if (!inDateRange(record.createTime, filters.createFrom, filters.createTo)) return false;
    return true;
  });
}

export function buildOptions(records: CustomerRecord[], key: keyof CustomerRecord): 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: CustomerRecord[]): Array<{ value: string; label: string }> {
  return records.map((record) => ({
    value: record.code,
    label: `${record.code} · ${record.name}`,
  }));
}

export function buildDeptManagerMap(records: CustomerRecord[]): Record<string, string[]> {
  const map: Record<string, string[]> = {};
  records.forEach((record) => {
    if (!record.department) return;
    if (!map[record.department]) map[record.department] = [];
    if (record.manager && !map[record.department].includes(record.manager)) {
      map[record.department].push(record.manager);
    }
  });
  Object.keys(map).forEach((dept) => {
    map[dept].sort((a, b) => a.localeCompare(b, 'zh-CN'));
  });
  return map;
}

export function getManagerOptions(
  deptManagerMap: Record<string, string[]>,
  departments: string[],
): string[] {
  if (departments.length === 0) {
    const all = new Set<string>();
    Object.values(deptManagerMap).forEach((managers) => {
      managers.forEach((manager) => all.add(manager));
    });
    return Array.from(all).sort((a, b) => a.localeCompare(b, 'zh-CN'));
  }
  const pick = new Set<string>();
  departments.forEach((dept) => {
    (deptManagerMap[dept] ?? []).forEach((manager) => pick.add(manager));
  });
  return Array.from(pick).sort((a, b) => a.localeCompare(b, 'zh-CN'));
}
