63 lines
2.4 KiB
JavaScript
63 lines
2.4 KiB
JavaScript
import { defineStore } from "pinia";
|
||
import { messageService } from "@/services/message";
|
||
import { conversationDb } from "@/utils/db/conversationDB";
|
||
import { useMessage } from "@/components/messages/useAlert";
|
||
|
||
const message = useMessage();
|
||
|
||
export const useConversationStore = defineStore('conversation', {
|
||
state: () => ({
|
||
conversations: []
|
||
}),
|
||
actions: {
|
||
async addConversation(conversation) {
|
||
await conversationDb.save(conversation);
|
||
this.conversations.unshift(conversation)
|
||
},
|
||
/**
|
||
* 加载当前会话消息列表
|
||
*/
|
||
async loadUserConversations() {
|
||
if (this.conversations.length == 0) {
|
||
try {
|
||
const covnersationsCache = await conversationDb.getAll();
|
||
if (covnersationsCache && covnersationsCache.length > 0) {
|
||
covnersationsCache.sort((a, b) => {
|
||
return new Date(a.dateTime) - new Date(b.dateTime);
|
||
})
|
||
}
|
||
} catch (e) {
|
||
message.error('读取本地会话缓存失败...');
|
||
console.log('读取本地会话缓存失败:', e);
|
||
}
|
||
}
|
||
await this.fetchConversationsFromServier()
|
||
},
|
||
/**
|
||
* 从服务器加载新消息
|
||
* @param {*} sessionId
|
||
* @returns
|
||
*/
|
||
async fetchConversationsFromServier() {
|
||
const newConversations = (await messageService.getConversations()).data;
|
||
if (newConversations.length > 0) {
|
||
// 1. 将当前的本地数据转为 Map,方便通过 ID 快速查找 (O(1) 复杂度)
|
||
const localMap = new Map(this.conversations.map(item => [item.id, item]));
|
||
newConversations.forEach(item => {
|
||
const existingItem = localMap.get(item.id);
|
||
if (existingItem) {
|
||
// --- 局部更新 ---
|
||
// 使用 Object.assign 将新数据合并到旧对象上,保持响应式引用
|
||
Object.assign(existingItem, item);
|
||
} else {
|
||
// --- 插入新会话 ---
|
||
this.conversations.unshift(item);
|
||
}
|
||
// 同步到本地数据库
|
||
conversationDb.save(item);
|
||
});
|
||
|
||
}
|
||
}
|
||
}
|
||
}) |