page.tsx 35.3 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 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
"use client";

import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
import { Check, Database, Pencil, Plus, Shield, Trash2, X } from "lucide-react";

import {
  Card,
  Drawer,
  Field,
  FormRow,
  GhostButton,
  Input,
  Modal,
  Pagination,
  PrimaryButton,
  SearchInput,
  Select,
  SortHeader,
  type SortState,
  Spinner,
  StatusBadge,
  SysPage,
  Toolbar,
} from "@/components/system/kit";
import Perm from "@/components/Perm";
import { DeptCheckTree, DeptLeafSelect } from "@/components/system/OrgTree";
import {
  createKb,
  grantKb,
  listKbs,
  listKbGrants,
  listKbOrgTree,
  provisionDeptKbs,
  removeKb,
  revokeKb,
  updateKb,
  type KbGrant,
  type KbInfo,
  type OaDept,
} from "@/lib/auth";
import { KbType, KbTypeLabel } from "@/lib/oaEnums";
import { cn } from "@/lib/utils";

/**
 * 表单区块:标签 + 可选说明 + 控件。
 *
 * 与 kit 的 FormRow 采用完全相同的标签排版与间距,但外层是 div 而非 label——
 * 类型卡片、部门勾选树这类含交互子元素的控件不能塞进 label(点说明文字会误触发选中)。
 * 有了它,弹窗/抽屉里每个字段的标签位置与行距才真正对齐,不再像拼接的。
 */
function FieldBlock({
  label,
  hint,
  children,
}: {
  label: string;
  hint?: string;
  children: ReactNode;
}) {
  return (
    <div className="space-y-1">
      <div className="text-xs font-medium text-slate-500">{label}</div>
      {hint && <p className="text-[11px] leading-relaxed text-slate-400">{hint}</p>}
      {children}
    </div>
  );
}

/** 类型标签配色(与下拉里的 TypeTag 一致):基础库=淡蓝、部门库=灰、项目库=紫。 */
const kbTypeTagCls = (kbType: string) =>
  kbType === KbType.BASE
    ? "bg-sky-50 text-sky-600 ring-sky-200"
    : kbType === KbType.PROJECT
      ? "bg-violet-50 text-violet-600 ring-violet-200"
      : "bg-slate-100 text-slate-500 ring-slate-200";

const KB_TYPE_OPTIONS = [
  { value: KbType.DEPT, label: "部门库", desc: "绑定唯一 Owner 部门(叶子),本部门成员可维护,落 ware/kb/dept/<库id>/" },
  { value: KbType.BASE, label: "基础库", desc: "面向全员的基础知识(默认全员只读),可按需授权 Editor(写)/Reader(读),落 ware/kb/base/<库id>/" },
  { value: KbType.PROJECT, label: "项目库", desc: "创建者为 Owner,按人授 Editor(写)/Reader(读) 协作(类 git),落 ware/kb/project/<库id>/" },
] as const;

/**
 * 知识库类型选择:等宽双卡片单选。
 *
 * 用整行两张等宽卡片(而非行内小胶囊/原生下拉),是为了与同一表单里 Input 的整行宽度对齐,
 * 避免控件宽窄不一显得拼凑;同时每个选项自带一句说明,管理员不必猜两种类型的差别。
 */
function KbTypePicker({
  value,
  onChange,
  disabled,
}: {
  value: string;
  onChange: (v: string) => void;
  disabled?: boolean;
}) {
  return (
    <div className="grid grid-cols-3 gap-2.5">
      {KB_TYPE_OPTIONS.map((opt) => {
        const active = value === opt.value;
        return (
          <button
            key={opt.value}
            type="button"
            disabled={disabled}
            onClick={() => onChange(opt.value)}
            className={cn(
              "rounded-lg border px-3.5 py-3 text-left transition",
              active
                ? "border-blue-500 bg-blue-50/60 ring-2 ring-blue-500/20"
                : "border-slate-200 bg-white hover:border-slate-300 hover:bg-slate-50",
              disabled && "cursor-not-allowed opacity-60 hover:border-slate-200 hover:bg-white"
            )}
          >
            <div className="flex items-center gap-2">
              <span
                className={cn(
                  "flex h-4 w-4 shrink-0 items-center justify-center rounded-full border transition",
                  active ? "border-blue-600 bg-blue-600" : "border-slate-300 bg-white"
                )}
              >
                {active && <Check className="h-2.5 w-2.5 text-white" strokeWidth={3.5} />}
              </span>
              <span className={cn("text-sm font-medium", active ? "text-blue-700" : "text-slate-700")}>
                {opt.label}
              </span>
            </div>
            <p className="mt-1.5 pl-6 text-[11px] leading-relaxed text-slate-400">{opt.desc}</p>
          </button>
        );
      })}
    </div>
  );
}

