UserProfileDialog.tsx 7.42 KB
"use client";

import { useCallback, useEffect, useState } from "react";
import { Brain, Loader2, RefreshCw, UserRound } from "lucide-react";

import {
  fetchUserProfile,
  regenerateUserProfile,
  updateUserProfile,
  type AdminUserProfile,
} from "@/lib/auth";
import { cn } from "@/lib/utils";

type TabKey = "profile" | "memory";

interface UserProfileDialogProps {
  userId: string;
  displayName: string;
  onClose: () => void;
}

/**
 * 管理员编辑某用户画像的弹窗:岗位画像 / 长期记忆 两个 Tab,均为可编辑 markdown 原文。
 *
 * 复用改密弹窗的模态外壳(遮罩 + 白卡)。与用户本人只读的「我的画像」页不同,
 * 这里两段内容都可直接改写并保存。
 */
export default function UserProfileDialog({
  userId,
  displayName,
  onClose,
}: UserProfileDialogProps) {
  const [tab, setTab] = useState<TabKey>("profile");
  const [data, setData] = useState<AdminUserProfile | null>(null);
  const [profileMd, setProfileMd] = useState("");
  const [longMemCoreMd, setLongMemCoreMd] = useState("");
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");

  const load = useCallback(async () => {
    setLoading(true);
    setError("");
    try {
      const payload = await fetchUserProfile(userId);
      setData(payload);
      setProfileMd(payload.profileMd);
      setLongMemCoreMd(payload.longMemCoreMd);
    } catch (err) {
      setError(err instanceof Error ? err.message : "加载失败");
    } finally {
      setLoading(false);
    }
  }, [userId]);

  useEffect(() => {
    load();
  }, [load]);

  const handleSave = async () => {
    setBusy(true);
    setError("");
    try {
      // 长期记忆是 mem0 核心集的派生缓存,不接受手改;管理员保存只写画像。
      await updateUserProfile(userId, { profileMd });
      setNotice("已保存");
      setTimeout(() => setNotice(""), 2500);
    } catch (err) {
      setError(err instanceof Error ? err.message : "保存失败");
    } finally {
      setBusy(false);
    }
  };

  const handleRegenerate = async () => {
    setBusy(true);
    setError("");
    try {
      await regenerateUserProfile(userId);
      await load();
      setNotice("已重新生成用户画像");
      setTimeout(() => setNotice(""), 2500);
    } catch (err) {
      setError(err instanceof Error ? err.message : "重新生成失败");
    } finally {
      setBusy(false);
    }
  };

  const value = tab === "profile" ? profileMd : longMemCoreMd;
  const onChange = tab === "profile" ? setProfileMd : setLongMemCoreMd;

  return (
    <div
      className="fixed inset-0 z-[60] flex items-center justify-center bg-slate-900/40 backdrop-blur-sm p-4"
      onClick={onClose}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        className="w-[720px] max-w-[92vw] max-h-[88vh] flex flex-col bg-white rounded-2xl shadow-2xl"
      >
        {/* 头部 */}
        <div className="flex items-center gap-2.5 px-5 py-4 border-b border-slate-100">
          <div className="w-9 h-9 bg-blue-50 text-blue-600 rounded-xl flex items-center justify-center shrink-0">
            <UserRound className="w-4.5 h-4.5" />
          </div>
          <div className="min-w-0">
            <h3 className="text-sm font-bold text-slate-800 truncate">
              {displayName} · 画像编辑
            </h3>
            <p className="text-[11px] text-slate-400">管理员可修改用户画像;长期记忆核心摘要只读(权威源在 mem0)</p>
          </div>
        </div>

        {/* Tab + 操作 */}
        <div className="flex items-center gap-1 px-5 pt-3">
          {(
            [
              { key: "profile", label: "用户画像", icon: UserRound },
              { key: "memory", label: "长期记忆核心摘要", icon: Brain },
            ] as const
          ).map(({ key, label, icon: Icon }) => (
            <button
              key={key}
              onClick={() => setTab(key)}
              className={cn(
                "flex items-center gap-1.5 px-3.5 py-2 text-xs font-semibold rounded-lg transition",
                tab === key
                  ? "bg-blue-50 text-blue-700"
                  : "text-slate-500 hover:bg-slate-100"
              )}
            >
              <Icon className="w-3.5 h-3.5" />
              {label}
            </button>
          ))}
          {tab === "profile" && (
            <button
              onClick={handleRegenerate}
              disabled={busy || loading}
              className="ml-auto flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-slate-600 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 transition disabled:opacity-60"
            >
              {busy ? (
                <Loader2 className="w-3 h-3 animate-spin" />
              ) : (
                <RefreshCw className="w-3 h-3" />
              )}
              重新生成
            </button>
          )}
        </div>

        {/* 编辑区 */}
        <div className="flex-1 min-h-0 px-5 py-3 overflow-hidden flex flex-col">
          {loading ? (
            <div className="flex items-center justify-center flex-1 text-slate-400 text-xs gap-2">
              <Loader2 className="w-4 h-4 animate-spin" />
              加载中…
            </div>
          ) : (
            <textarea
              value={value}
              onChange={(e) => onChange(e.target.value)}
              readOnly={tab === "memory"}
              spellCheck={false}
              placeholder={
                tab === "profile"
                  ? "用户画像(markdown)"
                  : "长期记忆核心摘要(mem0 核心集,只读)"
              }
              className={cn(
                "flex-1 min-h-[320px] w-full resize-none font-mono text-xs leading-relaxed text-slate-700 border rounded-lg p-3 outline-none transition",
                tab === "memory"
                  ? "bg-slate-100 border-slate-200 cursor-default text-slate-500"
                  : "bg-slate-50 border-slate-200 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20"
              )}
            />
          )}
          {data && !loading && tab === "memory" && (
            <p className="text-[11px] text-slate-400 mt-2">
              约 {data.memoryStats.entries} 条 · 上限 {data.memoryStats.maxChars} 字符
            </p>
          )}
        </div>

        {/* 底部 */}
        <div className="flex items-center gap-2 px-5 py-3.5 border-t border-slate-100">
          {error && <span className="text-xs text-red-600">{error}</span>}
          {notice && <span className="text-xs text-emerald-600">{notice}</span>}
          <div className="ml-auto flex items-center gap-2">
            <button
              onClick={onClose}
              className="px-3.5 py-1.5 text-xs font-semibold text-slate-600 hover:bg-slate-100 rounded-lg transition"
            >
              关闭
            </button>
            {tab === "profile" && (
              <button
                onClick={handleSave}
                disabled={busy || loading}
                className="px-3.5 py-1.5 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-60 rounded-lg transition flex items-center gap-1.5"
              >
                {busy && <Loader2 className="w-3 h-3 animate-spin" />}
                保存
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}