import type { DepartmentListQuery, OrgVO } from './types';

/** 收集组织树中所有节点 ID，用于默认展开全部节点。 */
export const collectOrgIds = (nodes: OrgVO[]): number[] =>
  nodes.flatMap((node) => [node.id, ...collectOrgIds(node.children ?? [])]);

/**
 * 按名称 / 类型 / 状态过滤组织树。
 * 命中节点保留完整子树；节点自身不命中但存在命中的后代时，保留其祖先链路。
 */
export const filterOrgTree = (nodes: OrgVO[], query: DepartmentListQuery): OrgVO[] => {
  const keyword = query.orgName?.trim().toLowerCase();

  const filterNodes = (list: OrgVO[]): OrgVO[] =>
    list.flatMap((node) => {
      const matchesSelf =
        (!keyword || node.orgName.toLowerCase().includes(keyword)) &&
        (!query.orgType || node.orgType === query.orgType) &&
        (!query.status || String(node.status) === query.status);

      if (matchesSelf) return [node];

      const children = filterNodes(node.children ?? []);
      return children.length ? [{ ...node, children }] : [];
    });

  return filterNodes(nodes);
};

export interface OrgTreeSelectOption {
  value: number;
  title: string;
  children?: OrgTreeSelectOption[];
}

/** 组织树转为 TreeSelect 数据；编辑时排除自身及其子树，避免把上级设为自身。 */
export const toOrgTreeSelectData = (
  nodes: OrgVO[],
  excludeId?: number,
): OrgTreeSelectOption[] =>
  nodes.flatMap((node) => {
    if (node.id === excludeId) return [];

    const children = toOrgTreeSelectData(node.children ?? [], excludeId);
    return [
      {
        value: node.id,
        title: node.orgName,
        children: children.length ? children : undefined,
      },
    ];
  });
