page.tsx 9.16 KB
"use client";

import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { Brain, Loader2, Pencil, Trash2, UserRound, X } from "lucide-react";

import ConfirmDialog from "@/components/ConfirmDialog";
import {
  clearMemory,
  fetchMe,
  fetchProfile,
  updateMyProfile,
  type CurrentUser,
  type ProfilePayload,
} from "@/lib/auth";
import { cn } from "@/lib/utils";

type TabKey = "profile" | "memory";

export default function ProfilePage() {
  const router = useRouter();
  const [user, setUser] = useState<CurrentUser | null>(null);
  const [data, setData] = useState<ProfilePayload | null>(null);
  const [tab, setTab] = useState<TabKey>("profile");
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);
  const [confirmClear, setConfirmClear] = useState(false);
  const [clearError, setClearError] = useState("");

  // 编辑态:editing 标记当前 tab 是否在编辑,draft 是编辑中的原文
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState("");

  const load = useCallback(async () => {
    const me = await fetchMe();
    if (!me) {
      router.push("/login");
      return;
    }
    setUser(me);
    setData(await fetchProfile());
    setLoading(false);
  }, [router]);

  useEffect(() => {
    load().catch(() => setLoading(false));
  }, [load]);

  // 切换 tab 时退出编辑态,避免草稿错位
  const switchTab = (key: TabKey) => {
    setTab(key);
    setEditing(false);
  };

  const startEdit = () => {
    if (!data) return;
    setDraft(tab === "profile" ? data.profileMdRaw : data.longMemCoreMdRaw);
    setEditing(true);
  };

  const handleSave = async () => {
    setBusy(true);
    try {
      await updateMyProfile(tab === "profile" ? { profileMd: draft } : { longMemCoreMd: draft });
      setData(await fetchProfile());
      setEditing(false);
    } finally {
      setBusy(false);
    }
  };

  const handleClearMemory = async () => {
    setBusy(true);
    setClearError("");
    try {
      await clearMemory();
      setData(await fetchProfile());
      setConfirmClear(false);
    } catch (err) {
      // 清空失败(如 mem0 不可用):后端已记录到日志表,这里让用户看到并可通知管理员
      setClearError(err instanceof Error ? err.message : "清空失败,请稍后重试或联系管理员");
      setConfirmClear(false);
    } finally {
      setBusy(false);
    }
  };

  const content = tab === "profile" ? data?.profileMd : data?.longMemCoreMd;

  return (
    <div className="flex-1 overflow-y-auto bg-slate-100">
      <div className="w-full max-w-none px-8 py-8 min-h-full flex flex-col">
        <header className="mb-6">
          <h1 className="text-lg font-bold text-slate-800">我的画像</h1>
          <p className="text-xs text-slate-500 mt-1">
            用户画像可手动编辑修正;长期记忆核心摘要由系统自动沉淀(只读),如需重置可清空。
          </p>
        </header>

        {user && (
          <div className="bg-white rounded-xl border border-slate-200 px-5 py-4 mb-5 flex items-center gap-4">
            <div className="w-11 h-11 bg-blue-600 rounded-xl flex items-center justify-center text-white shrink-0">
              <UserRound className="w-5 h-5" />
            </div>
            <div className="min-w-0">
              <div className="text-sm font-bold text-slate-800">{user.displayName}</div>
              <div className="text-xs text-slate-500 mt-0.5">
                {[user.positionName, user.storeName, user.username].filter(Boolean).join(" · ")}
              </div>
            </div>
          </div>
        )}

        <div className="flex items-center gap-1 mb-4">
          {(
            [
              { key: "profile", label: "用户画像", icon: UserRound },
              { key: "memory", label: "长期记忆核心摘要", icon: Brain },
            ] as const
          ).map(({ key, label, icon: Icon }) => (
            <button
              key={key}
              onClick={() => switchTab(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-200/60"
              )}
            >
              <Icon className="w-3.5 h-3.5" />
              {label}
            </button>
          ))}

          <div className="ml-auto flex items-center gap-2">
            {editing ? (
              <>
                <button
                  onClick={() => setEditing(false)}
                  disabled={busy}
                  className="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"
                >
                  <X className="w-3 h-3" />
                  取消
                </button>
                <button
                  onClick={handleSave}
                  disabled={busy}
                  className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition disabled:opacity-60"
                >
                  {busy && <Loader2 className="w-3 h-3 animate-spin" />}
                  保存
                </button>
              </>
            ) : (
              <>
                {/* 长期记忆是 mem0 核心集的派生缓存,手动编辑会被下次物化覆盖,故只在画像页可编辑 */}
                {tab === "profile" && (
                  <button
                    onClick={startEdit}
                    disabled={loading || !data}
                    className="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"
                  >
                    <Pencil className="w-3 h-3" />
                    编辑
                  </button>
                )}
                {tab === "memory" && (
                  <button
                    onClick={() => setConfirmClear(true)}
                    disabled={busy}
                    className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-red-600 bg-white border border-red-200 rounded-lg hover:bg-red-50 transition disabled:opacity-60"
                  >
                    <Trash2 className="w-3 h-3" />
                    清空记忆
                  </button>
                )}
              </>
            )}
          </div>
        </div>

        {tab === "memory" && clearError && (
          <div className="mb-3 flex items-start gap-2 rounded-lg border border-red-200 bg-red-50 px-3.5 py-2.5 text-xs text-red-700">
            <Trash2 className="w-3.5 h-3.5 mt-0.5 shrink-0" />
            <span>{clearError}</span>
          </div>
        )}

        <div className="bg-white rounded-xl border border-slate-200 p-6 flex-1 min-h-[320px] 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>
          ) : editing ? (
            <textarea
              value={draft}
              onChange={(e) => setDraft(e.target.value)}
              spellCheck={false}
              placeholder={tab === "profile" ? "用户画像(markdown)" : "长期记忆核心摘要(markdown)"}
              className="flex-1 min-h-[320px] w-full resize-none font-mono text-xs leading-relaxed text-slate-700 bg-slate-50 border border-slate-200 rounded-lg p-3 outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 transition"
            />
          ) : content ? (
            <article className="prose prose-sm prose-slate max-w-none">
              <ReactMarkdown remarkPlugins={[remarkGfm]}>{content}</ReactMarkdown>
            </article>
          ) : (
            <div className="text-center py-16 m-auto">
              <Brain className="w-10 h-10 mx-auto text-slate-300 mb-3" />
              <p className="text-xs text-slate-400 leading-relaxed">
                {tab === "profile"
                  ? "用户画像尚未生成,稍后刷新即可看到;也可点「编辑」自行填写"
                  : "还没有沉淀出长期记忆核心摘要,多使用几次问答后会自动生成"}
              </p>
            </div>
          )}
        </div>

        {tab === "memory" && data && !editing && (
          <p className="text-[11px] text-slate-400 mt-3">
            已沉淀 {data.memoryStats.entries} 条 · {data.memoryStats.chars}/
            {data.memoryStats.maxChars} 字符
          </p>
        )}
      </div>

      <ConfirmDialog
        open={confirmClear}
        title="清空长期记忆核心摘要?"
        description="将清除系统对你的所有理解(关注范围、表达偏好等),会话记录不受影响。此操作不可撤销。"
        confirmText="清空"
        loading={busy}
        onConfirm={handleClearMemory}
        onCancel={() => setConfirmClear(false)}
      />
    </div>
  );
}