OrgTree.tsx 7.92 KB
"use client";

import { useState } from "react";
import { ChevronDown, ChevronRight } from "lucide-react";
import type { KbInfo, OaDept } from "@/lib/auth";

// ============================================================
// 一、部门组织树多选(授权 / 数据范围用):任一节点可勾,节点之间相互独立。
//     勾选某中心 = 一条"授该节点整棵子树"的记录(由后端展开),不在前端展开成子节点。
// ============================================================

export function DeptCheckTree({
  nodes,
  selected,
  onToggle,
  disabledIds,
  badgeOf,
  partialIds,
}: {
  nodes: OaDept[];
  selected: Set<string>;
  onToggle: (id: string) => void;
  disabledIds?: Set<string>;               // 勾选但不可改(自身部门 / 被上级授权继承)
  badgeOf?: (id: string) => string | undefined;  // 节点后缀小标签(如「自身」「继承」)
  partialIds?: Set<string>;                // 自身未选,但下属部分被选 → 半选态(提示可展开查看)
}) {
  return (
    <ul className="space-y-0.5">
      {nodes.map((n) => (
        <DeptCheckNode
          key={n.id} node={n} selected={selected} onToggle={onToggle}
          disabledIds={disabledIds} badgeOf={badgeOf} partialIds={partialIds} depth={0}
        />
      ))}
    </ul>
  );
}

