page.tsx 9.96 KB
"use client";

import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import {
  ChevronLeft,
  ChevronRight,
  KeyRound,
  Loader2,
  Search,
  UserRound,
} from "lucide-react";

import ConfirmDialog from "@/components/ConfirmDialog";
import UserProfileDialog from "@/components/UserProfileDialog";
import { apiJson, fetchMe } from "@/lib/auth";
import { cn } from "@/lib/utils";

interface AdminUser {
  id: string;
  username: string;
  displayName: string;
  phone: string | null;
  email: string | null;
  role: string;
  status: string;
  storeName: string | null;
  positionName: string | null;
  lastLoginAt: string | null;
}

const PAGE_SIZE = 20;

export default function AdminUsersPage() {
  const router = useRouter();
  const [users, setUsers] = useState<AdminUser[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(0);
  const [keyword, setKeyword] = useState("");
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);
  const [resetTarget, setResetTarget] = useState<AdminUser | null>(null);
  const [editTarget, setEditTarget] = useState<AdminUser | null>(null);
  const [notice, setNotice] = useState("");

  const load = useCallback(
    async (search = "", pageIndex = 0) => {
      setLoading(true);
      try {
        const data = await apiJson<{ total: number; items: AdminUser[] }>(
          `/admin/users?keyword=${encodeURIComponent(search)}&limit=${PAGE_SIZE}&offset=${
            pageIndex * PAGE_SIZE
          }`
        );
        setUsers(data.items);
        setTotal(data.total);
      } catch {
        router.push("/login");
      } finally {
        setLoading(false);
      }
    },
    [router]
  );

  useEffect(() => {
    (async () => {
      const me = await fetchMe().catch(() => null);
      if (!me) {
        router.push("/login");
        return;
      }
      if (me.role !== "admin") {
        router.push("/");
        return;
      }
      await load();
    })();
  }, [router, load]);

  const handleSearch = () => {
    setPage(0);
    load(keyword, 0);
  };

  const goPage = (next: number) => {
    setPage(next);
    load(keyword, next);
  };

  const handleReset = async () => {
    if (!resetTarget) return;
    setBusy(true);
    try {
      const data = await apiJson<{ initialPassword: string }>(
        `/admin/users/${resetTarget.id}/reset-password`,
        { method: "POST" }
      );
      setNotice(`已将 ${resetTarget.displayName} 的密码重置为 ${data.initialPassword}`);
      setResetTarget(null);
      setTimeout(() => setNotice(""), 4000);
    } finally {
      setBusy(false);
    }
  };

  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));

  return (
    <div className="flex-1 overflow-y-auto bg-slate-100">
      <div className="w-full max-w-none px-8 py-8">
        <header className="mb-5 flex items-end justify-between">
          <div>
            <h1 className="text-lg font-bold text-slate-800">用户管理</h1>
            <p className="text-xs text-slate-500 mt-1">共 {total} 名用户</p>
          </div>
          <div className="relative">
            <Search className="w-3.5 h-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
            <input
              value={keyword}
              onChange={(e) => setKeyword(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && handleSearch()}
              placeholder="搜索姓名 / 账号 / 手机号"
              className="w-64 pl-8 pr-3 py-2 text-xs bg-white border border-slate-200 rounded-lg outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 transition"
            />
          </div>
        </header>

        {notice && (
          <div className="mb-4 text-xs text-emerald-700 bg-emerald-50 border border-emerald-100 rounded-lg px-3 py-2.5">
            {notice}
          </div>
        )}

        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          {loading ? (
            <div className="flex items-center justify-center py-16 text-slate-400 text-xs gap-2">
              <Loader2 className="w-4 h-4 animate-spin" />
              加载中…
            </div>
          ) : (
            <table className="w-full text-xs">
              <thead className="bg-slate-50 border-b border-slate-200">
                <tr className="text-left text-slate-500">
                  <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">岗位</th>
                  <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">状态</th>
                  <th className="px-4 py-2.5 font-semibold text-right">操作</th>
                </tr>
              </thead>
              <tbody>
                {users.map((user) => (
                  <tr
                    key={user.id}
                    onClick={() => setEditTarget(user)}
                    title="点击查看 / 编辑该用户的画像与长期记忆"
                    className="group border-b border-slate-100 last:border-0 hover:bg-blue-50/40 cursor-pointer transition"
                  >
                    <td className="px-4 py-2.5">
                      <div className="flex items-center gap-2">
                        <div className="w-6 h-6 bg-slate-100 rounded-lg flex items-center justify-center text-slate-500 group-hover:bg-blue-100 group-hover:text-blue-600 transition">
                          <UserRound className="w-3 h-3" />
                        </div>
                        <span className="font-medium text-slate-800 group-hover:text-blue-700 transition">
                          {user.displayName}
                        </span>
                      </div>
                    </td>
                    <td className="px-4 py-2.5 text-slate-500">{user.username}</td>
                    <td className="px-4 py-2.5 text-slate-500">{user.positionName || "—"}</td>
                    <td className="px-4 py-2.5 text-slate-500">{user.storeName || "—"}</td>
                    <td className="px-4 py-2.5">
                      <span
                        className={cn(
                          "px-2 py-0.5 rounded-md text-[10px] font-semibold",
                          user.role === "admin"
                            ? "bg-blue-50 text-blue-700"
                            : "bg-slate-100 text-slate-500"
                        )}
                      >
                        {user.role === "admin" ? "管理员" : "普通用户"}
                      </span>
                    </td>
                    <td className="px-4 py-2.5">
                      <span
                        className={cn(
                          "px-2 py-0.5 rounded-md text-[10px] font-semibold",
                          user.status === "active"
                            ? "bg-emerald-50 text-emerald-700"
                            : "bg-slate-100 text-slate-400"
                        )}
                      >
                        {user.status === "active" ? "启用" : "停用"}
                      </span>
                    </td>
                    <td className="px-4 py-2.5 text-right">
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          setResetTarget(user);
                        }}
                        className="inline-flex items-center gap-1 px-2.5 py-1 text-[11px] font-semibold text-slate-600 border border-slate-200 rounded-lg hover:bg-white bg-white transition"
                      >
                        <KeyRound className="w-3 h-3" />
                        重置密码
                      </button>
                    </td>
                  </tr>
                ))}
                {users.length === 0 && (
                  <tr>
                    <td colSpan={7} className="px-4 py-12 text-center text-slate-400">
                      没有匹配的用户
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          )}
        </div>

        {/* 分页条 */}
        {!loading && total > 0 && (
          <div className="mt-4 flex items-center justify-end gap-3 text-xs text-slate-500">
            <span>
              第 {page + 1} / {totalPages} 页
            </span>
            <div className="flex items-center gap-1">
              <button
                onClick={() => goPage(page - 1)}
                disabled={page <= 0}
                className="flex items-center gap-1 px-2.5 py-1.5 font-semibold bg-white border border-slate-200 rounded-lg hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed transition"
              >
                <ChevronLeft className="w-3.5 h-3.5" />
                上一页
              </button>
              <button
                onClick={() => goPage(page + 1)}
                disabled={page >= totalPages - 1}
                className="flex items-center gap-1 px-2.5 py-1.5 font-semibold bg-white border border-slate-200 rounded-lg hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed transition"
              >
                下一页
                <ChevronRight className="w-3.5 h-3.5" />
              </button>
            </div>
          </div>
        )}
      </div>

      <ConfirmDialog
        open={!!resetTarget}
        title="重置密码?"
        description={`将把 ${resetTarget?.displayName || ""} 的密码重置为初始密码,该用户需用新密码重新登录。`}
        confirmText="重置"
        loading={busy}
        onConfirm={handleReset}
        onCancel={() => setResetTarget(null)}
      />

      {editTarget && (
        <UserProfileDialog
          userId={editTarget.id}
          displayName={editTarget.displayName}
          onClose={() => setEditTarget(null)}
        />
      )}
    </div>
  );
}