import type { DictData, DeptSimple } from "../../../api/crm";

export function dateText(value?: string | number) {
  return value ? String(value).replace("T", " ").slice(0, 16) : "--";
}

export function dayText(value?: string | number) {
  return value ? String(value).slice(0, 10) : "--";
}

export function dictLabel(dicts: DictData[], type: string, value?: number | string, fallback = "--") {
  const raw = value === undefined || value === null ? "" : String(value);
  return dicts.find(item => item.dictType === type && (String(item.value) === raw || Number(item.value) === Number(value)))?.label || fallback;
}

export function dictOptions(dicts: DictData[], type: string) {
  return dicts.filter(item => item.dictType === type && item.status !== 1).sort((a, b) => (a.sort || 0) - (b.sort || 0));
}

export function userName(user?: { nickname?: string; username?: string }) {
  return user?.nickname || user?.username || "请选择";
}

export function normalizeDept(list: DeptSimple[]) {
  if (list.some(item => item.children?.length)) return list;
  const map = new Map<number, DeptSimple>();
  const roots: DeptSimple[] = [];
  list.forEach(item => map.set(item.id, { ...item, children: [] }));
  list.forEach(item => {
    const node = map.get(item.id);
    if (!node) return;
    if (item.parentId && item.parentId !== 0 && map.has(item.parentId)) map.get(item.parentId)?.children?.push(node);
    else roots.push(node);
  });
  return roots;
}

export function flattenDept(list: DeptSimple[], depth = 0): Array<DeptSimple & { depth: number }> {
  return list.flatMap(item => [{ ...item, depth }, ...flattenDept(item.children || [], depth + 1)]);
}
