page.tsx 19.8 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
"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { KeyRound, Pencil, Trash2, UserPlus, X } from "lucide-react";

import Perm from "@/components/Perm";
import {
  Card,
  Check,
  Drawer,
  Field,
  FormRow,
  GhostButton,
  Input,
  Modal,
  MultiSelectList,
  Pagination,
  PrimaryButton,
  SearchInput,
  Select,
  SortHeader,
  type SortState,
  Spinner,
  StatusBadge,
  SysPage,
  Toolbar,
} from "@/components/system/kit";
import {
  createOaUser,
  deleteOaUser,
  batchDeleteOaUsers,
  listOaDepts,
  listOaPosts,
  listOaRoles,
  listOaUsers,
  resetOaUserPwd,
  updateOaUser,
  type OaDept,
  type OaPost,
  type OaRole,
  type OaUser,
} from "@/lib/auth";

function flattenDepts(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) flattenDepts(d.children, depth + 1, out);
  }
  return out;
}

/** 构建「部门 id → 自身及所有子孙 id 集合」映射,用于按部门过滤下属岗位。 */
function buildDeptDescendants(items: OaDept[], map: Map<string, Set<string>> = new Map()) {
  for (const d of items) {
    const set = new Set<string>([d.id]);
    if (d.children?.length) {
      buildDeptDescendants(d.children, map);
      for (const c of d.children) for (const id of map.get(c.id) ?? []) set.add(id);
    }
    map.set(d.id, set);
  }
  return map;
}

