OrgTree.tsx 25.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { Check, ChevronDown, ChevronRight, Database } 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/project 库(无部门)单列在最前。 */
export function buildKbTree(kbs: KbInfo[]): { base: KbInfo[]; tree: KbTreeNode[] } {
  // base(基础库)与 project(项目库)都不挂在组织树上,作为扁平叶子排在最前
  const base = kbs.filter((k) => k.kbType !== "dept");
  const dept = kbs.filter((k) => k.kbType === "dept");
  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>
  );
}

// ============================================================
// 三、统一知识库树选择器 KbTreePicker:按钮 + 弹层 + 结构化树。
//     单选(可带「全部」)供图一顶部筛选 / 图三阅读页 / 上传目标;多选(带「全选」主控)供 Copilot。
//     base 库作为 depth=0 叶子节点与部门节点**同构渲染**(同样的 w-5 占位 + gap-1 行结构),
//     从根上消除「基础库旁挂缩进对不齐」的问题。
// ============================================================

/** 库的展示名:dept 用组织路径(无则退化库名),base/project 用库名。 */
export function kbLabel(k: KbInfo): string {
  return k.kbType === "dept" ? k.deptPath || k.kbName : k.kbName;
}

const ACCESS_TAG: Record<string, { label: string; cls: string }> = {
  owner: { label: "Owner", cls: "bg-blue-50 text-blue-600 ring-blue-200" },
  editor: { label: "Editor", cls: "bg-emerald-50 text-emerald-600 ring-emerald-200" },
  reader: { label: "Reader", cls: "bg-slate-100 text-slate-500 ring-slate-200" },
};

/** 权限标签:统一宽度、右对齐、细描边胶囊。 */
function AccessTag({ access }: { access?: string | null }) {
  const t = access ? ACCESS_TAG[access] : undefined;
  if (!t) return null;
  return (
    <span
      className={`ml-auto shrink-0 inline-flex w-[52px] items-center justify-center rounded-full py-[1px] text-[10px] font-semibold ring-1 ring-inset ${t.cls}`}
    >
      {t.label}
    </span>
  );
}

/** 库类型标签:基础库=淡蓝、项目库=紫、部门库=灰(跟在库名后,与权限标签并列右对齐)。 */
function TypeTag({ kbType }: { kbType?: string }) {
  if (!kbType) return null;
  const meta =
    kbType === "base"
      ? { label: "基础库", cls: "bg-sky-50 text-sky-600 ring-sky-200" }
      : kbType === "project"
        ? { label: "项目库", cls: "bg-violet-50 text-violet-600 ring-violet-200" }
        : { label: "部门库", cls: "bg-slate-100 text-slate-500 ring-slate-200" };
  return (
    <span
      className={`shrink-0 inline-flex w-[44px] items-center justify-center rounded-full py-[1px] text-[10px] font-medium ring-1 ring-inset ${meta.cls}`}
    >
      {meta.label}
    </span>
  );
}

/** 把 base 库并入树:base 作为 depth=0 叶子节点排在最前,与部门叶子同构。 */
function buildPickerNodes(kbs: KbInfo[]): KbTreeNode[] {
  const { base, tree } = buildKbTree(kbs);
  const baseNodes: KbTreeNode[] = base.map((k) => ({ key: k.id, label: k.kbName, kbId: k.id, children: [] }));
  return [...baseNodes, ...tree];
}

/** 组前缀:单选选中「中心/分组」节点时用 `grp:<key>` 作 token,与叶子的 kbId 区分开。 */
const GROUP_PREFIX = "grp:";

/** 扁平化:key → 节点,用于按 token 回查分组标签。 */
function flattenByKey(nodes: KbTreeNode[], out = new Map<string, KbTreeNode>()): Map<string, KbTreeNode> {
  for (const n of nodes) {
    out.set(n.key, n);
    if (n.children.length) flattenByKey(n.children, out);
  }
  return out;
}

