/**
 * 部门树选择的核心逻辑（与 UI 解耦，便于单测）
 *
 * 全部对齐 web 端 `form-create/components/dept-select.vue` —— 那里用的是
 * antd `TreeSelect`，且**没有**设置 `treeCheckStrictly` / `showCheckedStrategy`，
 * 因此走的是 antd 默认语义：
 *  - 单选（未开启 tree-checkable）：所有节点（含父级）都可作为值；
 *  - 多选：父子联动（勾父级连带全部后代，子级全选的祖先自动入集）；
 *  - 多选回填按默认 `showCheckedStrategy = SHOW_CHILD`，即最终值只保留叶子节点。
 */
import type { TreeNodeLike } from "./shared";

export interface DeptNode extends TreeNodeLike {
  name?: string;
  children?: DeptNode[];
}

/** key -> 节点 / 父节点 / 直接子节点 三张索引表 */
export interface DeptTreeIndex {
  nodeMap: Map<string, DeptNode>;
  parentMap: Map<string, string>;
  childMap: Map<string, DeptNode[]>;
}

export const deptKey = (node: DeptNode) => String(node?.id);

export function indexDeptTree(nodes: DeptNode[]): DeptTreeIndex {
  const nodeMap = new Map<string, DeptNode>();
  const parentMap = new Map<string, string>();
  const childMap = new Map<string, DeptNode[]>();
  const walk = (list: DeptNode[], parentKey?: string) => {
    (Array.isArray(list) ? list : []).forEach(node => {
      const key = deptKey(node);
      nodeMap.set(key, node);
      if (parentKey !== undefined) parentMap.set(key, parentKey);
      const children = Array.isArray(node.children) ? node.children : [];
      childMap.set(key, children);
      if (children.length) walk(children, key);
    });
  };
  walk(nodes || []);
  return { nodeMap, parentMap, childMap };
}

/** 以 key 为根的整棵子树（含自身） */
export function deptSubtreeKeys(index: DeptTreeIndex, key: string): string[] {
  const result = [key];
  (index.childMap.get(key) || []).forEach(child => {
    result.push(...deptSubtreeKeys(index, deptKey(child)));
  });
  return result;
}

/**
 * 勾选 / 取消单个节点（父子联动，对齐 antd `treeCheckStrictly = false`）。
 * 向下：连带整棵子树；向上：子级全选的祖先自动入集，否则出集（半选态不入集）。
 * 返回值是新的选中集，不修改入参。
 */
export function toggleDeptCheck(
  index: DeptTreeIndex,
  picked: string[],
  key: string,
): string[] {
  const set = new Set(picked);
  const subtree = deptSubtreeKeys(index, key);
  if (set.has(key)) subtree.forEach(item => set.delete(item));
  else subtree.forEach(item => set.add(item));

  let cursor = index.parentMap.get(key);
  while (cursor) {
    const siblings = index.childMap.get(cursor) || [];
    if (!siblings.length) break;
    if (siblings.every(child => set.has(deptKey(child)))) set.add(cursor);
    else set.delete(cursor);
    cursor = index.parentMap.get(cursor);
  }
  return [...set];
}

/** all 全选 / half 半选 / none 未选 */
export function deptCheckState(
  index: DeptTreeIndex,
  picked: Set<string>,
  key: string,
): "all" | "half" | "none" {
  const keys = deptSubtreeKeys(index, key);
  const checked = keys.filter(item => picked.has(item)).length;
  if (checked === 0) return "none";
  if (checked === keys.length) return "all";
  return "half";
}

/**
 * 提交值。
 * 移植 antd `formatStrategyValues` 的 SHOW_CHILD 分支：
 * 某节点只要「有子级在选中集里」且「全部子级都在选中集里」，该父节点就被剔除。
 * 配合父子联动，效果即最终只保留叶子节点 —— 与 web 端 dept-select.vue 存的值一致。
 */
export function deptSubmitKeys(
  index: DeptTreeIndex,
  picked: string[],
): Array<number | string> {
  const pickedSet = new Set(picked);
  return picked
    .filter(key => {
      const children = index.childMap.get(key) || [];
      if (!children.length) return true;
      const states = children.map(child => pickedSet.has(deptKey(child)));
      return !(states.some(Boolean) && states.every(Boolean));
    })
    .map(key => index.nodeMap.get(key)?.id as number | string)
    .filter(value => value !== undefined && value !== null);
}

/**
 * 搜索过滤（对齐 antd `filterTreeNode` + rc-tree filterTree）：
 * 节点自身命中时保留整棵子树（便于看清上下文），
 * 否则只要有后代命中就保留该节点作为路径。
 */
export function filterDeptTree(nodes: DeptNode[], keyword: string): DeptNode[] {
  const text = keyword.trim().toLowerCase();
  if (!text) return nodes || [];
  const result: DeptNode[] = [];
  (Array.isArray(nodes) ? nodes : []).forEach(node => {
    const children = Array.isArray(node.children) ? node.children : [];
    const selfMatch = String(node.name || "").toLowerCase().includes(text);
    if (selfMatch) {
      result.push(node);
      return;
    }
    const kept = filterDeptTree(children, text);
    if (kept.length) result.push({ ...node, children: kept });
  });
  return result;
}

/** 带层级的拍平结果，用于列表渲染 */
export interface DeptRow {
  key: string;
  node: DeptNode;
  depth: number;
  hasChildren: boolean;
  expanded: boolean;
  state: "all" | "half" | "none";
}

/**
 * 按展开状态把树拍平成可渲染的行。
 * children 取传入的「显示树」（搜索后是过滤过的），不会被整棵树覆盖。
 */
export function flattenDeptRows(
  index: DeptTreeIndex,
  displayNodes: DeptNode[],
  expandedKeys: Set<string>,
  pickedSet: Set<string>,
): DeptRow[] {
  const rows: DeptRow[] = [];
  const walk = (list: DeptNode[], depth: number) => {
    (Array.isArray(list) ? list : []).forEach(node => {
      const key = deptKey(node);
      const children = Array.isArray(node.children) ? node.children : [];
      const expanded = expandedKeys.has(key);
      rows.push({
        key,
        node,
        depth,
        hasChildren: children.length > 0,
        expanded,
        state: deptCheckState(index, pickedSet, key),
      });
      if (expanded && children.length) walk(children, depth + 1);
    });
  };
  walk(displayNodes, 0);
  return rows;
}

/** 树里有子节点的所有 key（用于「展开全部」） */
export function deptExpandableKeys(nodes: DeptNode[]): string[] {
  const keys: string[] = [];
  const walk = (list: DeptNode[]) => {
    (Array.isArray(list) ? list : []).forEach(node => {
      const children = Array.isArray(node.children) ? node.children : [];
      if (children.length) {
        keys.push(deptKey(node));
        walk(children);
      }
    });
  };
  walk(nodes || []);
  return keys;
}

/** 搜索时强制展开所有命中路径 */
export function deptVisibleKeys(nodes: DeptNode[]): Set<string> {
  const keys = new Set<string>();
  const walk = (list: DeptNode[]) => {
    (Array.isArray(list) ? list : []).forEach(node => {
      keys.add(deptKey(node));
      walk(Array.isArray(node.children) ? node.children : []);
    });
  };
  walk(nodes || []);
  return keys;
}
