/** * 消息发送服务 * 处理消息发送相关逻辑 */ import type { MessageResponse, MessageSegment, ConversationResponse } from '../../../types/dto'; import { messageService } from '@/services/message'; import { messageRepository } from '@/database'; import type { IMessageSendService } from '../types'; import { useMessageStore } from '../store'; export class MessageSendService implements IMessageSendService { private getCurrentUserId: () => string | null; constructor(getCurrentUserId: () => string | null) { this.getCurrentUserId = getCurrentUserId; } /** * 发送消息 */ async sendMessage( conversationId: string, segments: MessageSegment[], options?: { replyToId?: string } ): Promise { const store = useMessageStore.getState(); try { // 调用API发送 const response = await messageService.sendMessage(conversationId, { segments, reply_to_id: options?.replyToId, }); if (response) { const currentUserId = this.getCurrentUserId(); // 原子性合并新消息到内存(防止并发 WS 消息丢失) const newMessage: MessageResponse = { id: response.id, conversation_id: conversationId, sender_id: currentUserId || '', seq: response.seq, segments, created_at: new Date().toISOString(), status: 'normal', }; store.mergeMessages(conversationId, [newMessage]); // 更新会话最后消息 this.updateConversationWithNewMessage(conversationId, newMessage); // 保存到本地数据库 const textContent = segments ?.filter((s: any) => s.type === 'text') .map((s: any) => s.data?.text || '') .join('') || ''; messageRepository.saveMessage({ id: response.id, conversationId, senderId: currentUserId || '', content: textContent, type: segments?.find((s: any) => s.type === 'image') ? 'image' : 'text', isRead: true, createdAt: newMessage.created_at, seq: response.seq, status: 'normal', segments, }).catch(console.error); return newMessage; } return null; } catch (error) { console.error('[MessageSendService] 发送消息失败:', error); return null; } } /** * 更新会话的最后消息信息 */ private updateConversationWithNewMessage( conversationId: string, message: MessageResponse ): void { const store = useMessageStore.getState(); const conversation = store.getConversation(conversationId); const createdAt = message.created_at || new Date().toISOString(); if (conversation) { // 更新现有会话 const updatedConv: ConversationResponse = { ...conversation, last_seq: message.seq, last_message: message, last_message_at: createdAt, updated_at: createdAt, }; store.updateConversation(updatedConv); } } }