page.tsx 11.5 KB
"use client";

import { useEffect, useMemo, useState } from "react";
import { Building2, ChevronDown, ChevronRight, Pencil, Plus, Trash2 } from "lucide-react";

import Perm from "@/components/Perm";
import {
  Card,
  Drawer,
  Field,
  FormRow,
  GhostButton,
  Input,
  Modal,
  PrimaryButton,
  Select,
  Spinner,
  StatusBadge,
  SysPage,
} from "@/components/system/kit";
import {
  createOaDept,
  deleteOaDept,
  listOaDepts,
  updateOaDept,
  type OaDept,
} from "@/lib/auth";
import { DeptCategoryLabel } from "@/lib/oaEnums";
import { cn } from "@/lib/utils";

function flatten(items: OaDept[], depth = 0, out: { id: string; label: string }[] = []) {
  for (const d of items) {
    out.push({ id: d.id, label: `${" ".repeat(depth)}${d.deptName}` });
    if (d.children?.length) flatten(d.children, depth + 1, out);
  }
  return out;
}

export default function DeptPage() {
  const [tree, setTree] = useState<OaDept[]>([]);
  const [loading, setLoading] = useState(true);
  const [notice, setNotice] = useState("");
  const [selected, setSelected] = useState<OaDept | null>(null);
  const [open, setOpen] = useState<Set<string>>(new Set());
  const [editing, setEditing] = useState<OaDept | null>(null);
  const [creating, setCreating] = useState(false);

  const load = () => {
    setLoading(true);
    listOaDepts()
      .then((d) => {
        setTree(d.items);
        // 组织树默认展开到二级:顶级架构全部展开,露出各中心;三级部门保持折叠
        setOpen(new Set(d.items.map((x) => x.id)));
      })
      .finally(() => setLoading(false));
  };
  useEffect(load, []);
  const flash = (m: string) => (setNotice(m), setTimeout(() => setNotice(""), 3000));

  const flat = useMemo(() => flatten(tree), [tree]);
  const depthMap = useMemo(() => {
    const m = new Map<string, number>();
    const walk = (items: OaDept[], d: number) =>
      items.forEach((x) => { m.set(x.id, d); if (x.children?.length) walk(x.children, d + 1); });
    walk(tree, 0);
    return m;
  }, [tree]);
  const levelLabel = (d: OaDept) => {
    const dep = depthMap.get(d.id) ?? (d.parentId ? 2 : 0);
    return dep === 0 ? "架构(一级)" : dep === 1 ? "中心(二级)" : "部门(三级)";
  };
  const parentLabel = (id: string | null) =>
    id ? flat.find((d) => d.id === id)?.label.trim() ?? "—" : "顶级架构";
  const childCount = selected?.children?.length ?? 0;

  const toggle = (id: string) =>
    setOpen((s) => {
      const n = new Set(s);
      n.has(id) ? n.delete(id) : n.add(id);
      return n;
    });

  const onRow = (d: OaDept) => setSelected(d);

  const doDelete = async (d: OaDept) => {
    if (!confirm(`删除部门「${d.deptName}」?`)) return;
    try {
      await deleteOaDept(d.id);
      flash("已删除");
      if (selected?.id === d.id) setSelected(null);
      load();
    } catch (e) {
      alert(e instanceof Error ? e.message : "删除失败");
    }
  };

  return (
    <SysPage
      title="部门管理"
      subtitle="广联总部 / 外包架构 两大架构 → 中心 → 部门三级;默认展开到中心,点击可继续展开下级并预览详情"
      actions={
        <>
          <Perm code="oa:dept:add">
            <PrimaryButton onClick={() => setCreating(true)}>
              <Plus className="h-4 w-4" /> 新增部门
            </PrimaryButton>
          </Perm>
        </>
      }
    >
      {notice && (
        <div className="rounded-lg bg-emerald-50 px-3 py-2 text-sm text-emerald-700">{notice}</div>
      )}

      {/* 部门树(占满宽度,点击部门在右侧抽屉查看详情) */}
      <Card>
        <div className="border-b border-blue-100 bg-blue-50/60 px-4 py-2.5 text-xs font-semibold text-slate-500">
          组织架构树
        </div>
        <div className="min-h-0 flex-1 overflow-auto p-2">
          {loading ? (
            <Spinner />
          ) : (
            <ul>
              {tree.map((n) => (
                <DeptNode
                  key={n.id}
                  node={n}
                  depth={0}
                  open={open}
                  selectedId={selected?.id ?? null}
                  onRow={onRow}
                  onToggle={toggle}
                />
              ))}
            </ul>
          )}
        </div>
      </Card>

      {/* 详情抽屉(与用户/角色/岗位页一致的右侧滑出) */}
      <Drawer
        open={!!selected}
        onClose={() => setSelected(null)}
        title={
          <span className="flex items-center gap-2">
            <Building2 className="h-4 w-4 text-blue-500" />
            {selected?.deptName}
          </span>
        }
        subtitle={selected ? levelLabel(selected) : ""}
        footer={selected && (
          <>
            <Perm code="oa:dept:remove">
              <GhostButton danger onClick={() => doDelete(selected)}>
                <Trash2 className="h-4 w-4" /> 删除
              </GhostButton>
            </Perm>
            <Perm code="oa:dept:edit">
              <PrimaryButton onClick={() => setEditing(selected)}>
                <Pencil className="h-4 w-4" /> 编辑
              </PrimaryButton>
            </Perm>
          </>
        )}
      >
        {selected && (
          <div>
            <Field label="部门名称">{selected.deptName}</Field>
            <Field label="层级">{levelLabel(selected)}</Field>
            <Field label="类别">{DeptCategoryLabel[selected.deptCategory]}</Field>
            <Field label="上级">{parentLabel(selected.parentId)}</Field>
            <Field label="下级数">{childCount} 个</Field>
            <Field label="排序号">{selected.orderNum}</Field>
            <Field label="状态"><StatusBadge status={selected.status} /></Field>
            <div className="pt-3">
              <div className="mb-1.5 text-xs font-medium text-slate-400">部门职责</div>
              <div className="whitespace-pre-wrap rounded-xl bg-slate-50 p-3 text-sm leading-relaxed text-slate-700">
                {selected.duty || "暂无部门职责"}
              </div>
            </div>
          </div>
        )}
      </Drawer>

      {(editing || creating) && (
        <DeptForm
          dept={editing}
          allDepts={flat}
          onClose={() => (setEditing(null), setCreating(false))}
          onSaved={() => {
            flash("已保存");
            setEditing(null);
            setCreating(false);
            load();
          }}
        />
      )}
    </SysPage>
  );
}

