本地备份:消息系统改造前完整版本(未推送,便于回退)

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
XingQue
2026-06-29 04:18:48 +08:00
parent 848c2f6486
commit 9976bc1d6d
46 changed files with 2004 additions and 1060 deletions

View File

@@ -1,8 +1,10 @@
const app = getApp();
import { formatDate } from '../../static/lib/utils';
import { sendGroupMessage } from '../../utils/message-sender';
import { getLocalImUserId } from '../../utils/im-user.js';
import { resolveAvatarUrl } from '../../utils/avatar.js';
import { showConfirmByScene } from '../../utils/scriptService.js';
import { normalizeGroupMessage, getZhuangtaiText } from '../../utils/group-chat.js';
import { persistGroupMeta } from '../../utils/im-user.js';
import { getFreshImUser } from '../../utils/im-user.js';
Page({
data: {
@@ -11,6 +13,10 @@ Page({
groupAvatar: '',
orderId: '',
isCross: 0,
orderZhuangtai: null,
orderZhuangtaiText: '',
orderJine: '',
orderJieshao: '',
currentUser: null,
messages: [],
inputText: '',
@@ -28,7 +34,6 @@ Page({
lastTapMsgId: '',
emojiList: ['😀','😁','😂','🤣','😃','😄','😅','😆','😉','😊','😋','😎','😍','😘','😗','😙','😚','🙂','🤗','🤩','🤔','🤨','😐','😑','😶','🙄','😏','😣','😥','😮','🤐','😯','😪','😫','😴','😌','😛','😜','😝','🤤','😒','😓','😔','😕','🙃','🤑','😲','☹','🙁','😖','😞','😟','😤','😢','😭','😦','😧','😨','😩','🤯','😬','😰','😱','🥵','🥶','😳','🤪','😵','😡','😠','🤬','😷','🤒','🤕','🤢','🤮','🤧','😇','🤠','🤡','🤥','🤫','🤭','🧐','🤓','😈','👿','👹','👺','💀','👻','👽','🤖','💩','😺','😸','😹','😻','😼','😽','🙀','😿','😾'],
pendingImage: '',
pendingImageFile: null,
keyboardHeight: 0,
bottomSafeHeight: 10
},
@@ -41,111 +46,164 @@ Page({
p = { ...p, ...d };
} catch (e) {}
}
const orderId = String(p.orderId || p.groupId || '');
const groupId = String(p.groupId || p.orderId || '');
this.setData({
groupId,
groupId: p.groupId,
groupName: p.groupName,
groupAvatar: p.groupAvatar,
orderId,
isCross: p.isCross,
orderId: p.orderId,
isCross: p.isCross
});
wx.setNavigationBarTitle({ title: this.data.groupName });
const localImId = getLocalImUserId(app);
const userId = localImId || p.currentUserId;
if (userId) {
// 如果有外部传入的 currentUser 信息,直接用,不再依赖全局状态
if (p.currentUserId) {
this.setData({
currentUser: {
id: userId,
name: p.currentUserName || app.globalData.currentUser?.name || `用户${wx.getStorageSync('uid') || ''}`,
avatar: resolveAvatarUrl(p.currentUserAvatar || wx.getStorageSync('touxiang'), app),
},
id: p.currentUserId,
name: p.currentUserName || `用户${p.currentUserId.replace(/^[A-Za-z]+/,'')}`,
avatar: p.currentUserAvatar || (app.globalData.ossImageUrl + app.globalData.morentouxiang)
}
});
} else {
this.initCurrentUser();
}
},
initCurrentUser() {
const imId = getLocalImUserId(app);
const uid = wx.getStorageSync('uid');
if (!imId) return;
this.setData({
currentUser: {
id: imId,
name: app.globalData.currentUser?.name || wx.getStorageSync('nicheng') || `用户${uid}`,
avatar: resolveAvatarUrl(wx.getStorageSync('touxiang'), app),
},
});
},
buildImageFile(tempPath, size) {
return {
path: tempPath,
tempFilePath: tempPath,
size: size || 0,
};
},
normalizeMessage(msg) {
if (!msg) return msg;
if (!msg.payload) msg.payload = {};
if (msg.type === 'image') {
const p = msg.payload;
if (!p.url) p.url = p.thumbnail || p.thumb || p.imageUrl || '';
const meta = (app.globalData.groupInfoMap && app.globalData.groupInfoMap[p.groupId]) || {};
const initZt = p.orderZhuangtai != null ? p.orderZhuangtai : meta.orderZhuangtai;
if (initZt != null) {
this.applyOrderStatus(initZt, {
orderId: p.orderId || meta.orderId,
jine: p.orderJine || meta.orderJine,
jieshao: p.orderDesc || meta.orderDesc,
});
}
return msg;
},
mergeSentMessage(localId, sent) {
if (!sent) {
this.updateMsg(localId, 'success');
onShow() {
app.globalData.pageState.isInChatPage = true;
app.globalData.pageState.currentChatId = this.data.groupId;
app.globalData.pageState.isInGroupChat = true;
this.ensureChatConnection();
},
onHide() {
app.globalData.pageState.isInChatPage = false;
app.globalData.pageState.currentChatId = '';
app.globalData.pageState.isInGroupChat = false;
this.clearPageListeners();
},
applyOrderStatus(zhuangtai, extra) {
if (zhuangtai == null && zhuangtai !== 0) return;
const patch = {
orderZhuangtai: zhuangtai,
orderZhuangtaiText: getZhuangtaiText(zhuangtai),
};
if (extra) {
if (extra.jine) patch.orderJine = extra.jine;
if (extra.jieshao) patch.orderJieshao = extra.jieshao;
if (extra.orderId) patch.orderId = extra.orderId;
}
this.setData(patch);
const groupId = this.data.groupId;
if (!groupId) return;
if (!app.globalData.groupInfoMap) app.globalData.groupInfoMap = {};
const meta = { ...(app.globalData.groupInfoMap[groupId] || {}), orderZhuangtai: zhuangtai };
if (extra && extra.orderId) meta.orderId = extra.orderId;
app.globalData.groupInfoMap[groupId] = meta;
persistGroupMeta(app, groupId, meta);
},
applyOrderCardPayload(payload) {
if (!payload) return;
const cardOrderId = payload.orderId || payload.dingdan_id;
if (cardOrderId && this.data.orderId && cardOrderId !== this.data.orderId) return;
const zt = payload.zhuangtai != null ? payload.zhuangtai : this.data.orderZhuangtai;
payload.zhuangtaiText = getZhuangtaiText(zt);
this.applyOrderStatus(zt, {
orderId: payload.orderId || payload.dingdan_id || this.data.orderId,
jine: payload.jine,
jieshao: payload.jieshao,
});
this.updateOrderBubblesInList(payload);
},
updateOrderBubblesInList(payload) {
if (!payload) return;
const orderId = payload.orderId || payload.dingdan_id;
if (!orderId) return;
const messages = this.data.messages.map((m) => {
if (m.type !== 'order' || !m.payload) return m;
const oid = m.payload.orderId || m.payload.dingdan_id;
if (oid !== orderId) return m;
return { ...m, payload: { ...m.payload, ...payload, orderId: oid } };
});
this.setData({ messages });
},
mergeServerMessage(localId, status, serverMsg) {
if (!serverMsg) {
this.updateMsg(localId, status);
return;
}
normalizeGroupMessage(serverMsg);
serverMsg.formattedTime = formatDate(serverMsg.timestamp);
if (serverMsg.type === 'order') {
this.applyOrderCardPayload(serverMsg.payload);
}
const msgs = this.data.messages.map((m) => {
if (m.messageId !== localId) return m;
return this.normalizeMessage({
...m,
...sent,
status: 'success',
messageId: sent.messageId || m.messageId,
payload: sent.payload || m.payload,
senderData: m.senderData || sent.senderData,
});
return {
...serverMsg,
showTime: m.showTime,
status: status || 'success',
formattedTime: serverMsg.formattedTime || m.formattedTime,
};
});
this.setData({ messages: msgs });
},
onShow() {
this.autoConnect();
},
async ensureChatConnection() {
const role = app.globalData.currentRole || 'normal';
const uid = wx.getStorageSync('uid');
const prefixMap = { normal:'Boss', dashou:'Ds', shangjia:'Sj', guanshi:'Gs', zuzhang:'Zz', kaoheguan:'Kh' };
const pageUserId = this.data.currentUser?.id;
const targetUserId = pageUserId || (prefixMap[role] || 'Boss') + uid;
onHide() {
this.clearAllListeners();
},
autoConnect() {
const targetUserId = this.data.currentUser?.id || getLocalImUserId(app);
if (!targetUserId) return;
const afterReady = () => {
this.subscribeGroupIfNeeded().then(() => {
this.setupAllListeners();
this.loadHistory(true);
this.markGroupMessageAsRead();
});
const onReady = () => {
this.subscribeGroupIfNeeded()
.then(() => {
this.setupAllListeners();
return this.loadHistory(true);
})
.then(() => this.markGroupMessageAsRead());
};
const status = wx.goEasy.getConnectionStatus ? wx.goEasy.getConnectionStatus() : 'disconnected';
if (status === 'connected' || status === 'reconnected') {
const currentUserId = wx.goEasy.im ? wx.goEasy.im.userId : null;
if (currentUserId === targetUserId) {
afterReady();
return;
}
wx.goEasy.disconnect();
const connectedId = app.globalData?.goEasyConnection?.userId || wx.goEasy?.im?.userId;
const status = wx.goEasy?.getConnectionStatus?.() || 'disconnected';
const imOk = status === 'connected' || status === 'reconnected';
if (imOk && connectedId === targetUserId) {
onReady();
return;
}
this.connectGoEasy(targetUserId);
try {
if (app.ensureImForRole) {
await app.ensureImForRole(role);
} else if (app.connectWithIdentity) {
await app.connectWithIdentity(role, targetUserId, true);
}
onReady();
} catch (e) {
const s = wx.goEasy?.getConnectionStatus?.();
if (s === 'connected' || s === 'reconnected') onReady();
else wx.showToast({ title: '连接失败,请重试', icon: 'none' });
}
},
clearPageListeners() {
this.clearAllListeners();
},
connectGoEasy(userId) {
@@ -155,14 +213,15 @@ Page({
id: userId,
data: {
name: currentUser.name,
avatar: resolveAvatarUrl(currentUser.avatar, app),
avatar: currentUser.avatar || (app.globalData.ossImageUrl + app.globalData.morentouxiang)
},
onSuccess: () => {
this.subscribeGroupIfNeeded().then(() => {
this.setupAllListeners();
this.loadHistory(true);
this.markGroupMessageAsRead();
});
this.subscribeGroupIfNeeded()
.then(() => {
this.setupAllListeners();
return this.loadHistory(true);
})
.then(() => this.markGroupMessageAsRead());
},
onFailed: (error) => {
if (error.code === 408) {
@@ -179,14 +238,17 @@ Page({
subscribeGroupIfNeeded() {
const { groupId } = this.data;
if (!groupId || !wx.goEasy?.im?.subscribeGroup) return Promise.resolve();
if (!groupId || !wx.goEasy?.im) return Promise.resolve();
return new Promise((resolve) => {
wx.goEasy.im.subscribeGroup({
groupIds: [String(groupId)],
onSuccess: () => resolve(true),
onFailed: (error) => {
console.warn('subscribeGroup failed', error);
resolve(false);
groupIds: [groupId],
onSuccess: () => {
console.log(`[群聊页] 订阅成功: ${groupId}`);
resolve();
},
onFailed: (err) => {
console.error(`[群聊页] 订阅失败: ${groupId}`, err);
resolve();
},
});
});
@@ -205,6 +267,23 @@ Page({
if (this._deleteHandler) { wx.goEasy.im.off(wx.GoEasy.IM_EVENT.MESSAGE_DELETED, this._deleteHandler); this._deleteHandler = null; }
},
initCurrentUser() {
const uid = wx.getStorageSync('uid');
const role = app.globalData.currentRole || 'normal';
const fresh = getFreshImUser(app, role, uid);
this.setData({ currentUser: {
id: fresh.id,
name: fresh.name,
avatar: fresh.avatar,
}});
},
fixAvatar(url) {
if (!url) return app.globalData.ossImageUrl + app.globalData.morentouxiang;
if (url.startsWith('http')) return url;
return app.globalData.ossImageUrl + url;
},
isConnected() {
const s = wx.goEasy.getConnectionStatus ? wx.goEasy.getConnectionStatus() : 'disconnected';
return s === 'connected' || s === 'reconnected';
@@ -231,12 +310,14 @@ Page({
let list = res.content || [];
list.sort((a, b) => a.timestamp - b.timestamp);
list.forEach((m, idx) => {
m = this.normalizeMessage(m);
list[idx] = m;
normalizeGroupMessage(m);
m.formattedTime = formatDate(m.timestamp);
if (idx === 0) m.showTime = true;
else m.showTime = (m.timestamp - list[idx-1].timestamp) / 60000 > 5;
if (!m.senderData) m.senderData = { name: '未知用户', avatar: '' };
if (m.type === 'order' && m.payload) {
this.applyOrderCardPayload(m.payload);
}
});
let final = refresh ? list : [...list, ...this.data.messages];
if (!refresh) {
@@ -267,17 +348,21 @@ Page({
if (this._msgHandler) wx.goEasy.im.off(wx.GoEasy.IM_EVENT.GROUP_MESSAGE_RECEIVED, this._msgHandler);
this._msgHandler = (msg) => {
if (msg.groupId !== this.data.groupId) return;
if (msg.senderId === this.data.currentUser.id) return;
msg = this.normalizeMessage(msg);
normalizeGroupMessage(msg);
if (msg.type === 'order' && msg.payload) {
this.applyOrderCardPayload(msg.payload);
}
if (msg.senderId === this.data.currentUser.id && msg.type !== 'order') return;
msg.formattedTime = formatDate(msg.timestamp);
const msgs = this.data.messages;
if (msgs.some((m) => m.messageId === msg.messageId)) return;
const last = msgs.length ? msgs[msgs.length-1] : null;
msg.showTime = last ? (msg.timestamp - last.timestamp) / 60000 > 5 : true;
this.setData({ messages: [...msgs, msg], scrollToView: 'msg-bottom' });
this.markGroupMessageAsRead();
};
wx.goEasy.im.on(wx.GoEasy.IM_EVENT.GROUP_MESSAGE_RECEIVED, this._msgHandler);
this.markGroupMessageAsRead();
this.markGroupMessageAsRead(); // ← 收到新消息就标记已读
},
markGroupMessageAsRead() {
@@ -312,31 +397,21 @@ Page({
chooseImage() {
const that = this;
wx.chooseMedia({
count: 1,
mediaType: ['image'],
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success(res) {
const file = (res.tempFiles && res.tempFiles[0]) || null;
if (!file || !file.tempFilePath) return;
that.setData({
pendingImage: file.tempFilePath,
pendingImageFile: that.buildImageFile(file.tempFilePath, file.size),
});
},
fail() {
wx.showToast({ title: '选择图片失败', icon: 'none' });
},
wx.chooseImage({
count: 1, sizeType: ['compressed'], sourceType: ['album', 'camera'],
success(res) { that.setData({ pendingImage: res.tempFilePaths[0] }); }
});
},
clearPendingImage() { this.setData({ pendingImage: '', pendingImageFile: null }); },
clearPendingImage() { this.setData({ pendingImage: '' }); },
sendMessage() {
if (this.data.pendingImage) {
this.sendImageMsg(this.data.pendingImage, this.data.pendingImageFile);
this.setData({ pendingImage: '', pendingImageFile: null });
const file = this.data.pendingImage;
showConfirmByScene('chat_image_confirm', () => {
this.sendImageMsg(file);
this.setData({ pendingImage: '' });
});
return;
}
const text = this.data.inputText.trim();
@@ -367,61 +442,18 @@ Page({
}
that.setData({ messages: [...msgs, localMsg], scrollToView: 'msg-bottom' });
},
onSuccess: (messageId, status) => {
that.updateMsg(messageId, status);
onSuccess: (messageId, status, serverMsg) => {
that.mergeServerMessage(messageId, status, serverMsg);
}
});
},
sendImageMsg(filePath, fileObj) {
sendImageMsg(file) {
const that = this;
const { currentUser, groupId, orderId, isCross, groupName, groupAvatar } = that.data;
if (!filePath || !currentUser || !groupId) return;
if (isCross === 0) {
if (!wx.goEasy || !wx.goEasy.im) {
wx.showToast({ title: '聊天未连接', icon: 'none' });
return;
}
const avatar = resolveAvatarUrl(currentUser.avatar, app);
const name = currentUser.name || '用户';
const localId = `image-${Date.now()}`;
const imageFile = fileObj || this.buildImageFile(filePath, 0);
const localMsg = {
messageId: localId,
type: 'image',
timestamp: Date.now(),
senderId: currentUser.id,
groupId,
senderData: { name, avatar },
payload: { url: filePath },
status: 'sending',
formattedTime: formatDate(Date.now()),
showTime: this.needShow(Date.now()),
};
that.setData({ messages: [...that.data.messages, localMsg], scrollToView: 'msg-bottom' });
const toData = { name: groupName || '订单群聊', avatar: groupAvatar || avatar, isCross: 0 };
if (orderId) toData.orderId = orderId;
const imgMsg = wx.goEasy.im.createImageMessage({
file: imageFile,
to: { type: wx.GoEasy.IM_SCENE.GROUP, id: groupId, data: toData },
});
wx.goEasy.im.sendMessage({
message: imgMsg,
onSuccess: (sent) => that.mergeSentMessage(localId, sent),
onFailed: (error) => {
console.error('[群聊] 图片发送失败', error);
that.updateMsg(localId, 'failed');
wx.showToast({ title: '图片发送失败', icon: 'none' });
},
});
return;
}
sendGroupMessage({
msgData: {
type: 'image',
filePath,
filePath: file,
currentUser: that.data.currentUser,
groupId: that.data.groupId,
orderId: that.data.orderId,
@@ -438,11 +470,8 @@ Page({
}
that.setData({ messages: [...msgs, localMsg], scrollToView: 'msg-bottom' });
},
onSuccess: (messageId, status) => {
that.updateMsg(messageId, status);
if (status === 'failed') {
wx.showToast({ title: '图片发送失败', icon: 'none' });
}
onSuccess: (messageId, status, serverMsg) => {
that.mergeServerMessage(messageId, status, serverMsg);
}
});
},
@@ -477,7 +506,7 @@ Page({
const msgId = e.currentTarget.dataset.messageid;
if (!msgId) return;
const msg = this.data.messages.find(m => m.messageId === msgId);
if (!msg || msg.messageId.startsWith('local-')) return;
if (!msg || String(msg.messageId).startsWith('local-')) return;
const itemList = ['复制'];
if (msg.senderId === this.data.currentUser.id && (Date.now() - msg.timestamp < 120000) && !msg.recalled) {
itemList.push('撤回');