export default function KbPage() {
  const [items, setItems] = useState<KbInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [kbType, setKbType] = useState("");
  const [kwInput, setKwInput] = useState("");
  const [keyword, setKeyword] = useState("");
  // 默认按名称排序
  const [sort, setSort] = useState<SortState>({ by: "kbName", order: "asc" });

  const [deptTree, setDeptTree] = useState<OaDept[]>([]);

  const [creating, setCreating] = useState(false);
  const [provisioning, setProvisioning] = useState(false);
  const [grantKbTarget, setGrantKbTarget] = useState<KbInfo | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      // 库数量小,一次取全,排序/分页在前端做
      const d = await listKbs({ keyword, kbType, limit: 500, offset: 0 });
      setItems(d.items);
    } finally {
      setLoading(false);
    }
  }, [keyword, kbType]);
  useEffect(() => { load(); }, [load]);

  useEffect(() => {
    listKbOrgTree().then((d) => setDeptTree(d.items)).catch(() => {});
  }, []);

  const viewItems = useMemo(() => {
    const arr = [...items];
    const dir = sort.order === "desc" ? -1 : 1;
    // 内置公共库恒排最前,其余按名称(公共库现可有多个,故按 isBuiltin 而非 kbType 置顶)
    arr.sort((a, b) => {
      const ka = a.isBuiltin ? "" : (a.kbName || "");
      const kb = b.isBuiltin ? "" : (b.kbName || "");
      return ka.localeCompare(kb, "zh") * dir;
    });
    return arr;
  }, [items, sort]);

  const pagedItems = useMemo(
    () => viewItems.slice((page - 1) * pageSize, page * pageSize),
    [viewItems, page, pageSize]
  );

  // 已被部门库占用的叶子部门 id(1:1)——供 Owner 绑定选择器禁选已占用项
  const occupiedDeptIds = useMemo(
    () => new Set(items.filter((k) => k.deptId).map((k) => k.deptId as string)),
    [items]
  );

  const apply = () => { setKeyword(kwInput.trim()); setPage(1); };

  const onToggleStatus = async (kb: KbInfo) => {
    const next = kb.status === "active" ? "disabled" : "active";
    try {
      await updateKb(kb.id, { status: next });
      await load();
    } catch (e) {
      alert((e as Error).message);
    }
  };

  const onRemove = async (kb: KbInfo) => {
    if (!confirm(`确认删除知识库「${kb.kbName}」?删除后不可恢复(库内若有文件将被拦截)。`)) return;
    try {
      await removeKb(kb.id);
      setGrantKbTarget(null);
      await load();
    } catch (e) {
      alert((e as Error).message);
    }
  };

  const onProvisionDept = async () => {
    if (!confirm("将为每个「尚未建库」的叶子部门各自新建一个部门库(已有库的部门自动跳过),确认执行?")) return;
    setProvisioning(true);
    try {
      const r = await provisionDeptKbs();
      alert(`完成:新建 ${r.created.length} 个部门库,跳过 ${r.skipped.length} 个(已有库)。`);
      await load();
    } catch (e) {
      alert((e as Error).message);
    } finally {
      setProvisioning(false);
    }
  };

  return (
    <SysPage
      title="知识库配置"
      subtitle="部门库绑定唯一 Owner 部门(叶子、可读写);再按需授权 Editor(写)/ Reader(只读)给部门 / 中心。"
      actions={
        <>
          <Perm code="kb:create">
            <GhostButton onClick={onProvisionDept} disabled={provisioning}>
              <Database className="h-4 w-4" /> {provisioning ? "创建中…" : "一键新建部门库"}
            </GhostButton>
          </Perm>
          <Perm code="kb:create">
            <PrimaryButton onClick={() => setCreating(true)}>
              <Plus className="h-4 w-4" /> 新建知识库
            </PrimaryButton>
          </Perm>
        </>
      }
    >
      <Toolbar>
        <SearchInput value={kwInput} onChange={setKwInput} onEnter={apply} placeholder="知识库名称" className="w-56" />
        <Select value={kbType} onChange={(v) => (setKbType(v), setPage(1))}>
          <option value="">全部类型</option>
          {Object.entries(KbTypeLabel).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
        </Select>
        {(keyword || kbType) && (
          <GhostButton onClick={() => (setKwInput(""), setKeyword(""), setKbType(""), setPage(1))}>
            <X className="h-4 w-4" /> 重置
          </GhostButton>
        )}
      </Toolbar>

      <Card>
        <div className="min-h-0 flex-1 overflow-auto">
          <table className="w-full table-fixed text-sm">
            <colgroup>
              <col className="w-56" /><col className="w-20" /><col className="w-16" /><col className="w-56" /><col className="w-56" /><col className="w-32" />
            </colgroup>
            <thead className="sticky top-0 z-10 bg-blue-50/95 text-left backdrop-blur">
              <tr className="border-b border-blue-100 text-slate-500">
                <SortHeader label="名称" field="kbName" sort={sort} onSort={(s) => (setSort(s), setPage(1))} />
                <th className="px-4 py-2.5 font-semibold">类型</th>
                <th className="px-4 py-2.5 font-semibold">状态</th>
                <th className="px-4 py-2.5 font-semibold">绑定部门(Owner)</th>
                <th className="px-4 py-2.5 font-semibold">已授权 Editor/Reader</th>
                <th className="px-4 py-2.5 font-semibold">创建时间</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={6}><Spinner /></td></tr>
              ) : viewItems.length === 0 ? (
                <tr><td colSpan={6} className="py-16 text-center text-slate-400">暂无知识库,点击「新建知识库」创建</td></tr>
              ) : (
                pagedItems.map((kb) => (
                  <tr
                    key={kb.id}
                    onClick={() => setGrantKbTarget(kb)}
                    className="cursor-pointer border-b border-slate-50 transition hover:bg-blue-50/50"
                    title="点击进入授权管理"
                  >
                    <td className="truncate px-4 py-2.5 font-medium text-slate-700" title={kb.kbName}>
                      <Database className="mr-1 inline h-3.5 w-3.5 text-blue-400" />{kb.kbName}
                    </td>
                    <td className="px-4 py-2.5">
                      <span className={cn("inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ring-1 ring-inset", kbTypeTagCls(kb.kbType))}>{KbTypeLabel[kb.kbType] ?? kb.kbType}</span>
                    </td>
                    <td className="px-4 py-2.5"><StatusBadge status={kb.status} /></td>
                    <td className="truncate px-4 py-2.5 text-slate-500" title={kb.deptPath || ""}>
                      {kb.kbType === "base" ? <span className="text-slate-300">—</span> : kb.deptPath || <span className="text-amber-500">未绑定</span>}
                    </td>
                    <td className="truncate px-4 py-2.5 text-slate-500" title={(kb.grantedLabels || []).join("、")}>
                      {kb.grantedLabels && kb.grantedLabels.length > 0 ? kb.grantedLabels.join("、") : "—"}
                    </td>
                    <td className="truncate px-4 py-2.5 text-slate-400">{kb.createdAt ? kb.createdAt.slice(0, 19).replace("T", " ") : "—"}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
        <Pagination page={page} pageSize={pageSize} total={viewItems.length} onPage={setPage} onPageSize={(s) => (setPageSize(s), setPage(1))} />
      </Card>

      {creating && (
        <CreateKbModal deptTree={deptTree} occupiedDeptIds={occupiedDeptIds} onClose={() => setCreating(false)} onDone={() => { setCreating(false); load(); }} />
      )}
      {grantKbTarget && (
        <GrantDrawer
          // key 必须带:抽屉内的名称/类型是用 useState(kb.xxx) 初始化的,而 React 对同位置的
          // 同类型元素只会复用实例、不重跑初始值。换一个库时若不换 key,抽屉会残留上一个库的
          // 名称与类型。
          key={grantKbTarget.id}
          kb={grantKbTarget}
          deptTree={deptTree}
          occupiedDeptIds={occupiedDeptIds}
          onClose={() => setGrantKbTarget(null)}
          onToggleStatus={async (kb) => { await onToggleStatus(kb); setGrantKbTarget(null); }}
          onRemove={onRemove}
          onSaved={load}
        />
      )}
    </SysPage>
  );
}

function CreateKbModal({
  deptTree,
  occupiedDeptIds,
  onClose,
  onDone,
}: {
  deptTree: OaDept[];
  occupiedDeptIds: Set<string>;
  onClose: () => void;
  onDone: () => void;
}) {
  const [name, setName] = useState("");
  const [kbType, setKbType] = useState("dept");
  const [ownerDept, setOwnerDept] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);

  const submit = async () => {
    if (!name.trim()) { alert("请输入知识库名称"); return; }
    if (kbType === "dept" && !ownerDept) { alert("部门库必须绑定一个 Owner 部门(叶子节点)"); return; }
    setSaving(true);
    try {
      await createKb(name.trim(), kbType, kbType === "dept" ? ownerDept ?? undefined : undefined);
      onDone();
    } catch (e) {
      alert((e as Error).message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal title="新建知识库" onClose={onClose} size="2xl">
      <div className="space-y-5">
        <FormRow label="知识库名称">
          <Input value={name} onChange={setName} placeholder="如:产品部知识库" />
        </FormRow>
        <FieldBlock label="知识库类型">
          <KbTypePicker value={kbType} onChange={(v) => { setKbType(v); if (v !== "dept") setOwnerDept(null); }} />
        </FieldBlock>
        {kbType === "dept" && (
          <FieldBlock
            label="Owner 绑定部门(必选,仅叶子部门)"
            hint="Owner = 该部门为知识库的唯一归属(可读写:上传/摄入/摄出/删除,按角色),一个部门只能绑定一个库。中心/架构不可选。Editor(写)/ Reader(只读)授权请在创建后进入详情配置。"
          >
            <div className="max-h-64 overflow-auto rounded-lg border border-slate-200 p-2">
              {deptTree.length === 0 ? (
                <div className="py-6 text-center text-xs text-slate-400">加载中…</div>
              ) : (
                <DeptLeafSelect
                  nodes={deptTree}
                  value={ownerDept}
                  onChange={setOwnerDept}
                  disabledIds={occupiedDeptIds}
                />
              )}
            </div>
          </FieldBlock>
        )}
        <div className="flex justify-end gap-2 border-t border-slate-100 pt-4">
          <GhostButton onClick={onClose}>取消</GhostButton>
          <PrimaryButton onClick={submit} disabled={saving}>{saving ? "创建中…" : "创建"}</PrimaryButton>
        </div>
      </div>
    </Modal>
  );
}

/** 从嵌套部门树构建「id → 祖先 id 列表」映射(根在前,不含自身),用于判断继承。 */
function buildAncestorMap(nodes: OaDept[], trail: string[] = [], out = new Map<string, string[]>()) {
  for (const n of nodes) {
    out.set(n.id, trail);
    if (n.children?.length) buildAncestorMap(n.children, [...trail, n.id], out);
  }
  return out;
}

/** 从嵌套部门树构建「id → 全部后代 id 列表」映射(不含自身),用于计算中心节点的半选态。 */
function buildDescendantMap(nodes: OaDept[], out = new Map<string, string[]>()) {
  const walk = (n: OaDept): string[] => {
    const all: string[] = [];
    for (const c of n.children ?? []) {
      all.push(c.id, ...walk(c));
    }
    out.set(n.id, all);
    return all;
  };
  for (const n of nodes) walk(n);
  return out;
}

/**
 * 由本地暂存的显式勾选集推导整棵树的展示态(纯函数,供 Owner / Guest 两棵树各调一次)。
 * - selected:显式 ∪ 继承(某祖先被显式授权 → 后端「授节点=授整棵子树」)
 * - disabledIds:仅继承而非显式(禁止取消,需到该祖先节点取消)
 * - partialIds:自身未选但下属部分被选(折叠时也能看出中心与部门的勾选关系)
 */
function computeTreeState(
  pending: Set<string>,
  ancestorMap: Map<string, string[]>,
  descendantMap: Map<string, string[]>,
) {
  const selected = new Set<string>(pending);
  const disabledIds = new Set<string>();
  for (const id of ancestorMap.keys()) {
    if (pending.has(id)) continue;
    if ((ancestorMap.get(id) ?? []).some((a) => pending.has(a))) {
      selected.add(id);
      disabledIds.add(id);
    }
  }
  const partialIds = new Set<string>();
  for (const [id, descs] of descendantMap) {
    if (!selected.has(id) && descs.some((d) => selected.has(d))) partialIds.add(id);
  }
  return { selected, disabledIds, partialIds };
}

function GrantDrawer({
  kb,
  deptTree,
  occupiedDeptIds,
  onClose,
  onToggleStatus,
  onRemove,
  onSaved,
}: {
  kb: KbInfo;
  deptTree: OaDept[];
  occupiedDeptIds: Set<string>;
  onClose: () => void;
  onToggleStatus: (kb: KbInfo) => void | Promise<void>;
  onRemove: (kb: KbInfo) => void | Promise<void>;
  onSaved: () => void;
}) {
  const [grants, setGrants] = useState<KbGrant[]>([]);
  const [loadedOnce, setLoadedOnce] = useState(false); // 树只在首次加载时切换 spinner,之后保存触发的刷新不再卸载重挂,展开态不丢
  const [saving, setSaving] = useState(false);

  // 点击列表行进来默认是「预览」;名称/绑定部门/授权均只读,点「编辑」才能改。
  // 类型创建后一律不可修改(决定物理目录 ware/kb/base|dept 与权限语义)。
  const [isEditing, setIsEditing] = useState(false);
  const [currentName, setCurrentName] = useState(kb.kbName);
  const [currentType, setCurrentType] = useState(kb.kbType);
  const [currentDept, setCurrentDept] = useState<string | null>(kb.deptId);
  const [editName, setEditName] = useState(kb.kbName);
  const [editType, setEditType] = useState(kb.kbType);
  const [editDept, setEditDept] = useState<string | null>(kb.deptId);
  // 注:上面几个 useState 只在挂载时取一次 kb 的值,靠 KbPage 传入的 key={kb.id} 保证
  // 换库时整个抽屉重新挂载来同步,不需要(也不该)再写 effect 回写 state。

  const isDept = currentType === "dept";
  const deptName = useMemo(() => {
    const idx = new Map<string, string>();
    const walk = (ns: OaDept[]) => ns.forEach((n) => { idx.set(n.id, n.deptName); walk(n.children ?? []); });
    walk(deptTree);
    return (id: string | null) => (id ? idx.get(id) ?? id : null);
  }, [deptTree]);
  // 编辑 Owner 时排除本库当前占用的部门(1:1,其余库占用的仍禁选)
  const occupiedForEdit = useMemo(
    () => new Set([...occupiedDeptIds].filter((id) => id !== currentDept)),
    [occupiedDeptIds, currentDept]
  );

  const reload = useCallback(async () => {
    try {
      const d = await listKbGrants(kb.id);
      setGrants(d.items);
    } finally {
      setLoadedOnce(true);
    }
  }, [kb.id]);
  useEffect(() => { reload(); }, [reload]);

  const ancestorMap = useMemo(() => buildAncestorMap(deptTree), [deptTree]);
  const descendantMap = useMemo(() => buildDescendantMap(deptTree), [deptTree]);

  // 整棵组织树都可勾选 Editor/Reader 授权
  const visibleTree = deptTree;

  // 服务端已确认的显式授权节点集合(按 editor / reader 分列)+ 其撤销所需的 grantId
  const explicitEditor = useMemo(
    () => new Set(grants.filter((g) => g.granteeType === "dept" && g.access === "editor").map((g) => g.granteeId)),
    [grants]
  );
  const explicitReader = useMemo(
    () => new Set(grants.filter((g) => g.granteeType === "dept" && g.access === "reader").map((g) => g.granteeId)),
    [grants]
  );
  const grantIdBy = useMemo(() => {
    const m = new Map<string, string>();  // key = `${access}:${granteeId}`
    grants.filter((g) => g.granteeType === "dept").forEach((g) => m.set(`${g.access}:${g.granteeId}`, g.id));
    return m;
  }, [grants]);

  // 预览态列表:Owner 部门(currentDept)恒有读写,不在 Editor/Reader 里重复展示
  const previewEditor = useMemo(
    () => grants.filter((g) => g.access === "editor" && g.granteeId !== currentDept),
    [grants, currentDept]
  );
  const previewReader = useMemo(
    () => grants.filter((g) => g.access === "reader" && g.granteeId !== currentDept),
    [grants, currentDept]
  );

  // 本地暂存的勾选态:仅在点击“保存”时才提交后端,避免每次勾选都刷新导致树折叠、体验割裂
  const [pendingEditor, setPendingEditor] = useState<Set<string>>(new Set());
  const [pendingReader, setPendingReader] = useState<Set<string>>(new Set());
  useEffect(() => { setPendingEditor(new Set(explicitEditor)); }, [explicitEditor]);
  useEffect(() => { setPendingReader(new Set(explicitReader)); }, [explicitReader]);

  // Owner 部门(当前编辑绑定)恒有读写、是最高权限,从 Editor/Reader 授权中排除:
  // 既不可勾选(树里禁用并打 Owner 标记),也不进入待提交差异(若有历史授权则在保存时撤销)。
  const ownerExclude = useMemo(() => new Set(editDept ? [editDept] : []), [editDept]);
  const pendingEditorEff = useMemo(() => {
    const s = new Set(pendingEditor); if (editDept) s.delete(editDept); return s;
  }, [pendingEditor, editDept]);
  const pendingReaderEff = useMemo(() => {
    const s = new Set(pendingReader); if (editDept) s.delete(editDept); return s;
  }, [pendingReader, editDept]);
  // 服务端授权同样排除 Owner 部门后再与本地暂存态比对:Owner 恒有读写(由 dept_id 承载),
  // 若历史数据里 Owner 部门自身还残留一条 editor/reader 授权,它既不在可勾选集里、也已从
  // pendingEff 中剔除;若不同步从 explicit 剔除,就会被算成「一条待撤销」,导致点开预览(未做
  // 任何编辑)也判定为 dirty、关闭时误弹「有未保存的改动」。此处对齐两侧口径,消除幽灵差异。
  const explicitEditorEff = useMemo(() => {
    const s = new Set(explicitEditor); if (editDept) s.delete(editDept); return s;
  }, [explicitEditor, editDept]);
  const explicitReaderEff = useMemo(() => {
    const s = new Set(explicitReader); if (editDept) s.delete(editDept); return s;
  }, [explicitReader, editDept]);

  const editorState = useMemo(
    () => computeTreeState(pendingEditorEff, ancestorMap, descendantMap),
    [pendingEditorEff, ancestorMap, descendantMap]
  );
  const readerState = useMemo(
    () => computeTreeState(pendingReaderEff, ancestorMap, descendantMap),
    [pendingReaderEff, ancestorMap, descendantMap]
  );
  // 树的禁用集 = 继承锁定 ∪ Owner 部门
  const editorDisabled = useMemo(() => new Set([...editorState.disabledIds, ...ownerExclude]), [editorState, ownerExclude]);
  const readerDisabled = useMemo(() => new Set([...readerState.disabledIds, ...ownerExclude]), [readerState, ownerExclude]);

  const editorBadge = useCallback((id: string): string | undefined => {
    if (ownerExclude.has(id)) return "Owner";
    if (pendingEditorEff.has(id)) return "已授权";
    if (editorState.disabledIds.has(id)) return "继承自上级";
    return undefined;
  }, [ownerExclude, pendingEditorEff, editorState]);
  const readerBadge = useCallback((id: string): string | undefined => {
    if (ownerExclude.has(id)) return "Owner";
    if (pendingReaderEff.has(id)) return "已授权";
    if (readerState.disabledIds.has(id)) return "继承自上级";
    return undefined;
  }, [ownerExclude, pendingReaderEff, readerState]);

  const onToggleEditor = (id: string) => setPendingEditor((prev) => {
    const next = new Set(prev); next.has(id) ? next.delete(id) : next.add(id); return next;
  });
  const onToggleReader = (id: string) => setPendingReader((prev) => {
    const next = new Set(prev); next.has(id) ? next.delete(id) : next.add(id); return next;
  });

  const toAddEditor = useMemo(() => [...pendingEditorEff].filter((id) => !explicitEditorEff.has(id)), [pendingEditorEff, explicitEditorEff]);
  const toRemoveEditor = useMemo(() => [...explicitEditorEff].filter((id) => !pendingEditorEff.has(id)), [explicitEditorEff, pendingEditorEff]);
  const toAddReader = useMemo(() => [...pendingReaderEff].filter((id) => !explicitReaderEff.has(id)), [pendingReaderEff, explicitReaderEff]);
  const toRemoveReader = useMemo(() => [...explicitReaderEff].filter((id) => !pendingReaderEff.has(id)), [explicitReaderEff, pendingReaderEff]);
  const nameDirty = editName.trim() !== currentName;
  const deptDirty = isDept && editDept !== currentDept;
  const infoDirty = nameDirty || deptDirty;
  const grantDirtyCount = toAddEditor.length + toRemoveEditor.length + toAddReader.length + toRemoveReader.length;
  const dirty = grantDirtyCount > 0 || infoDirty;
  const pendingCount = grantDirtyCount + (nameDirty ? 1 : 0) + (deptDirty ? 1 : 0);

  // 内置公共库是系统兜底库(承载 kb_id 为空的历史文件、默认上传目标),类型/停用/删除均锁死
  const isBuiltin = kb.isBuiltin === true;

  const startEdit = () => {
    setEditName(currentName);
    setEditType(currentType);
    setEditDept(currentDept);
    setIsEditing(true);
  };

  const onSave = async () => {
    if (saving || !dirty) return;
    if (!editName.trim()) { alert("知识库名称不能为空"); return; }
    if (isDept && !editDept) { alert("部门库必须绑定一个 Owner 部门"); return; }
    setSaving(true);
    try {
      if (nameDirty || deptDirty) {
        await updateKb(kb.id, {
          ...(nameDirty ? { kbName: editName.trim() } : {}),
          ...(deptDirty ? { deptId: editDept ?? undefined } : {}),
        });
      }
      if (toAddEditor.length) await grantKb(kb.id, { granteeIds: toAddEditor, access: "editor" });
      if (toAddReader.length) await grantKb(kb.id, { granteeIds: toAddReader, access: "reader" });
      for (const id of toRemoveEditor) {
        const gid = grantIdBy.get(`editor:${id}`);
        if (gid) await revokeKb(kb.id, gid);
      }
      for (const id of toRemoveReader) {
        const gid = grantIdBy.get(`reader:${id}`);
        if (gid) await revokeKb(kb.id, gid);
      }
      setCurrentName(editName.trim());
      setCurrentType(editType);
      setCurrentDept(editDept);
      setIsEditing(false);
      await reload();
      onSaved();
    } catch (e) {
      alert((e as Error).message);
    } finally {
      setSaving(false);
    }
  };

  const onCancelEdits = () => {
    setPendingEditor(new Set(explicitEditor));
    setPendingReader(new Set(explicitReader));
    setEditName(currentName);
    setEditType(currentType);
    setEditDept(currentDept);
    setIsEditing(false);
  };

  const handleClose = () => {
    if (dirty && !confirm("有未保存的改动,确认放弃吗?")) return;
    onClose();
  };

  return (
    <Drawer
      open
      onClose={handleClose}
      title={<><Shield className="mr-1 inline h-4 w-4 text-blue-500" />{currentName} · 知识库详情</>}
      subtitle={
        isEditing
          ? `编辑名称 / 绑定部门 / Editor·Reader 授权${dirty ? `(${pendingCount} 项待保存)` : ""}`
          : "预览详情;点击「编辑」后可修改名称、绑定部门与授权"
      }
      footer={
        isEditing ? (
          <>
            <GhostButton onClick={onCancelEdits} disabled={saving}>取消</GhostButton>
            <PrimaryButton onClick={onSave} disabled={!dirty || saving}>
              {saving ? "保存中…" : "保存"}
            </PrimaryButton>
          </>
        ) : (
          <>
            {isBuiltin ? (
              <span className="mr-auto self-center text-xs text-slate-400">内置基础库不可停用 / 删除</span>
            ) : (
              <>
                <Perm code="kb:create">
                  <button
                    onClick={() => onToggleStatus(kb)}
                    className={
                      kb.status === "active"
                        ? "rounded-lg border border-amber-300 bg-amber-50 px-3 py-1.5 text-sm font-medium text-amber-700 transition hover:bg-amber-100"
                        : "rounded-lg border border-emerald-300 bg-emerald-50 px-3 py-1.5 text-sm font-medium text-emerald-700 transition hover:bg-emerald-100"
                    }
                  >
                    {kb.status === "active" ? "停用该知识库" : "启用该知识库"}
                  </button>
                </Perm>
                <Perm code="kb:remove">
                  <button
                    onClick={() => onRemove(kb)}
                    className="inline-flex items-center gap-1 rounded-lg border border-rose-300 bg-rose-50 px-3 py-1.5 text-sm font-medium text-rose-600 transition hover:bg-rose-100"
                  >
                    <Trash2 className="h-3.5 w-3.5" /> 删除知识库
                  </button>
                </Perm>
              </>
            )}
            <Perm code="kb:create">
              <PrimaryButton onClick={startEdit}>
                <Pencil className="h-4 w-4" /> 编辑
              </PrimaryButton>
            </Perm>
          </>
        )
      }
    >
      {/* 预览态统一走 Field(标签左、值右的详情列表);编辑态统一走 FormRow / FieldBlock
          (标签在上、控件占满整行)。两套排版各自内部对齐,不再混用导致字段忽左忽上。 */}
      {isEditing ? (
        <div className={cn("space-y-5", saving && "pointer-events-none opacity-60")}>
          <FormRow label="知识库名称">
            <Input value={editName} onChange={setEditName} placeholder="如:产品部知识库" />
          </FormRow>
          <FieldBlock
            label="知识库类型"
            hint="知识库类型创建后不可修改(类型决定物理目录与权限语义)。"
          >
            <KbTypePicker value={editType} onChange={setEditType} disabled />
          </FieldBlock>
          {isDept && (
            <FieldBlock
              label="绑定部门(Owner)(可读写,仅叶子部门、1:1)"
              hint="Owner = 该部门为知识库的唯一归属(本部门成员按角色可读写)。改绑到新叶子部门;已被其它库占用的部门禁选。"
            >
              <div className="max-h-56 overflow-auto rounded-lg border border-blue-200 bg-blue-50/20 p-2">
                {deptTree.length === 0 ? (
                  <div className="py-6 text-center text-xs text-slate-400">加载中…</div>
                ) : (
                  <DeptLeafSelect
                    nodes={visibleTree}
                    value={editDept}
                    onChange={setEditDept}
                    disabledIds={occupiedForEdit}
                  />
                )}
              </div>
            </FieldBlock>
          )}
          <FieldBlock
            label="Editor 写权限配置(可读写)"
            hint="Editor = 该组织成员按角色可上传/摄入/摄出/删除。授某中心 = 其下全部部门自动继承(显示为「继承自上级」且锁定,需在该中心节点取消)。勾选先本地暂存,点「保存」才生效。"
          >
            <div className="max-h-64 overflow-auto rounded-lg border border-emerald-200 bg-emerald-50/20 p-2">
              {!loadedOnce ? (
                <div className="py-6 text-center text-xs text-slate-400">加载中…</div>
              ) : (
                <DeptCheckTree
                  nodes={visibleTree}
                  selected={editorState.selected}
                  onToggle={onToggleEditor}
                  disabledIds={editorDisabled}
                  badgeOf={editorBadge}
                  partialIds={editorState.partialIds}
                />
              )}
            </div>
          </FieldBlock>
          <FieldBlock
            label="Reader 访问权限配置(只读)"
            hint="Reader = 该组织成员仅可查看/预览/查询/下载,写操作会被拒绝(权限不足)。同一节点若同时是 Owner/Editor 与 Reader,按「交集取大」生效更高级别。"
          >
            <div className="max-h-64 overflow-auto rounded-lg border border-slate-200 bg-slate-50/40 p-2">
              {!loadedOnce ? (
                <div className="py-6 text-center text-xs text-slate-400">加载中…</div>
              ) : (
                <DeptCheckTree
                  nodes={visibleTree}
                  selected={readerState.selected}
                  onToggle={onToggleReader}
                  disabledIds={readerDisabled}
                  badgeOf={readerBadge}
                  partialIds={readerState.partialIds}
                />
              )}
            </div>
          </FieldBlock>
        </div>
      ) : (
        <div>
          <Field label="知识库名称">{currentName}</Field>
          <Field label="类型">
            <span className={cn("inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ring-1 ring-inset", kbTypeTagCls(currentType))}>
              {KbTypeLabel[currentType] ?? currentType}
            </span>
            {isBuiltin && <span className="ml-2 text-xs text-slate-400">系统内置</span>}
          </Field>
          <Field label="状态"><StatusBadge status={kb.status} /></Field>
          {isDept && (
            <Field label="绑定部门(Owner)">
              {currentDept ? (
                <span className="rounded-full border border-blue-200 bg-blue-50 px-2 py-0.5 text-xs text-blue-600">
                  {kb.deptPath || deptName(currentDept)}
                </span>
              ) : (
                <span className="text-xs text-amber-500">未绑定(请点「编辑」设置)</span>
              )}
            </Field>
          )}
          <Field label="Editor(可读写)">
            {!loadedOnce ? (
              <span className="text-xs text-slate-400">加载中…</span>
            ) : previewEditor.length === 0 ? (
              <span className="text-xs text-slate-400">未配置 Editor</span>
            ) : (
              <div className="flex flex-wrap gap-1.5">
                {previewEditor.map((g) => (
                  <span key={g.id} className="rounded-full border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-xs text-emerald-600">
                    {g.granteeLabel || "—"}
                  </span>
                ))}
              </div>
            )}
          </Field>
          <Field label="Reader(只读)">
            {!loadedOnce ? (
              <span className="text-xs text-slate-400">加载中…</span>
            ) : previewReader.length === 0 ? (
              <span className="text-xs text-slate-400">未配置 Reader</span>
            ) : (
              <div className="flex flex-wrap gap-1.5">
                {previewReader.map((g) => (
                  <span key={g.id} className="rounded-full border border-slate-200 bg-slate-100 px-2 py-0.5 text-xs text-slate-600">
                    {g.granteeLabel || "—"}
                  </span>
                ))}
              </div>
            )}
          </Field>
          <Field label="库根目录">
            <span className="break-all font-mono text-xs text-slate-500">{kb.rootDir}</span>
          </Field>
        </div>
      )}
    </Drawer>
  );
}