interface KbTreePickerProps {
  kbs: KbInfo[];
  mode: "single" | "multi";
  /** 单选:当前选中 token("" =全部;叶子=kbId;分组=`grp:<key>`)。 */
  value?: string;
  /** 单选回调:token + 该选择覆盖的全部叶子库 id(叶子=1 个,分组=其子树全部库,全部=所有可选库)。 */
  onChange?: (token: string, kbIds: string[]) => void;
  allowAll?: boolean; // 单选时提供「全部知识库」项
  allLabel?: string;
  allowGroupSelect?: boolean; // 单选时允许选中「中心/分组」节点(选它=其下全部库)
  /** 多选:已选库 id 集合与回调。 */
  selected?: Set<string>;
  onChangeMulti?: (ids: Set<string>) => void;
  showAccessBadge?: boolean; // 叶子后缀显示 Owner/Editor/Reader 标记
  placeholder?: string;
  openUp?: boolean; // 弹层向上展开(如 Copilot 底部输入区)
  panelWidthClass?: string; // 弹层宽度(默认 w-[26rem])
  buttonClassName?: string; // 触发按钮样式(供工具栏/输入区各自定制)
  labelPrefix?: string; // 按钮摘要前缀(如「知识库:」)
}

/** 自包含的知识库树选择器(管理开合与外部点击关闭)。 */
export function KbTreePicker({
  kbs,
  mode,
  value = "",
  onChange,
  allowAll,
  allLabel = "全部知识库",
  allowGroupSelect,
  selected,
  onChangeMulti,
  showAccessBadge,
  placeholder = "选择知识库",
  openUp,
  panelWidthClass = "w-[26rem]",
  buttonClassName,
  labelPrefix,
}: KbTreePickerProps) {
  const [open, setOpen] = useState(false);
  const rootRef = useRef<HTMLDivElement>(null);
  const nodes = useMemo(() => buildPickerNodes(kbs), [kbs]);
  const kbById = useMemo(() => new Map(kbs.map((k) => [k.id, k])), [kbs]);
  const nodeByKey = useMemo(() => flattenByKey(nodes), [nodes]);
  const allKbIds = useMemo(() => nodes.flatMap((n) => collectKbIds(n)), [nodes]);

  // 外部点击关闭
  useEffect(() => {
    if (!open) return;
    const onDoc = (e: MouseEvent) => {
      if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [open]);

  const sel = selected ?? new Set<string>();
  const allSelected = mode === "multi" && allKbIds.length > 0 && allKbIds.every((id) => sel.has(id));
  const someSelected = mode === "multi" && allKbIds.some((id) => sel.has(id));

  const toggleMulti = (ids: string[], next: boolean) => {
    const n = new Set(sel);
    for (const id of ids) (next ? n.add(id) : n.delete(id));
    onChangeMulti?.(n);
  };

  // 触发按钮摘要
  let summary: string;
  if (mode === "multi") {
    summary = allSelected ? (allLabel ?? "全部") : someSelected ? `已选 ${sel.size} 个` : "未选";
  } else if (!value) {
    summary = allowAll ? allLabel : placeholder;
  } else if (value.startsWith(GROUP_PREFIX)) {
    const node = nodeByKey.get(value.slice(GROUP_PREFIX.length));
    summary = node ? node.label : placeholder;
  } else {
    const k = kbById.get(value);
    summary = k ? kbLabel(k) : placeholder;
  }

  return (
    <div className="relative" ref={rootRef}>
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className={
          buttonClassName ??
          "flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-2 h-8 text-xs font-semibold text-slate-600 outline-none transition hover:border-slate-300"
        }
        title="选择知识库"
      >
        <Database className="h-3.5 w-3.5 shrink-0 text-slate-400" />
        <span className="truncate max-w-[16rem]">{labelPrefix ? `${labelPrefix}${summary}` : summary}</span>
        <ChevronDown className="h-3.5 w-3.5 shrink-0" />
      </button>
      {open && (
        <div
          className={`absolute ${openUp ? "bottom-full mb-2" : "top-full mt-2"} left-0 z-30 max-h-80 ${panelWidthClass} overflow-auto rounded-xl border border-slate-200 bg-white p-2 shadow-xl`}
        >
          {mode === "multi" ? (
            <label className="mb-1 flex cursor-pointer items-center gap-2 rounded-md border-b border-slate-100 px-2 py-1.5">
              <input
                type="checkbox"
                className="h-3.5 w-3.5 accent-blue-600"
                checked={allSelected}
                ref={(el) => { if (el) el.indeterminate = someSelected && !allSelected; }}
                onChange={() => toggleMulti(allKbIds, !allSelected)}
              />
              <span className="text-[12px] font-semibold text-slate-600">全选(默认)</span>
              <span className="ml-auto text-[11px] text-slate-400">选中心=含其全部部门库</span>
            </label>
          ) : allowAll ? (
            <button
              type="button"
              onClick={() => { onChange?.("", allKbIds); setOpen(false); }}
              className="mb-1 flex w-full items-center gap-2 rounded-md border-b border-slate-100 px-2 py-1.5 text-left hover:bg-blue-50/60"
            >
              <span className="inline-flex h-4 w-4 items-center justify-center">{!value && <Check className="h-3.5 w-3.5 text-blue-600" />}</span>
              <span className="text-[12px] font-semibold text-slate-600">{allLabel}</span>
            </button>
          ) : null}

          {kbs.length === 0 ? (
            <div className="py-4 text-center text-xs text-slate-400">暂无可选知识库</div>
          ) : (
            <ul className="space-y-0.5 pt-1">
              {nodes.map((n) => (
                <KbPickerNode
                  key={n.key}
                  node={n}
                  depth={0}
                  mode={mode}
                  value={value}
                  allowGroupSelect={allowGroupSelect}
                  onPick={(token, kbIds) => { onChange?.(token, kbIds); setOpen(false); }}
                  selected={sel}
                  onToggleKbs={toggleMulti}
                  kbById={kbById}
                  showAccessBadge={showAccessBadge}
                />
              ))}
            </ul>
          )}
        </div>
      )}
    </div>
  );
}

function KbPickerNode({
  node,
  depth,
  mode,
  value,
  allowGroupSelect,
  onPick,
  selected,
  onToggleKbs,
  kbById,
  showAccessBadge,
}: {
  node: KbTreeNode;
  depth: number;
  mode: "single" | "multi";
  value: string;
  allowGroupSelect?: boolean;
  onPick: (token: string, kbIds: string[]) => void;
  selected: Set<string>;
  onToggleKbs: (ids: string[], next: boolean) => void;
  kbById: Map<string, KbInfo>;
  showAccessBadge?: boolean;
}) {
  const [open, setOpen] = useState(true);
  const isGroup = node.children.length > 0;
  const allKbs = collectKbIds(node);
  const kb = node.kbId ? kbById.get(node.kbId) : undefined;
  const groupToken = GROUP_PREFIX + node.key;

  // 多选态(含中心三态)
  const selCount = allKbs.filter((id) => selected.has(id)).length;
  const checked = allKbs.length > 0 && selCount === allKbs.length;
  const indeterminate = selCount > 0 && selCount < allKbs.length;
  // 单选:叶子=可选库;分组(allowGroupSelect 时)=其下全部库
  const leafPicked = mode === "single" && !!node.kbId && node.kbId === value;
  const groupPicked = mode === "single" && isGroup && !!allowGroupSelect && value === groupToken;

  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 shrink-0 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 shrink-0" />
        )}

        {mode === "multi" ? (
          <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 shrink-0 accent-blue-600"
              checked={checked}
              ref={(el) => { if (el) el.indeterminate = indeterminate; }}
              onChange={() => onToggleKbs(allKbs, !checked)}
            />
            <span className={`min-w-0 flex-1 truncate text-sm ${isGroup ? "font-medium text-slate-600" : "text-slate-700"}`}>
              {node.label}
            </span>
            {!isGroup && <TypeTag kbType={kb?.kbType} />}
            {showAccessBadge && !isGroup && <AccessTag access={kb?.access} />}
          </label>
        ) : node.kbId ? (
          <button
            type="button"
            onClick={() => onPick(node.kbId!, [node.kbId!])}
            className={`flex flex-1 items-center gap-2 rounded px-1.5 py-1 text-left hover:bg-blue-50/60 ${leafPicked ? "bg-blue-50" : ""}`}
          >
            <span className="inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center">{leafPicked && <Check className="h-3.5 w-3.5 text-blue-600" />}</span>
            <span className={`min-w-0 flex-1 truncate text-sm ${leafPicked ? "font-medium text-blue-700" : "text-slate-700"}`}>{node.label}</span>
            <TypeTag kbType={kb?.kbType} />
            {showAccessBadge && <AccessTag access={kb?.access} />}
          </button>
        ) : allowGroupSelect ? (
          // 单选 + 允许选分组:点击标签=选中该中心下全部库(chevron 仍单独控制展开)
          <button
            type="button"
            onClick={() => onPick(groupToken, allKbs)}
            className={`flex flex-1 items-center gap-2 rounded px-1.5 py-1 text-left hover:bg-blue-50/60 ${groupPicked ? "bg-blue-50" : ""}`}
          >
            <span className="inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center">{groupPicked && <Check className="h-3.5 w-3.5 text-blue-600" />}</span>
            <span className={`min-w-0 flex-1 truncate text-sm ${groupPicked ? "font-medium text-blue-700" : "font-medium text-slate-600"}`}>{node.label}</span>
            <span className="shrink-0 text-[10px] text-slate-400">{allKbs.length} 库</span>
          </button>
        ) : (
          // 单选、不允许选分组:中心仅作层级表头(点击展开/收起)
          <button
            type="button"
            onClick={() => setOpen((o) => !o)}
            className="flex flex-1 items-center gap-2 rounded px-1.5 py-1 text-left"
          >
            <span className="inline-block h-3.5 w-3.5 shrink-0" />
            <span className="min-w-0 flex-1 truncate text-sm font-medium text-slate-500">{node.label}</span>
          </button>
        )}
      </div>
      {isGroup && open && (
        <ul className="space-y-0.5">
          {node.children.map((c) => (
            <KbPickerNode
              key={c.key}
              node={c}
              depth={depth + 1}
              mode={mode}
              value={value}
              allowGroupSelect={allowGroupSelect}
              onPick={onPick}
              selected={selected}
              onToggleKbs={onToggleKbs}
              kbById={kbById}
              showAccessBadge={showAccessBadge}
            />
          ))}
        </ul>
      )}
    </li>
  );
}