export default function UserPage() {
  const [users, setUsers] = useState<OaUser[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);

  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [sort, setSort] = useState<SortState>({ by: "createdAt", order: "desc" });

  const [kwInput, setKwInput] = useState("");
  const [keyword, setKeyword] = useState("");
  const [deptId, setDeptId] = useState("");
  const [roleId, setRoleId] = useState("");
  const [postName, setPostName] = useState("");
  const [statusF, setStatusF] = useState("");

  const [depts, setDepts] = useState<{ id: string; label: string }[]>([]);
  const [deptDesc, setDeptDesc] = useState<Map<string, Set<string>>>(new Map());
  const [roles, setRoles] = useState<OaRole[]>([]);
  const [posts, setPosts] = useState<OaPost[]>([]);

  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [preview, setPreview] = useState<OaUser | null>(null);
  const [editUser, setEditUser] = useState<OaUser | null>(null);
  const [creating, setCreating] = useState(false);
  const [notice, setNotice] = useState("");

  const flash = (m: string) => (setNotice(m), setTimeout(() => setNotice(""), 3500));

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const data = await listOaUsers({
        keyword, deptId, roleId, postName, status: statusF,
        sortBy: sort.by, sortOrder: sort.order,
        limit: pageSize, offset: (page - 1) * pageSize,
      });
      setUsers(data.items);
      setTotal(data.total);
    } finally {
      setLoading(false);
    }
  }, [keyword, deptId, roleId, postName, statusF, sort, page, pageSize]);

  useEffect(() => { load(); }, [load]);
  useEffect(() => {
    listOaDepts().then((d) => { setDepts(flattenDepts(d.items)); setDeptDesc(buildDeptDescendants(d.items)); }).catch(() => undefined);
    listOaRoles().then((r) => setRoles(r.items)).catch(() => undefined);
    listOaPosts().then((p) => setPosts(p.items)).catch(() => undefined);
  }, []);

  const resetTo1 = () => (setPage(1), setSelected(new Set()));
  const onSort = (s: SortState) => (setSort(s), resetTo1());

  // 岗位下拉:按名称去重(同名岗位可能分散在多部门,按名筛选可命中全部持有者)
  const postNames = useMemo(
    () => Array.from(new Set(posts.map((p) => p.postName))).sort((a, b) => a.localeCompare(b)),
    [posts]
  );

  const pageIds = users.map((u) => u.id);
  const allChecked = pageIds.length > 0 && pageIds.every((id) => selected.has(id));
  const someChecked = pageIds.some((id) => selected.has(id));
  const toggleAll = (v: boolean) =>
    setSelected((s) => { const n = new Set(s); pageIds.forEach((id) => (v ? n.add(id) : n.delete(id))); return n; });
  const toggleOne = (id: string, v: boolean) =>
    setSelected((s) => { const n = new Set(s); v ? n.add(id) : n.delete(id); return n; });

  const applyKeyword = () => { setKeyword(kwInput.trim()); resetTo1(); };
  const clearFilters = () => {
    setKwInput(""); setKeyword(""); setDeptId(""); setRoleId(""); setPostName(""); setStatusF(""); resetTo1();
  };
  const hasFilter = keyword || deptId || roleId || postName || statusF;

  const batchDelete = async () => {
    const ids = [...selected];
    if (!ids.length) return;
    if (!confirm(`确认删除选中的 ${ids.length} 个用户?超级管理员会自动跳过。`)) return;
    const r = await batchDeleteOaUsers(ids);
    flash(`已删除 ${r.deleted} 人${r.skipped ? `,跳过超管 ${r.skipped} 人` : ""}`);
    setSelected(new Set());
    load();
  };
  const doDelete = async (u: OaUser) => {
    if (u.isSuperadmin) return alert("超级管理员不可删除");
    if (!confirm(`确认删除用户「${u.displayName}」?`)) return;
    await deleteOaUser(u.id);
    flash("已删除"); setPreview(null); load();
  };

  return (
    <SysPage
      title="用户管理"
      subtitle={`组织内共 ${total} 名成员;选择“中心”会展开其下所有部门人员`}
      actions={
        <>
          {selected.size > 0 && (
            <Perm code="oa:user:remove">
              <GhostButton danger onClick={batchDelete}>
                <Trash2 className="h-4 w-4" /> 批量删除({selected.size})
              </GhostButton>
            </Perm>
          )}
          <Perm code="oa:user:add">
            <PrimaryButton onClick={() => setCreating(true)}>
              <UserPlus className="h-4 w-4" /> 新增用户
            </PrimaryButton>
          </Perm>
        </>
      }
    >
      {notice && <div className="shrink-0 rounded-lg bg-emerald-50 px-3 py-2 text-sm text-emerald-700">{notice}</div>}

      <Toolbar>
        <SearchInput value={kwInput} onChange={setKwInput} onEnter={applyKeyword} placeholder="姓名 / 手机号 / 门店" className="w-56" />
        <Select value={deptId} onChange={(v) => (setDeptId(v), resetTo1())}>
          <option value="">全部中心 / 部门</option>
          {depts.map((d) => <option key={d.id} value={d.id}>{d.label}</option>)}
        </Select>
        <Select value={roleId} onChange={(v) => (setRoleId(v), resetTo1())}>
          <option value="">全部角色</option>
          {roles.map((r) => <option key={r.id} value={r.id}>{r.roleName}</option>)}
        </Select>
        <Select value={postName} onChange={(v) => (setPostName(v), resetTo1())}>
          <option value="">全部岗位</option>
          {postNames.map((n) => <option key={n} value={n}>{n}</option>)}
        </Select>
        <Select value={statusF} onChange={(v) => (setStatusF(v), resetTo1())}>
          <option value="">全部状态</option>
          <option value="active">启用</option>
          <option value="disabled">停用</option>
        </Select>
        <PrimaryButton onClick={applyKeyword}>搜索</PrimaryButton>
        {hasFilter && <GhostButton onClick={clearFilters}><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-10" />
              <col className="w-28" />
              <col className="w-32" />
              <col className="w-40" />
              <col className="w-32" />
              <col className="w-36" />
              <col className="w-28" />
              <col className="w-20" />
              <col className="w-36" />
            </colgroup>
            <thead className="sticky top-0 z-10 bg-blue-50/95 text-left backdrop-blur">
              <tr className="border-b border-blue-100">
                <th className="px-4 py-2.5"><Check checked={allChecked} indeterminate={someChecked} onChange={toggleAll} /></th>
                <SortHeader label="姓名" field="displayName" sort={sort} onSort={onSort} />
                <SortHeader label="账号" field="username" sort={sort} onSort={onSort} />
                <th className="px-4 py-2.5 font-semibold text-slate-500">中心</th>
                <SortHeader label="部门" field="deptName" sort={sort} onSort={onSort} />
                <SortHeader label="岗位" field="postName" sort={sort} onSort={onSort} />
                <SortHeader label="角色" field="roleName" sort={sort} onSort={onSort} />
                <SortHeader label="状态" field="status" sort={sort} onSort={onSort} />
                <SortHeader label="最近登录" field="lastLoginAt" sort={sort} onSort={onSort} />
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={9}><Spinner /></td></tr>
              ) : users.length === 0 ? (
                <tr><td colSpan={9} className="py-16 text-center text-slate-400">暂无匹配的用户</td></tr>
              ) : (
                users.map((u) => (
                  <tr key={u.id} onClick={() => setPreview(u)} className="cursor-pointer border-b border-slate-50 transition hover:bg-blue-50/50">
                    <td className="px-4 py-2.5"><Check checked={selected.has(u.id)} onChange={(v) => toggleOne(u.id, v)} /></td>
                    <td className="truncate px-4 py-2.5 font-medium text-slate-800">
                      {u.displayName}
                      {u.isSuperadmin && <span className="ml-1 rounded bg-amber-100 px-1 py-0.5 text-[11px] font-medium text-amber-700">超管</span>}
                    </td>
                    <td className="truncate px-4 py-2.5 text-slate-500">{u.username}</td>
                    <td className="truncate px-4 py-2.5 text-slate-500">{u.centerName || "-"}</td>
                    <td className="truncate px-4 py-2.5 text-slate-500">{u.deptName || u.storeName || "-"}</td>
                    <td className="truncate px-4 py-2.5 text-slate-500">{(u.posts ?? []).join("、") || "-"}</td>
                    <td className="truncate px-4 py-2.5 text-slate-500">{(u.roles ?? []).join("、") || "-"}</td>
                    <td className="px-4 py-2.5"><StatusBadge status={u.status} /></td>
                    <td className="truncate px-4 py-2.5 text-slate-400">{u.lastLoginAt ? u.lastLoginAt.slice(0, 16).replace("T", " ") : "从未登录"}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
        <Pagination page={page} pageSize={pageSize} total={total} onPage={setPage} onPageSize={(s) => (setPageSize(s), setPage(1))} selectedCount={selected.size} />
      </Card>

      <Drawer
        open={!!preview}
        onClose={() => setPreview(null)}
        title={
          <span className="flex items-center gap-2">
            {preview?.displayName}
            {preview?.isSuperadmin && <span className="rounded bg-amber-100 px-1.5 py-0.5 text-[11px] font-medium text-amber-700">超管</span>}
          </span>
        }
        subtitle={preview?.username}
        footer={preview && (
          <>
            {!preview.isSuperadmin && (
              <Perm code="oa:user:remove"><GhostButton danger onClick={() => doDelete(preview)}><Trash2 className="h-4 w-4" /> 删除</GhostButton></Perm>
            )}
            <Perm code="oa:user:edit"><PrimaryButton onClick={() => setEditUser(preview)}><Pencil className="h-4 w-4" /> 编辑</PrimaryButton></Perm>
          </>
        )}
      >
        {preview && (
          <div>
            <Field label="姓名">{preview.displayName}</Field>
            <Field label="登录账号">{preview.username}</Field>
            <Field label="手机号">{preview.phone || "—"}</Field>
            <Field label="邮箱">{preview.email || "—"}</Field>
            <Field label="架构">{preview.archName || "—"}</Field>
            <Field label="中心">{preview.centerName || "—"}</Field>
            <Field label="部门">{preview.deptName || "—"}</Field>
            <Field label="门店">{preview.storeName || "—"}</Field>
            <Field label="岗位">{(preview.posts ?? []).join("、") || "—"}</Field>
            <Field label="角色">{(preview.roles ?? []).join("、") || "—"}</Field>
            <Field label="状态"><StatusBadge status={preview.status} /></Field>
            <Field label="超级管理员">{preview.isSuperadmin ? "是(默认全部权限)" : "否"}</Field>
            <Field label="最近登录">{preview.lastLoginAt ? preview.lastLoginAt.slice(0, 19).replace("T", " ") : "从未登录"}</Field>
          </div>
        )}
      </Drawer>

      {(creating || editUser) && (
        <UserDialog
          user={editUser}
          depts={depts}
          deptDesc={deptDesc}
          roles={roles}
          posts={posts}
          onClose={() => { setCreating(false); setEditUser(null); }}
          onSaved={(m) => { flash(m); setCreating(false); setEditUser(null); setPreview(null); load(); }}
        />
      )}
    </SysPage>
  );
}

function UserDialog({
  user, depts, deptDesc, roles, posts, onClose, onSaved,
}: {
  user: OaUser | null;
  depts: { id: string; label: string }[];
  deptDesc: Map<string, Set<string>>;
  roles: OaRole[];
  posts: OaPost[];
  onClose: () => void;
  onSaved: (msg: string) => void;
}) {
  const [displayName, setDisplayName] = useState(user?.displayName ?? "");
  const [phone, setPhone] = useState(user?.phone ?? user?.username ?? "");
  const [email, setEmail] = useState(user?.email ?? "");
  const [deptId, setDeptId] = useState(user?.deptId ?? "");
  const [storeName, setStoreName] = useState(user?.storeName ?? "");
  const [statusV, setStatusV] = useState(user?.status ?? "active");
  const [isSuper, setIsSuper] = useState(Boolean(user?.isSuperadmin));
  const [postIds, setPostIds] = useState<Set<string>>(new Set(user?.postIds ?? []));
  const [roleIds, setRoleIds] = useState<Set<string>>(new Set(user?.roleIds ?? []));
  const [err, setErr] = useState("");
  const [saving, setSaving] = useState(false);

  // 选定部门/中心后,仅展示该部门(含下属)的岗位;未选部门则展示全部
  const allowed = deptId ? deptDesc.get(deptId) : null;
  const visiblePosts = allowed
    ? posts.filter((p) => (p.deptId && allowed.has(p.deptId)) || postIds.has(p.id))
    : posts;
  const postOpts = visiblePosts.map((p) => ({
    id: p.id,
    label: p.postName,
    hint: [p.centerName, p.deptName].filter(Boolean).join("·") || undefined,
  }));
  const roleOpts = roles.map((r) => ({ id: r.id, label: r.roleName, hint: r.roleCode }));

  // 岗位↔角色绑定:勾选岗位时,自动并入其默认角色(可再手动调整)
  const togglePost = (id: string) =>
    setPostIds((s) => {
      const n = new Set(s);
      if (n.has(id)) n.delete(id);
      else {
        n.add(id);
        const p = posts.find((x) => x.id === id);
        if (p?.defaultRoleIds?.length) setRoleIds((rs) => new Set([...rs, ...p.defaultRoleIds]));
      }
      return n;
    });
  const toggleRole = (id: string) =>
    setRoleIds((s) => { const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n; });

  const submit = async () => {
    setSaving(true); setErr("");
    try {
      if (user) {
        await updateOaUser(user.id, {
          displayName, phone, email: email || null, deptId: deptId || null,
          storeName: storeName || null, status: statusV, isSuperadmin: isSuper,
          roleIds: [...roleIds], postIds: [...postIds],
        });
        onSaved("已保存");
      } else {
        const r = await createOaUser({
          displayName, phone, email: email || null, deptId: deptId || null,
          storeName: storeName || null, isSuperadmin: isSuper,
          roleIds: [...roleIds], postIds: [...postIds],
        });
        onSaved(`已创建,初始密码:${r.initialPassword}`);
      }
    } catch (e) {
      setErr(e instanceof Error ? e.message : "保存失败");
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal title={user ? "编辑用户" : "新增用户"} onClose={onClose} size="2xl">
      <div className="space-y-5">
        {/* 基本信息 */}
        <section>
          <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-slate-400">基本信息</div>
          <div className="grid grid-cols-2 gap-x-5 gap-y-3">
            <FormRow label="姓名"><Input value={displayName} onChange={setDisplayName} /></FormRow>
            <FormRow label="手机号(登录账号)"><Input value={phone} onChange={setPhone} placeholder="初始密码 123456" /></FormRow>
            <FormRow label="邮箱"><Input value={email} onChange={setEmail} /></FormRow>
            <FormRow label="门店(驻店人员)"><Input value={storeName} onChange={setStoreName} /></FormRow>
            <FormRow label="部门 / 中心">
              <Select value={deptId} onChange={setDeptId} className="w-full">
                <option value="">(未指定)</option>
                {depts.map((d) => <option key={d.id} value={d.id}>{d.label}</option>)}
              </Select>
            </FormRow>
            <FormRow label="状态">
              <Select value={statusV} onChange={setStatusV} className="w-full">
                <option value="active">启用</option>
                <option value="disabled">停用</option>
              </Select>
            </FormRow>
          </div>
          <label className="mt-3 flex items-center gap-2 text-sm text-slate-600">
            <input type="checkbox" checked={isSuper} onChange={(e) => setIsSuper(e.target.checked)} className="h-4 w-4 accent-blue-600" />
            设为超级管理员(默认拥有全部权限,不可被删除)
          </label>
        </section>

        {/* 岗位与角色(单栏堆叠,岗位随所选部门过滤) */}
        <section className="space-y-4">
          <div>
            <div className="mb-1.5 flex items-center justify-between">
              <span className="text-xs font-semibold uppercase tracking-wide text-slate-400">岗位(可多选,支持搜索)</span>
              <span className="text-[11px] text-slate-400">
                {deptId ? `已按所选部门过滤,共 ${postOpts.length} 个` : "未选部门,展示全部岗位"}
              </span>
            </div>
            <MultiSelectList options={postOpts} selected={postIds} onToggle={togglePost} searchable emptyText="该部门下暂无岗位" height="max-h-48" />
          </div>
          <div>
            <div className="mb-1.5 text-xs font-semibold uppercase tracking-wide text-slate-400">角色(可多选,随岗位默认角色自动并入)</div>
            <MultiSelectList options={roleOpts} selected={roleIds} onToggle={toggleRole} searchable emptyText="无角色" height="max-h-48" />
          </div>
        </section>

        {err && <p className="text-sm text-rose-500">{err}</p>}
        <div className="flex items-center justify-between gap-2 border-t border-slate-100 pt-4">
          <div>
            {user && (
              <Perm code="oa:user:resetPwd">
                <GhostButton
                  onClick={async () => {
                    if (!confirm("确认将该用户密码重置为初始密码?")) return;
                    const r = await resetOaUserPwd(user.id);
                    setErr(`已重置密码:${r.initialPassword}`);
                  }}
                >
                  <KeyRound className="h-4 w-4" /> 重置密码
                </GhostButton>
              </Perm>
            )}
          </div>
          <div className="flex gap-2">
            <GhostButton onClick={onClose}>取消</GhostButton>
            <PrimaryButton onClick={submit} disabled={saving}>{saving ? "保存中…" : "保存"}</PrimaryButton>
          </div>
        </div>
      </div>
    </Modal>
  );
}