280 lines
8.6 KiB
JavaScript
280 lines
8.6 KiB
JavaScript
import {getChatRegisterInfoApi, getMessagesByRoomIdApi} from "@/request/api/im";
|
||
|
||
/**
|
||
* 聊天消息管理器
|
||
* @type {{currentRoomId: null, lastMessageId: null, unreadCounts: {}, messageCache: {}, roomMessages: {}, enterRoom(*): void, leaveRoom(): void, getCurrentRoomId(): *, increaseUnreadCount(*): void, resetUnreadCount(*): void, getUnreadCount(*): *, getAllUnreadCount(): *, loadHistory(): *, getMessageType(): *, notifyUnreadChange(): void,, addMessageToRoom(*, *): void, getRoomMessages(*): *, handleIncomingMessage(*): void}}
|
||
*/
|
||
const ChatManager = {
|
||
// 当前房间ID
|
||
currentRoomId: null,
|
||
|
||
lastMessageId: 0,
|
||
|
||
// 存储未读消息数 { roomId: count }
|
||
unreadCounts: {},
|
||
|
||
// 消息缓存 { roomId: [message1, message2, ...] }
|
||
messageCache: {},
|
||
|
||
// 房间消息存储 { roomId: [message1, message2, ...] }
|
||
roomMessages: {},
|
||
|
||
// 进入聊天室
|
||
enterRoom(roomId) {
|
||
this.currentRoomId = roomId;
|
||
uni.setStorageSync('currentRoomId', roomId);
|
||
console.log(`进入房间`);
|
||
// 重置当前房间的未读消息
|
||
this.resetUnreadCount(roomId);
|
||
},
|
||
|
||
// 离开聊天室
|
||
leaveRoom() {
|
||
this.currentRoomId = null;
|
||
uni.removeStorageSync('currentRoomId');
|
||
console.log('离开当前房间');
|
||
},
|
||
|
||
// 获取当前房间ID
|
||
getCurrentRoomId() {
|
||
return this.currentRoomId || uni.getStorageSync('currentRoomId');
|
||
},
|
||
|
||
// 增加未读消息数
|
||
increaseUnreadCount(roomId) {
|
||
// 如果当前不在该房间,才增加未读计数
|
||
if (this.getCurrentRoomId() !== roomId) {
|
||
this.unreadCounts[roomId] = (this.unreadCounts[roomId] || 0) + 1;
|
||
this.notifyUnreadChange();
|
||
console.log(`房间 ${roomId} 未读消息 +1, 当前: ${this.unreadCounts[roomId]}`);
|
||
}
|
||
},
|
||
|
||
// 重置未读消息数
|
||
resetUnreadCount(roomId) {
|
||
if (this.unreadCounts[roomId]) {
|
||
this.unreadCounts[roomId] = 0;
|
||
this.notifyUnreadChange();
|
||
console.log(`重置房间 ${roomId} 未读消息数`);
|
||
}
|
||
},
|
||
|
||
// 获取未读消息数
|
||
getUnreadCount(roomId) {
|
||
return this.unreadCounts[roomId] || 0;
|
||
},
|
||
|
||
// 获取所有未读消息数
|
||
getAllUnreadCount() {
|
||
return Object.values(this.unreadCounts).reduce((sum, count) => sum + count, 0);
|
||
},
|
||
|
||
// 通知未读消息变化
|
||
notifyUnreadChange() {
|
||
uni.$emit('unread-message-update', {
|
||
total: this.getAllUnreadCount(),
|
||
byRoom: {...this.unreadCounts}
|
||
});
|
||
},
|
||
|
||
// 添加消息到房间
|
||
addMessageToRoom(roomId, message) {
|
||
if (!this.roomMessages[roomId]) {
|
||
this.roomMessages[roomId] = [];
|
||
}
|
||
this.roomMessages[roomId].push(message);
|
||
console.log('addMessageToRoom', this.roomMessages[roomId])
|
||
},
|
||
|
||
// 获取房间消息
|
||
getRoomMessages(roomId) {
|
||
let that = this;
|
||
this.roomMessages[roomId] = [];
|
||
getMessagesByRoomIdApi({
|
||
room_id: roomId,
|
||
last_message_id: 0,
|
||
}).then((res) => {
|
||
that.roomMessages[roomId] = that.checkMessage(res.data.result.list);
|
||
that.lastMessageId = res.data.result.last_message_id;
|
||
console.log(that.roomMessages[roomId], 'roomMessages')
|
||
|
||
uni.$emit('load-room-message', 1);
|
||
return this.roomMessages[roomId] || [];
|
||
})
|
||
return this.roomMessages[roomId] || [];
|
||
|
||
},
|
||
|
||
checkMessage(message, type = 0) {
|
||
if (type === 1) {
|
||
return {
|
||
id: message.id,
|
||
sender: message.sender_user_id,
|
||
type: this.getMessageType(message.message_type),
|
||
// type: message.type,
|
||
content:
|
||
item.message_type === 4 || item.message_type === 10
|
||
? JSON.parse(item.message_content)
|
||
: item.message_content,
|
||
duration: message.duration,
|
||
time: this.formatTime(message.send_time),
|
||
timestamp: message.send_time
|
||
};
|
||
}
|
||
return message.map((item, index) => {
|
||
let msg = item.message_type === 4 || item.message_type === 10
|
||
? JSON.parse(item.message_content)
|
||
: item.message_content;
|
||
|
||
if (item.message_type === 10) {
|
||
this.getChatRegisterInfo(msg, index)
|
||
}
|
||
return {
|
||
id: item.id,
|
||
sender: item.sender_user_id,
|
||
type: this.getMessageType(item.message_type),
|
||
content: msg,
|
||
duration: item.duration,
|
||
time: item?.created_at_text || item.send_time,
|
||
timestamp: item?.created_at || item.send_time
|
||
};
|
||
});
|
||
},
|
||
|
||
// 根据消息类型ID获取类型名称
|
||
getMessageType(typeId) {
|
||
const types = {
|
||
0: 'text',
|
||
1: 'image',
|
||
2: 'audio',
|
||
3: 'video',
|
||
4: 'prescription',
|
||
5: 'file',
|
||
10: 'register',
|
||
};
|
||
return types[typeId];
|
||
},
|
||
|
||
/**
|
||
* 获取挂号信息卡片
|
||
* @param item
|
||
* @param index
|
||
* @returns {*}
|
||
*/
|
||
getChatRegisterInfo(item, index) {
|
||
let that = this;
|
||
getChatRegisterInfoApi({
|
||
id: item.id
|
||
}).then((res) => {
|
||
console.log(that.roomMessages, 'ssssssssssss1')
|
||
console.log(that.currentRoomId, 'ssssssssssss2')
|
||
console.log(index, 'ssssssssssss3')
|
||
console.log(that.roomMessages[that.currentRoomId][index], 'ssssssssssss4')
|
||
that.roomMessages[that.currentRoomId][index].content = res.data.result;
|
||
console.log('getChatRegisterInfo', that.roomMessages[that.currentRoomId][index].content)
|
||
// return res.data.result
|
||
})
|
||
},
|
||
|
||
// 格式化时间
|
||
formatTime(timestamp) {
|
||
let date;
|
||
|
||
// 处理不同输入类型
|
||
if (typeof timestamp === 'number') {
|
||
// 数字直接作为时间戳处理
|
||
date = new Date(timestamp);
|
||
} else if (timestamp instanceof Date) {
|
||
// Date对象直接使用
|
||
date = timestamp;
|
||
} else if (typeof timestamp === 'string') {
|
||
// 字符串类型:尝试转换为时间戳
|
||
const parsed = Date.parse(timestamp);
|
||
if (isNaN(parsed)) {
|
||
// 转换失败则使用当前时间
|
||
date = new Date();
|
||
} else {
|
||
date = new Date(parsed);
|
||
}
|
||
} else {
|
||
// 其他类型使用当前时间
|
||
date = new Date();
|
||
}
|
||
|
||
const now = new Date();
|
||
const diff = now - date; // 时间差(毫秒)
|
||
const seconds = Math.floor(diff / 1000);
|
||
|
||
// 定义星期几的名称
|
||
const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
|
||
const currentWeekday = date.getDay(); // 0=周日,1=周一,...,6=周六
|
||
|
||
// 格式化时间函数 (补零)
|
||
const formatTime = (num) => num.toString().padStart(2, '0');
|
||
const formattedTime = `${formatTime(date.getHours())}:${formatTime(date.getMinutes())}`;
|
||
|
||
if (seconds < 60) {
|
||
return '刚刚';
|
||
} else if (seconds < 3600) {
|
||
return Math.floor(seconds / 60) + '分钟前';
|
||
} else if (seconds < 7200) { // 1-2小时
|
||
return Math.floor(seconds / 3600) + '小时前';
|
||
} else if (seconds < 86400) { // 2-24小时
|
||
return formattedTime;
|
||
} else if (seconds < 172800) { // 1-2天(昨天)
|
||
return `昨天 ${formattedTime}`;
|
||
} else if (seconds < 259200) { // 2-3天(前天)
|
||
return `前天 ${formattedTime}`;
|
||
} else if (seconds < 604800) { // 3-7天内(本周X)
|
||
return `周${weekdays[currentWeekday]} ${formattedTime}`;
|
||
} else if (seconds < 1209600) { // 7-14天(上周X)
|
||
return `上周${weekdays[currentWeekday]} ${formattedTime}`;
|
||
} else if (seconds < 2592000) { // 14天-1个月
|
||
return Math.floor(seconds / 86400) + '天前';
|
||
} else if (seconds < 31536000) { // 1个月-1年
|
||
return Math.floor(seconds / 2592000) + '个月前';
|
||
} else { // 超过1年
|
||
return `${date.getFullYear()}-${formatTime(date.getMonth() + 1)}-${formatTime(date.getDate())}`;
|
||
}
|
||
},
|
||
|
||
loadHistory(roomId) {
|
||
let that = this;
|
||
getMessagesByRoomIdApi({
|
||
room_id: roomId,
|
||
last_message_id: that.lastMessageId,
|
||
}).then((res) => {
|
||
|
||
if (res.data.result.list?.length === 0) {
|
||
// 没有更多历史消息
|
||
uni.$emit('no-more-history');
|
||
return;
|
||
}
|
||
that.roomMessages[roomId] = [...that.checkMessage(res.data.result.list), ...that.roomMessages[roomId]];
|
||
that.lastMessageId = res.data.result.last_message_id;
|
||
|
||
uni.$emit('load-room-message');
|
||
return res.data.result.list
|
||
})
|
||
},
|
||
|
||
// 处理收到的消息
|
||
handleIncomingMessage(message) {
|
||
const roomId = message.room_id;
|
||
const currentRoomId = this.getCurrentRoomId();
|
||
|
||
// 添加消息到房间
|
||
this.addMessageToRoom(roomId, this.checkMessage(message, 1));
|
||
|
||
// 如果当前在消息所属的房间,直接显示
|
||
if (currentRoomId === roomId) {
|
||
// 通知聊天页面显示消息
|
||
uni.$emit('new-room-message', this.checkMessage(message, 1));
|
||
} else {
|
||
// 不在当前房间,缓存消息并增加未读消息数
|
||
this.increaseUnreadCount(roomId);
|
||
}
|
||
}
|
||
};
|
||
|
||
export { ChatManager }; |