// ============================================================
// 四、部门叶子单选 DeptLeafSelect:Owner 绑定用。
//     中心/架构(含下属部门)不可选、仅可展开;叶子部门单选。
// ============================================================

export function DeptLeafSelect({
  nodes,
  value,
  onChange,
  disabledIds,
}: {
  nodes: OaDept[];
  value: string | null;
  onChange: (id: string) => void;
  disabledIds?: Set<string>; // 额外禁选(如已被其它库占用的叶子)
}) {
  return (
    <ul className="space-y-0.5">
      {nodes.map((n) => (
        <DeptLeafNode key={n.id} node={n} value={value} onChange={onChange} disabledIds={disabledIds} depth={0} />
      ))}
    </ul>
  );
}

function DeptLeafNode({
  node,
  value,
  onChange,
  disabledIds,
  depth,
}: {
  node: OaDept;
  value: string | null;
  onChange: (id: string) => void;
  disabledIds?: Set<string>;
  depth: number;
}) {
  const [open, setOpen] = useState(depth < 1);
  const kids = node.children ?? [];
  const isLeaf = kids.length === 0;
  const picked = isLeaf && node.id === value;
  const blocked = disabledIds?.has(node.id) ?? false;

  return (
    <li>
      <div className="flex items-center gap-1" style={{ paddingLeft: depth * 16 }}>
        {!isLeaf ? (
          <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" />
        )}
        {isLeaf ? (
          <button
            type="button"
            disabled={blocked}
            onClick={() => onChange(node.id)}
            className={`flex flex-1 items-center gap-2 rounded px-1.5 py-1 text-left ${
              blocked ? "cursor-not-allowed opacity-50" : "hover:bg-blue-50/60"
            } ${picked ? "bg-blue-50" : ""}`}
          >
            <span className="inline-flex h-3.5 w-3.5 items-center justify-center">{picked && <Check className="h-3.5 w-3.5 text-blue-600" />}</span>
            <span className={`truncate text-sm ${picked ? "font-medium text-blue-700" : "text-slate-700"}`}>{node.deptName}</span>
            {blocked && <span className="shrink-0 rounded bg-slate-100 px-1 text-[10px] text-slate-400">已占用</span>}
          </button>
        ) : (
          <button
            type="button"
            onClick={() => setOpen((o) => !o)}
            className="flex flex-1 items-center gap-2 rounded px-1.5 py-1 text-left"
          >
            <span className="inline-block h-3.5 w-3.5" />
            <span className="truncate text-sm font-medium text-slate-500">{node.deptName}</span>
          </button>
        )}
      </div>
      {!isLeaf && open && (
        <ul className="space-y-0.5">
          {kids.map((c) => (
            <DeptLeafNode key={c.id} node={c} value={value} onChange={onChange} disabledIds={disabledIds} depth={depth + 1} />
          ))}
        </ul>
      )}
    </li>
  );
}