function DeptCheckNode({
  node,
  selected,
  onToggle,
  disabledIds,
  badgeOf,
  partialIds,
  depth,
}: {
  node: OaDept;
  selected: Set<string>;
  onToggle: (id: string) => void;
  disabledIds?: Set<string>;
  badgeOf?: (id: string) => string | undefined;
  partialIds?: Set<string>;
  depth: number;
}) {
  const [open, setOpen] = useState(depth < 1); // 默认展开到中心一层
  const kids = node.children ?? [];
  const disabled = disabledIds?.has(node.id) ?? false;
  const checked = selected.has(node.id);
  const partial = !checked && (partialIds?.has(node.id) ?? false);
  const badge = badgeOf?.(node.id);
  return (
    <li>
      <div className="flex items-center gap-1" style={{ paddingLeft: depth * 16 }}>
        {kids.length > 0 ? (
          <button
            type="button"
            onClick={() => setOpen((o) => !o)}
            className="flex h-5 w-5 items-center justify-center rounded text-slate-400 hover:bg-slate-100"
          >
            {open ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
          </button>
        ) : (
          <span className="inline-block h-5 w-5" />
        )}
        <label
          className={`flex flex-1 items-center gap-2 rounded px-1.5 py-1 ${
            disabled ? "cursor-not-allowed" : "cursor-pointer hover:bg-blue-50/60"
          }`}
        >
          <input
            type="checkbox"
            className="h-3.5 w-3.5 accent-blue-600 disabled:opacity-60"
            checked={checked}
            ref={(el) => { if (el) el.indeterminate = partial; }}
            disabled={disabled}
            onChange={() => { if (!disabled) onToggle(node.id); }}
          />
          <span className={`truncate text-sm ${disabled ? "text-slate-400" : "text-slate-700"}`}>
            {node.deptName}
          </span>
          {badge && (
            <span className="shrink-0 rounded bg-slate-100 px-1.5 py-0.5 text-[10px] font-medium text-slate-500">
              {badge}
            </span>
          )}
        </label>
      </div>
      {kids.length > 0 && open && (
        <ul className="space-y-0.5">
          {kids.map((c) => (
            <DeptCheckNode
              key={c.id} node={c} selected={selected} onToggle={onToggle}
              disabledIds={disabledIds} badgeOf={badgeOf} partialIds={partialIds} depth={depth + 1}
            />
          ))}
        </ul>
      )}
    </li>
  );
}

// ============================================================
// 二、知识库组织树多选(库选择器用):中心=分组表头(自身无库,不可直接选),
//     只有叶子部门=真实库可选;勾选中心 = 勾选其下全部子库(三态)。
// ============================================================

export interface KbTreeNode {
  key: string;          // 部门 id(分组)或库 id(叶子)
  label: string;
  kbId?: string;        // 叶子库才有
  children: KbTreeNode[];
}

/** 依据每个库的 deptIdPath 组织链构建 架构>中心>部门 的树;base 库单列在最前。 */
export function buildKbTree(kbs: KbInfo[]): { base: KbInfo[]; tree: KbTreeNode[] } {
  const base = kbs.filter((k) => k.kbType === "base");
  const dept = kbs.filter((k) => k.kbType !== "base");
  const roots: KbTreeNode[] = [];
  const byKey = new Map<string, KbTreeNode>();

  // 已按 sortKey 排序的输入可保证兄弟顺序;这里保持插入序
  const nameOf = (k: KbInfo, i: number) => (k.deptPath ? k.deptPath.split(" / ")[i] : k.kbName);

  for (const k of dept) {
    const idPath = k.deptIdPath && k.deptIdPath.length ? k.deptIdPath : [k.deptId || k.id];
    let parentList = roots;
    let accKey = "";
    for (let i = 0; i < idPath.length; i++) {
      const id = idPath[i];
      accKey = accKey ? `${accKey}/${id}` : id;
      const isLeaf = i === idPath.length - 1;
      let node = byKey.get(accKey);
      if (!node) {
        node = { key: accKey, label: nameOf(k, i) || id, children: [] };
        byKey.set(accKey, node);
        parentList.push(node);
      }
      if (isLeaf) node.kbId = k.id; // 叶子=真实库
      parentList = node.children;
    }
  }
  return { base, tree: roots };
}

/** 收集某节点子树下的全部库 id(叶子)。 */
export function collectKbIds(node: KbTreeNode, out: string[] = []): string[] {
  if (node.kbId) out.push(node.kbId);
  for (const c of node.children) collectKbIds(c, out);
  return out;
}

export function KbCheckTree({
  tree,
  selected,
  onToggleKbs,
}: {
  tree: KbTreeNode[];
  selected: Set<string>;      // 已选库 id 集合
  onToggleKbs: (kbIds: string[], next: boolean) => void; // 批量勾/取消
}) {
  return (
    <ul className="space-y-0.5">
      {tree.map((n) => (
        <KbCheckNode key={n.key} node={n} selected={selected} onToggleKbs={onToggleKbs} depth={0} />
      ))}
    </ul>
  );
}

function KbCheckNode({
  node,
  selected,
  onToggleKbs,
  depth,
}: {
  node: KbTreeNode;
  selected: Set<string>;
  onToggleKbs: (kbIds: string[], next: boolean) => void;
  depth: number;
}) {
  const [open, setOpen] = useState(true);
  const allKbs = collectKbIds(node);
  const selCount = allKbs.filter((id) => selected.has(id)).length;
  const checked = allKbs.length > 0 && selCount === allKbs.length;
  const indeterminate = selCount > 0 && selCount < allKbs.length;
  const isGroup = node.children.length > 0;

  return (
    <li>
      <div className="flex items-center gap-1" style={{ paddingLeft: depth * 16 }}>
        {isGroup ? (
          <button
            type="button"
            onClick={() => setOpen((o) => !o)}
            className="flex h-5 w-5 items-center justify-center rounded text-slate-400 hover:bg-slate-100"
          >
            {open ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
          </button>
        ) : (
          <span className="inline-block h-5 w-5" />
        )}
        <label className="flex flex-1 cursor-pointer items-center gap-2 rounded px-1.5 py-1 hover:bg-blue-50/60">
          <input
            type="checkbox"
            className="h-3.5 w-3.5 accent-blue-600"
            checked={checked}
            ref={(el) => { if (el) el.indeterminate = indeterminate; }}
            onChange={() => onToggleKbs(allKbs, !checked)}
          />
          <span className={`truncate text-sm ${isGroup ? "font-medium text-slate-600" : "text-slate-700"}`}>
            {node.label}
          </span>
        </label>
      </div>
      {isGroup && open && (
        <ul className="space-y-0.5">
          {node.children.map((c) => (
            <KbCheckNode key={c.key} node={c} selected={selected} onToggleKbs={onToggleKbs} depth={depth + 1} />
          ))}
        </ul>
      )}
    </li>
  );
}