function DeptNode({
  node,
  depth,
  open,
  selectedId,
  onRow,
  onToggle,
}: {
  node: OaDept;
  depth: number;
  open: Set<string>;
  selectedId: string | null;
  onRow: (d: OaDept) => void;
  onToggle: (id: string) => void;
}) {
  const hasChild = node.children?.length > 0;
  const isOpen = open.has(node.id);
  return (
    <li>
      <div
        onClick={() => onRow(node)}
        style={{ paddingLeft: depth * 16 + 8 }}
        className={cn(
          "group flex cursor-pointer items-center gap-1.5 rounded-lg py-2 pr-2 text-sm transition",
          selectedId === node.id ? "bg-blue-100 text-blue-800" : "hover:bg-blue-50"
        )}
      >
        {hasChild ? (
          <button
            onClick={(e) => (e.stopPropagation(), onToggle(node.id))}
            className="text-slate-400"
          >
            {isOpen ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
          </button>
        ) : (
          <span className="w-4" />
        )}
        <span className="font-medium text-slate-700">{node.deptName}</span>
        {/* 层级:一级=架构,二级=中心,三级及以下=部门 */}
        <span
          className={cn(
            "rounded px-1.5 py-0.5 text-[11px]",
            depth === 0 ? "bg-indigo-50 text-indigo-600" : depth === 1 ? "bg-blue-50 text-blue-600" : "bg-slate-100 text-slate-500"
          )}
        >
          {depth === 0 ? "架构" : depth === 1 ? "中心" : "部门"}
        </span>
        {hasChild && (
          <span className="ml-1 text-[11px] text-slate-400">{node.children.length}</span>
        )}
      </div>
      {hasChild && isOpen && (
        <ul>
          {node.children.map((c) => (
            <DeptNode
              key={c.id}
              node={c}
              depth={depth + 1}
              open={open}
              selectedId={selectedId}
              onRow={onRow}
              onToggle={onToggle}
            />
          ))}
        </ul>
      )}
    </li>
  );
}

function DeptForm({
  dept,
  allDepts,
  onClose,
  onSaved,
}: {
  dept: OaDept | null;
  allDepts: { id: string; label: string }[];
  onClose: () => void;
  onSaved: () => void;
}) {
  const [deptName, setName] = useState(dept?.deptName ?? "");
  const [deptCategory, setCat] = useState(dept?.deptCategory ?? "hq");
  const [parentId, setParentId] = useState(dept?.parentId ?? "");
  const [orderNum, setOrder] = useState(String(dept?.orderNum ?? 0));
  const [duty, setDuty] = useState(dept?.duty ?? "");
  const [err, setErr] = useState("");

  const submit = async () => {
    try {
      if (dept) {
        await updateOaDept(dept.id, { deptName, deptCategory, orderNum: Number(orderNum) || 0, duty });
      } else {
        await createOaDept({
          deptName,
          deptCategory,
          parentId: parentId || null,
          orderNum: Number(orderNum) || 0,
          duty,
        });
      }
      onSaved();
    } catch (e) {
      setErr(e instanceof Error ? e.message : "失败");
    }
  };

  return (
    <Modal title={dept ? "编辑部门" : "新增部门"} onClose={onClose} size="2xl">
      <div className="space-y-4">
        <div className="grid grid-cols-2 gap-x-5 gap-y-3">
          <FormRow label="部门名称">
            <Input value={deptName} onChange={setName} />
          </FormRow>
          {!dept ? (
            <FormRow label="上级部门(留空即为顶级架构)">
              <Select value={parentId} onChange={setParentId} className="w-full">
                <option value="">(顶级架构)</option>
                {allDepts.map((d) => (
                  <option key={d.id} value={d.id}>
                    {d.label}
                  </option>
                ))}
              </Select>
            </FormRow>
          ) : (
            <FormRow label="类别">
              <Select value={deptCategory} onChange={setCat} className="w-full">
                <option value="hq">总部</option>
                <option value="outsource">外包</option>
              </Select>
            </FormRow>
          )}
          {!dept && (
            <FormRow label="类别">
              <Select value={deptCategory} onChange={setCat} className="w-full">
                <option value="hq">总部</option>
                <option value="outsource">外包</option>
              </Select>
            </FormRow>
          )}
          <FormRow label="排序号(越小越靠前)">
            <Input value={orderNum} onChange={setOrder} type="number" />
          </FormRow>
        </div>
        <FormRow label="部门职责">
          <textarea
            value={duty}
            onChange={(e) => setDuty(e.target.value)}
            rows={10}
            className="w-full rounded-lg border border-slate-200 px-3 py-2.5 text-sm leading-relaxed outline-none transition focus:border-blue-400 focus:ring-2 focus:ring-blue-400/20"
          />
        </FormRow>
        {err && <p className="text-sm text-rose-500">{err}</p>}
        <div className="flex justify-end gap-2 pt-1">
          <GhostButton onClick={onClose}>取消</GhostButton>
          <PrimaryButton onClick={submit}>保存</PrimaryButton>
        </div>
      </div>
    </Modal>
  );
}