DashboardShell.tsx 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. "use client";
  2. import { useCallback, useMemo, useState } from "react";
  3. import dynamic from "next/dynamic";
  4. import { useAuth } from "@/features/agent/hooks/useAuth";
  5. import { useConversations } from "@/features/agent/hooks/useConversations";
  6. import { useMessages } from "@/features/agent/hooks/useMessages";
  7. import { useProfile } from "@/features/agent/hooks/useProfile";
  8. import { Profile } from "@/features/agent/types";
  9. import { ResponsiveLayout } from "@/components/layout";
  10. import { LAYOUT } from "@/lib/constants/breakpoints";
  11. import { ChatHeader } from "./ChatHeader";
  12. import { ConversationSidebar } from "./ConversationSidebar";
  13. import { MessageInput } from "./MessageInput";
  14. import { MessageList } from "./MessageList";
  15. import { NavigationSidebar, type NavigationPage } from "./NavigationSidebar";
  16. import { ProfileModal } from "./ProfileModal";
  17. import { VisitorDetailPanel } from "./VisitorDetailPanel";
  18. // 动态导入其他页面组件
  19. const FAQsPage = dynamic(() => import("@/app/agent/faqs/page").then(mod => ({ default: mod.default })), { ssr: false });
  20. const UsersPage = dynamic(() => import("@/app/agent/users/page").then(mod => ({ default: mod.default })), { ssr: false });
  21. const SettingsPage = dynamic(() => import("@/app/agent/settings/page").then(mod => ({ default: mod.default })), { ssr: false });
  22. export function DashboardShell() {
  23. // 登录状态:负责从本地存储读取客服信息,并提供登出方法
  24. const { agent, loading: authLoading, logout } = useAuth();
  25. // 页面状态管理(必须在所有其他 Hooks 之前声明,确保 Hooks 调用顺序一致)
  26. const [currentPage, setCurrentPage] = useState<NavigationPage>("dashboard");
  27. // 个人资料状态
  28. const [profileModalOpen, setProfileModalOpen] = useState(false);
  29. const {
  30. profile,
  31. loading: profileLoading,
  32. refresh: refreshProfile,
  33. update: updateProfile,
  34. upload: uploadAvatar,
  35. } = useProfile({
  36. userId: agent?.id ?? null,
  37. enabled: Boolean(agent?.id),
  38. });
  39. // 会话过滤状态
  40. const [conversationFilter, setConversationFilter] = useState<"all" | "mine" | "others">("all");
  41. // 会话状态:包含会话列表、搜索关键字、选中的会话等
  42. const {
  43. conversations,
  44. filteredConversations,
  45. selectedConversationId,
  46. searchQuery,
  47. loading,
  48. isInitialLoad,
  49. setSearchQuery,
  50. selectConversation,
  51. updateConversation,
  52. refresh: refreshConversations,
  53. hasConversation,
  54. } = useConversations({
  55. agentId: agent?.id ?? null, // 传递客服ID,用于建立全局 WebSocket 连接
  56. filter: conversationFilter, // 传递过滤类型
  57. });
  58. // 输入框内容与搜索高亮关键字
  59. const [messageInput, setMessageInput] = useState("");
  60. const [highlightKeyword, setHighlightKeyword] = useState("");
  61. // 当前选中的会话信息,供右侧访客详情展示
  62. const selectedConversation = useMemo(
  63. () =>
  64. conversations.find(
  65. (conversation) => conversation.id === selectedConversationId
  66. ) ?? null,
  67. [conversations, selectedConversationId]
  68. );
  69. // 消息层:负责消息列表、未读状态、访客详情以及 WebSocket
  70. const {
  71. messages,
  72. loadingMessages,
  73. sending,
  74. conversationDetail,
  75. refreshConversationDetail,
  76. refreshMessages,
  77. sendMessage,
  78. markMessagesAsRead,
  79. updateContactInfo,
  80. includeAIMessages,
  81. toggleAIMessages,
  82. } = useMessages({
  83. conversationId: selectedConversationId,
  84. agentId: agent?.id ?? null,
  85. updateConversation,
  86. refreshConversations,
  87. hasConversation,
  88. });
  89. // 左侧选择会话时,记录关键字用于消息高亮
  90. const handleConversationSelect = useCallback(
  91. (conversationId: number) => {
  92. if (searchQuery.trim()) {
  93. setHighlightKeyword(searchQuery.trim());
  94. } else {
  95. setHighlightKeyword("");
  96. }
  97. selectConversation(conversationId);
  98. },
  99. [searchQuery, selectConversation]
  100. );
  101. // 发送消息:调用 service 后清空输入框
  102. const handleSendMessage = useCallback(async (fileInfo?: { file_url: string; file_type: string; file_name: string; file_size: number; mime_type: string }) => {
  103. const content = messageInput.trim();
  104. try {
  105. await sendMessage(content, fileInfo);
  106. setMessageInput("");
  107. } catch (error) {
  108. alert((error as Error).message);
  109. }
  110. }, [messageInput, sendMessage]);
  111. // 标记当前会话全部消息为已读
  112. const handleMarkAllRead = useCallback(() => {
  113. if (selectedConversationId) {
  114. markMessagesAsRead(selectedConversationId, true);
  115. }
  116. }, [markMessagesAsRead, selectedConversationId]);
  117. // 手动刷新消息与访客详情
  118. const handleRefreshChat = useCallback(() => {
  119. if (!selectedConversationId) return;
  120. refreshMessages(selectedConversationId);
  121. refreshConversationDetail(selectedConversationId);
  122. }, [refreshConversationDetail, refreshMessages, selectedConversationId]);
  123. // 单独刷新访客详情
  124. const handleRefreshVisitor = useCallback(() => {
  125. if (!selectedConversationId) return;
  126. refreshConversationDetail(selectedConversationId);
  127. }, [refreshConversationDetail, selectedConversationId]);
  128. // 当前会话未读数(优先使用详情返回的数据)
  129. const selectedUnreadCount =
  130. conversationDetail?.unread_count ??
  131. selectedConversation?.unread_count ??
  132. 0;
  133. // 3 秒后清除搜索高亮
  134. const clearHighlight = useCallback(() => {
  135. setHighlightKeyword("");
  136. }, []);
  137. // 处理个人资料更新
  138. const handleProfileUpdate = useCallback(
  139. (updated: Profile) => {
  140. // 个人资料更新后,刷新缓存(这里可以通过更新 agent 状态来触发UI更新)
  141. refreshProfile();
  142. },
  143. [refreshProfile]
  144. );
  145. // 处理导航切换(必须在所有条件返回之前声明)
  146. const handleNavigate = useCallback((page: NavigationPage) => {
  147. setCurrentPage(page);
  148. // 如果切换到非 dashboard 页面,清空选中的对话
  149. if (page !== "dashboard") {
  150. selectConversation(null);
  151. }
  152. }, [selectConversation]);
  153. if (authLoading || (loading && isInitialLoad)) {
  154. return (
  155. <div className="flex justify-center items-center min-h-screen bg-background">
  156. <div className="text-lg text-muted-foreground">加载中...</div>
  157. </div>
  158. );
  159. }
  160. if (!agent) {
  161. return null;
  162. }
  163. // 构建侧边栏内容(包含导航栏和对话列表)
  164. // 在 dashboard 页面时,显示导航栏 + 对话列表
  165. // 在其他页面时,只显示导航栏
  166. const sidebarContent = currentPage === "dashboard" ? (
  167. <div className="flex h-full">
  168. <NavigationSidebar
  169. currentPage={currentPage}
  170. onNavigate={handleNavigate}
  171. onProfileClick={() => setProfileModalOpen(true)}
  172. onLogout={logout}
  173. avatarUrl={profile?.avatar_url}
  174. />
  175. <ConversationSidebar
  176. conversations={filteredConversations}
  177. selectedConversationId={selectedConversationId}
  178. searchQuery={searchQuery}
  179. onSearchChange={setSearchQuery}
  180. onSelectConversation={handleConversationSelect}
  181. filter={conversationFilter}
  182. onFilterChange={setConversationFilter}
  183. />
  184. </div>
  185. ) : (
  186. <div className="flex h-full">
  187. <NavigationSidebar
  188. currentPage={currentPage}
  189. onNavigate={handleNavigate}
  190. onProfileClick={() => setProfileModalOpen(true)}
  191. onLogout={logout}
  192. avatarUrl={profile?.avatar_url}
  193. />
  194. </div>
  195. );
  196. // 构建主内容区
  197. const mainContent = (
  198. <div className="flex-1 flex flex-col bg-background min-h-0">
  199. {currentPage === "dashboard" ? (
  200. selectedConversationId ? (
  201. <>
  202. <ChatHeader
  203. conversationId={selectedConversationId}
  204. lastSeenAt={conversationDetail?.last_seen_at}
  205. unreadCount={selectedUnreadCount}
  206. onMarkAllRead={handleMarkAllRead}
  207. onRefresh={handleRefreshChat}
  208. includeAIMessages={includeAIMessages}
  209. onToggleAIMessages={toggleAIMessages}
  210. />
  211. <MessageList
  212. messages={messages}
  213. loading={loadingMessages}
  214. highlightKeyword={highlightKeyword}
  215. onHighlightClear={clearHighlight}
  216. currentUserIsAgent={true}
  217. conversationId={selectedConversationId ?? null}
  218. onMarkMessagesRead={markMessagesAsRead}
  219. />
  220. <MessageInput
  221. value={messageInput}
  222. onChange={setMessageInput}
  223. onSubmit={handleSendMessage}
  224. sending={sending}
  225. conversationId={selectedConversationId ?? undefined}
  226. />
  227. </>
  228. ) : (
  229. <div className="flex-1 flex items-center justify-center text-muted-foreground text-sm">
  230. 选择一个对话开始聊天
  231. </div>
  232. )
  233. ) : (
  234. <div className="flex-1 flex flex-col min-h-0 overflow-hidden">
  235. {currentPage === "faqs" && <FAQsPage embedded={true} />}
  236. {currentPage === "users" && <UsersPage embedded={true} />}
  237. {currentPage === "settings" && <SettingsPage embedded={true} />}
  238. </div>
  239. )}
  240. </div>
  241. );
  242. // 构建右侧面板(仅在 dashboard 页面且选中对话时显示)
  243. const rightPanelContent = currentPage === "dashboard" && selectedConversationId ? (
  244. <VisitorDetailPanel
  245. conversation={selectedConversation}
  246. detail={conversationDetail}
  247. onRefresh={handleRefreshVisitor}
  248. onUpdateContact={updateContactInfo}
  249. />
  250. ) : undefined;
  251. return (
  252. <>
  253. <ResponsiveLayout
  254. sidebar={sidebarContent}
  255. main={mainContent}
  256. rightPanel={rightPanelContent}
  257. sidebarWidth={currentPage === "dashboard" ? undefined : LAYOUT.navigationWidth}
  258. />
  259. {/* 个人资料弹窗 */}
  260. <ProfileModal
  261. profile={profile}
  262. open={profileModalOpen}
  263. onClose={() => setProfileModalOpen(false)}
  264. onUpdate={handleProfileUpdate}
  265. />
  266. </>
  267. );
  268. }