修复消息监听角标、历史记录加载与重复订单卡片推送
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -2,7 +2,8 @@ const app = getApp();
|
||||
import { formatDate } from '../../static/lib/utils';
|
||||
import { sendGroupMessage } from '../../utils/message-sender';
|
||||
import { showConfirmByScene } from '../../utils/scriptService.js';
|
||||
import { normalizeGroupMessage } from '../../utils/group-chat.js';
|
||||
import { normalizeGroupMessage, getZhuangtaiText } from '../../utils/group-chat.js';
|
||||
import { persistGroupMeta } from '../../utils/im-user.js';
|
||||
import { getFreshImUser } from '../../utils/im-user.js';
|
||||
|
||||
Page({
|
||||
@@ -12,6 +13,10 @@ Page({
|
||||
groupAvatar: '',
|
||||
orderId: '',
|
||||
isCross: 0,
|
||||
orderZhuangtai: null,
|
||||
orderZhuangtaiText: '',
|
||||
orderJine: '',
|
||||
orderJieshao: '',
|
||||
currentUser: null,
|
||||
messages: [],
|
||||
inputText: '',
|
||||
@@ -61,49 +66,124 @@ Page({
|
||||
} else {
|
||||
this.initCurrentUser();
|
||||
}
|
||||
},
|
||||
|
||||
/*onLoad(options) {
|
||||
if (options.data) {
|
||||
try {
|
||||
const p = JSON.parse(decodeURIComponent(options.data));
|
||||
this.setData({
|
||||
groupId: p.groupId || '',
|
||||
groupName: p.groupName || '订单群聊',
|
||||
groupAvatar: p.groupAvatar || '',
|
||||
orderId: p.orderId || '',
|
||||
isCross: p.isCross || 0
|
||||
});
|
||||
} catch (e) {}
|
||||
|
||||
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,
|
||||
});
|
||||
}
|
||||
wx.setNavigationBarTitle({ title: this.data.groupName });
|
||||
this.initCurrentUser();
|
||||
},*/
|
||||
},
|
||||
|
||||
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 {
|
||||
...serverMsg,
|
||||
showTime: m.showTime,
|
||||
status: status || 'success',
|
||||
formattedTime: serverMsg.formattedTime || m.formattedTime,
|
||||
};
|
||||
});
|
||||
this.setData({ messages: msgs });
|
||||
},
|
||||
|
||||
ensureChatConnection() {
|
||||
const role = app.globalData.currentRole || 'normal';
|
||||
const uid = wx.getStorageSync('uid');
|
||||
const prefixMap = { normal:'Boss', dashou:'Ds', shangjia:'Sj', guanshi:'Gs', zuzhang:'Zz' };
|
||||
const targetUserId = (prefixMap[role] || 'Boss') + uid;
|
||||
const pageUserId = this.data.currentUser?.id;
|
||||
const targetUserId = pageUserId || (prefixMap[role] || 'Boss') + uid;
|
||||
|
||||
const onReady = () => {
|
||||
this.subscribeGroupIfNeeded();
|
||||
this.setupAllListeners();
|
||||
this.loadHistory(true).then(() => this.markGroupMessageAsRead());
|
||||
this.subscribeGroupIfNeeded()
|
||||
.then(() => {
|
||||
this.setupAllListeners();
|
||||
return this.loadHistory(true);
|
||||
})
|
||||
.then(() => this.markGroupMessageAsRead());
|
||||
};
|
||||
|
||||
const connectedId = app.globalData?.goEasyConnection?.userId || wx.goEasy?.im?.userId;
|
||||
const status = wx.goEasy?.getConnectionStatus?.() || 'disconnected';
|
||||
const currentUserId = wx.goEasy?.im?.userId;
|
||||
const imOk = status === 'connected' || status === 'reconnected';
|
||||
|
||||
if ((status === 'connected' || status === 'reconnected') && currentUserId === targetUserId) {
|
||||
if (imOk && connectedId === targetUserId) {
|
||||
onReady();
|
||||
return;
|
||||
}
|
||||
@@ -132,15 +212,19 @@ Page({
|
||||
avatar: currentUser.avatar || (app.globalData.ossImageUrl + app.globalData.morentouxiang)
|
||||
},
|
||||
onSuccess: () => {
|
||||
this.subscribeGroupIfNeeded();
|
||||
this.setupAllListeners();
|
||||
this.loadHistory(true).then(() => this.markGroupMessageAsRead());
|
||||
this.subscribeGroupIfNeeded()
|
||||
.then(() => {
|
||||
this.setupAllListeners();
|
||||
return this.loadHistory(true);
|
||||
})
|
||||
.then(() => this.markGroupMessageAsRead());
|
||||
},
|
||||
onFailed: (error) => {
|
||||
if (error.code === 408) {
|
||||
this.subscribeGroupIfNeeded();
|
||||
this.setupAllListeners();
|
||||
this.loadHistory(true);
|
||||
this.subscribeGroupIfNeeded().then(() => {
|
||||
this.setupAllListeners();
|
||||
this.loadHistory(true);
|
||||
});
|
||||
} else {
|
||||
wx.showToast({ title: '连接失败,请重试', icon: 'none' });
|
||||
}
|
||||
@@ -150,11 +234,19 @@ Page({
|
||||
|
||||
subscribeGroupIfNeeded() {
|
||||
const { groupId } = this.data;
|
||||
if (!groupId) return;
|
||||
wx.goEasy.im.subscribeGroup({
|
||||
groupIds: [groupId],
|
||||
onSuccess: () => console.log(`[群聊页] 订阅成功: ${groupId}`),
|
||||
onFailed: (err) => console.error(`[群聊页] 订阅失败: ${groupId}`, err)
|
||||
if (!groupId || !wx.goEasy?.im) return Promise.resolve();
|
||||
return new Promise((resolve) => {
|
||||
wx.goEasy.im.subscribeGroup({
|
||||
groupIds: [groupId],
|
||||
onSuccess: () => {
|
||||
console.log(`[群聊页] 订阅成功: ${groupId}`);
|
||||
resolve();
|
||||
},
|
||||
onFailed: (err) => {
|
||||
console.error(`[群聊页] 订阅失败: ${groupId}`, err);
|
||||
resolve();
|
||||
},
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
@@ -219,6 +311,9 @@ Page({
|
||||
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) {
|
||||
@@ -249,10 +344,14 @@ 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;
|
||||
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' });
|
||||
@@ -339,8 +438,8 @@ 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);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -367,8 +466,8 @@ 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);
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -403,7 +502,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('撤回');
|
||||
|
||||
@@ -32,14 +32,34 @@ Page({
|
||||
this.renderConversations(content);
|
||||
}
|
||||
};
|
||||
this._onUnreadChanged = (data) => {
|
||||
const unreadTotal = data?.unreadTotal ?? app.globalData.messageManager?.unreadTotal ?? 0;
|
||||
if (app.globalData.messageManager) {
|
||||
app.globalData.messageManager.unreadTotal = unreadTotal;
|
||||
}
|
||||
if (app.emitEvent) {
|
||||
app.emitEvent('tabBarBadgeChanged', {
|
||||
badgeText: unreadTotal > 0 ? String(unreadTotal) : '',
|
||||
});
|
||||
}
|
||||
if (this.data.currentUser) {
|
||||
this.loadConversations();
|
||||
}
|
||||
};
|
||||
app.on('conversationsUpdated', this._onGlobalConvUpdated);
|
||||
app.on('unreadCountChanged', this._onGlobalConvUpdated);
|
||||
app.on('unreadCountChanged', this._onUnreadChanged);
|
||||
},
|
||||
|
||||
onUnload() {
|
||||
if (this._onGlobalConvUpdated) {
|
||||
app.off('conversationsUpdated', this._onGlobalConvUpdated);
|
||||
app.off('unreadCountChanged', this._onGlobalConvUpdated);
|
||||
}
|
||||
if (this._onUnreadChanged) {
|
||||
app.off('unreadCountChanged', this._onUnreadChanged);
|
||||
}
|
||||
if (this.conversationsUpdatedListener && wx.goEasy?.im) {
|
||||
wx.goEasy.im.off(wx.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, this.conversationsUpdatedListener);
|
||||
this.conversationsUpdatedListener = null;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -55,11 +75,7 @@ Page({
|
||||
this.checkPermissionAndAutoConnect();
|
||||
},
|
||||
|
||||
// ❌ 原版注释保留:删除所有清理逻辑,监听器永久存活
|
||||
onHide() {},
|
||||
onUnload() {},
|
||||
|
||||
// ========== 鉴权检查 ==========
|
||||
async checkPermissionAndAutoConnect() {
|
||||
const seq = ++this._permissionSeq;
|
||||
let quanxian;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// utils/chat-core.js
|
||||
import GoEasy from '../static/lib/goeasy-2.13.24.esm.min';
|
||||
import { jianquanxian } from './imAuth/jianquanxian';
|
||||
import { getFreshImUser } from './im-user.js';
|
||||
import { parseOrderCardText } from './group-chat.js';
|
||||
import { persistGroupMeta } from './im-user.js';
|
||||
|
||||
let _globalPrivateHandler = null;
|
||||
let _globalGroupHandler = null;
|
||||
@@ -124,9 +125,15 @@ function ensureConnection(app) {
|
||||
|
||||
// 连接不存在时尝试恢复
|
||||
const saved = getSavedConnection(app);
|
||||
if (!saved || !saved.userId || !saved.identityType) return;
|
||||
if (saved && saved.userId && saved.identityType) {
|
||||
connectWithIdentity(app, saved.identityType, saved.userId, true);
|
||||
return;
|
||||
}
|
||||
|
||||
connectWithIdentity(app, saved.identityType, saved.userId, true);
|
||||
const uid = wx.getStorageSync('uid');
|
||||
if (uid) {
|
||||
connectForCurrentRole(app);
|
||||
}
|
||||
}
|
||||
|
||||
function getSavedConnection(app) {
|
||||
@@ -200,7 +207,9 @@ function disconnectGoEasy(app) {
|
||||
|
||||
async function connectWithIdentity(app, identityType, userId, isAutoRestore = false) {
|
||||
const quanxian = await jianquanxian(app);
|
||||
if (!quanxian.allowed) return Promise.reject(quanxian.reason);
|
||||
if (!quanxian.allowed) {
|
||||
return Promise.reject(new Error(quanxian.reason || '无聊天权限'));
|
||||
}
|
||||
|
||||
app.globalData.goEasyConnection.autoReconnect = true;
|
||||
app.globalData.goEasyConnection.status = 'connecting';
|
||||
@@ -364,6 +373,9 @@ function removeGlobalMessageListeners() {
|
||||
}
|
||||
|
||||
function setupMessageListeners(app) {
|
||||
if (!wx.goEasy?.im || typeof wx.goEasy.im.on !== 'function') {
|
||||
return;
|
||||
}
|
||||
removeGlobalMessageListeners();
|
||||
|
||||
_globalPrivateHandler = (message) => {
|
||||
@@ -444,14 +456,8 @@ function handleNewMessage(app, message) {
|
||||
function shouldShowNotification(app) {
|
||||
if (app.globalData.messageManager.notificationMuted) return false;
|
||||
if (isDoNotDisturbTime(app)) return false;
|
||||
if (app.globalData.pageState.isInChatPage) {
|
||||
const pages = getCurrentPages();
|
||||
if (pages.length > 0) {
|
||||
const currentPage = pages[pages.length - 1];
|
||||
if (currentPage.data && currentPage.data.currentChatId) {
|
||||
if (isMessageFromCurrentChat(app, currentPage.data.currentChatId)) return false;
|
||||
}
|
||||
}
|
||||
if (app.globalData.pageState.isInChatPage && app.globalData.pageState.currentChatId) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -472,8 +478,16 @@ function isDoNotDisturbTime(app) {
|
||||
}
|
||||
}
|
||||
|
||||
function isMessageFromCurrentChat(app, currentChatId) {
|
||||
return false;
|
||||
function isMessageFromCurrentChat(app, message) {
|
||||
const pageState = app.globalData.pageState || {};
|
||||
if (!pageState.isInChatPage || !pageState.currentChatId) return false;
|
||||
if (message.groupId) {
|
||||
return message.groupId === pageState.currentChatId;
|
||||
}
|
||||
const myId = app.globalData.goEasyConnection?.userId || getCurrentGoEasyUserId();
|
||||
if (!myId) return false;
|
||||
const peerId = message.senderId === myId ? message.receiverId : message.senderId;
|
||||
return peerId === pageState.currentChatId || message.senderId === pageState.currentChatId;
|
||||
}
|
||||
|
||||
function showNotificationDirect(app, data) {
|
||||
@@ -534,6 +548,20 @@ function formatMessageForNotification(message) {
|
||||
}
|
||||
|
||||
function cacheMessage(app, message) {
|
||||
if (message.groupId && message.type === 'text' && message.payload?.text) {
|
||||
const card = parseOrderCardText(message.payload.text);
|
||||
if (card && card.zhuangtai != null) {
|
||||
if (!app.globalData.groupInfoMap) app.globalData.groupInfoMap = {};
|
||||
const meta = {
|
||||
...(app.globalData.groupInfoMap[message.groupId] || {}),
|
||||
orderId: card.orderId,
|
||||
orderZhuangtai: card.zhuangtai,
|
||||
orderDesc: card.jieshao,
|
||||
};
|
||||
app.globalData.groupInfoMap[message.groupId] = meta;
|
||||
persistGroupMeta(app, message.groupId, meta);
|
||||
}
|
||||
}
|
||||
const { latestMessages } = app.globalData.messageManager;
|
||||
latestMessages.unshift({
|
||||
id: message.messageId,
|
||||
|
||||
@@ -1,42 +1,46 @@
|
||||
/**
|
||||
* 连接管理模块 - 订单群聊跳转(后端准备群 + 稳定连接)
|
||||
* 订单群聊跳转:先确定群 ID,IM 连接失败也尽量能进聊天页
|
||||
*/
|
||||
import request from './request';
|
||||
import { persistGroupMeta } from './im-user.js';
|
||||
import { resolveLocalGroupId } from './group-chat.js';
|
||||
|
||||
const app = getApp();
|
||||
|
||||
function waitForConnection(expectedUserId, timeout = 15000) {
|
||||
function formatError(err) {
|
||||
if (!err) return '进入聊天失败';
|
||||
if (typeof err === 'string') return err;
|
||||
if (err.message) return err.message;
|
||||
if (err.content) return String(err.content);
|
||||
if (err.msg) return String(err.msg);
|
||||
if (err.code) return `连接失败(${err.code})`;
|
||||
try {
|
||||
return JSON.stringify(err);
|
||||
} catch (e) {
|
||||
return '进入聊天失败';
|
||||
}
|
||||
}
|
||||
|
||||
function withTimeout(promise, ms, errMsg) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const status = wx.goEasy?.getConnectionStatus?.();
|
||||
const currentUserId = wx.goEasy?.im?.userId;
|
||||
if ((status === 'connected' || status === 'reconnected') && currentUserId === expectedUserId) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
app.off('connectionChanged', handler);
|
||||
reject(new Error('连接超时'));
|
||||
}, timeout);
|
||||
|
||||
const handler = (event) => {
|
||||
if (event.status === 'connected') {
|
||||
const uid = event.userId || wx.goEasy?.im?.userId;
|
||||
if (uid === expectedUserId) {
|
||||
clearTimeout(timer);
|
||||
app.off('connectionChanged', handler);
|
||||
resolve();
|
||||
}
|
||||
} else if (event.status === 'disconnected' && event.manual) {
|
||||
clearTimeout(timer);
|
||||
app.off('connectionChanged', handler);
|
||||
reject(new Error('连接已断开'));
|
||||
}
|
||||
};
|
||||
app.on('connectionChanged', handler);
|
||||
const timer = setTimeout(() => reject(new Error(errMsg || '操作超时')), ms);
|
||||
promise
|
||||
.then((v) => { clearTimeout(timer); resolve(v); })
|
||||
.catch((e) => { clearTimeout(timer); reject(e); });
|
||||
});
|
||||
}
|
||||
|
||||
function getConnectedUserId() {
|
||||
const fromState = app.globalData?.goEasyConnection?.userId;
|
||||
const fromIm = wx.goEasy?.im?.userId;
|
||||
return fromState || fromIm || '';
|
||||
}
|
||||
|
||||
function isImConnected() {
|
||||
const status = wx.goEasy?.getConnectionStatus?.() || 'disconnected';
|
||||
return status === 'connected' || status === 'reconnected';
|
||||
}
|
||||
|
||||
async function ensureIdentityConnection(identityType, userId) {
|
||||
app.globalData.currentRole = identityType;
|
||||
wx.setStorageSync('currentRole', identityType);
|
||||
@@ -50,21 +54,88 @@ async function ensureIdentityConnection(identityType, userId) {
|
||||
avatar: avatar,
|
||||
};
|
||||
|
||||
const status = wx.goEasy?.getConnectionStatus?.() || 'disconnected';
|
||||
const currentUserId = wx.goEasy?.im?.userId;
|
||||
if (!app.globalData.chatEnabled || !wx.goEasy?.im) {
|
||||
throw new Error('聊天服务未就绪,请稍后重试');
|
||||
}
|
||||
|
||||
if ((status === 'connected' || status === 'reconnected') && currentUserId === userId) {
|
||||
if (isImConnected() && getConnectedUserId() === userId) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentUserId && currentUserId !== userId && app.disconnectGoEasy) {
|
||||
const connectedId = getConnectedUserId();
|
||||
if (connectedId && connectedId !== userId && app.disconnectGoEasy) {
|
||||
await app.disconnectGoEasy();
|
||||
}
|
||||
|
||||
const waitPromise = waitForConnection(userId);
|
||||
const connectPromise = app.connectWithIdentity(identityType, userId, true);
|
||||
await waitPromise;
|
||||
await connectPromise;
|
||||
if (!app.connectWithIdentity) {
|
||||
throw new Error('聊天功能未初始化');
|
||||
}
|
||||
|
||||
await withTimeout(
|
||||
app.connectWithIdentity(identityType, userId, true),
|
||||
12000,
|
||||
'IM连接超时'
|
||||
);
|
||||
|
||||
if (!isImConnected()) {
|
||||
throw new Error('IM连接失败,请检查网络后重试');
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareGroupChat(identityType, userId, orderId, partnerUid, fadanPingtai, groupName, isCross) {
|
||||
let chatData = null;
|
||||
|
||||
try {
|
||||
const res = await withTimeout(
|
||||
request({
|
||||
url: '/dingdan/ltdhzb',
|
||||
method: 'POST',
|
||||
data: {
|
||||
dingdan_id: orderId,
|
||||
identityType,
|
||||
push_order_card: false,
|
||||
},
|
||||
}),
|
||||
12000,
|
||||
'准备群聊超时'
|
||||
);
|
||||
const body = res?.data || {};
|
||||
if (body.code === 0 && body.data?.groupId) {
|
||||
chatData = body.data;
|
||||
} else if (body.msg) {
|
||||
console.warn('ltdhzb:', body.msg);
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('ltdhzb 请求失败,尝试本地 groupId', e);
|
||||
}
|
||||
|
||||
if (!chatData?.groupId) {
|
||||
const myUid = userId.replace(/^(Ds|Sj|Boss)/, '');
|
||||
let localGroupId = resolveLocalGroupId(
|
||||
identityType, myUid, partnerUid, fadanPingtai, orderId, isCross
|
||||
);
|
||||
if (!localGroupId && orderId) {
|
||||
localGroupId = `group_${orderId}`;
|
||||
}
|
||||
if (!localGroupId) {
|
||||
throw new Error('无法确定群聊,请确认订单已接单且对方信息完整');
|
||||
}
|
||||
chatData = {
|
||||
groupId: localGroupId,
|
||||
orderId,
|
||||
groupName: groupName || '订单群聊',
|
||||
isCross: isCross || fadanPingtai || 0,
|
||||
};
|
||||
try {
|
||||
await request({
|
||||
url: '/dingdan/ltdhzb',
|
||||
method: 'POST',
|
||||
data: { dingdan_id: orderId, identityType, push_order_card: false },
|
||||
});
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
return chatData;
|
||||
}
|
||||
|
||||
class ConnectionManager {
|
||||
@@ -89,39 +160,30 @@ class ConnectionManager {
|
||||
};
|
||||
|
||||
const param = { to, currentUser };
|
||||
const path = '/pages/liaotian/liaotian?data=' + encodeURIComponent(JSON.stringify(param));
|
||||
wx.navigateTo({ url: path });
|
||||
wx.navigateTo({ url: '/pages/liaotian/liaotian?data=' + encodeURIComponent(JSON.stringify(param)) });
|
||||
}
|
||||
|
||||
async connectToGroupChat(params) {
|
||||
const { identityType, userId, orderId, groupName, groupAvatar, isCross } = params;
|
||||
const {
|
||||
identityType, userId, orderId, groupName, groupAvatar, isCross,
|
||||
partnerUid, fadanPingtai,
|
||||
} = params;
|
||||
|
||||
if (!identityType || !userId || !orderId) {
|
||||
throw new Error('参数不完整:identityType, userId, orderId 必填');
|
||||
throw new Error('参数不完整');
|
||||
}
|
||||
|
||||
app.globalData.currentRole = identityType;
|
||||
wx.setStorageSync('currentRole', identityType);
|
||||
|
||||
wx.showLoading({ title: '建立联系中...', mask: true });
|
||||
|
||||
try {
|
||||
await ensureIdentityConnection(identityType, userId);
|
||||
const chatData = await prepareGroupChat(
|
||||
identityType, userId, orderId, partnerUid, fadanPingtai || isCross, groupName, isCross
|
||||
);
|
||||
|
||||
const res = await request({
|
||||
url: '/dingdan/ltdhzb',
|
||||
method: 'POST',
|
||||
data: {
|
||||
dingdan_id: orderId,
|
||||
identityType,
|
||||
push_order_card: true,
|
||||
},
|
||||
});
|
||||
|
||||
const body = res?.data || {};
|
||||
if (body.code !== 0 || !body.data || !body.data.groupId) {
|
||||
throw new Error(body.msg || '准备群聊失败');
|
||||
}
|
||||
|
||||
const chatData = body.data;
|
||||
const realGroupId = chatData.groupId;
|
||||
|
||||
let avatar = chatData.counterpartAvatar || chatData.groupAvatar || groupAvatar || '';
|
||||
if (avatar && !avatar.startsWith('http')) {
|
||||
avatar = app.globalData.ossImageUrl + avatar.replace(/^\//, '');
|
||||
@@ -148,30 +210,57 @@ class ConnectionManager {
|
||||
app.globalData.groupInfoMap[realGroupId] = meta;
|
||||
persistGroupMeta(app, realGroupId, meta);
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
wx.goEasy.im.subscribeGroup({
|
||||
groupIds: [realGroupId],
|
||||
onSuccess: () => resolve(),
|
||||
onFailed: (error) => reject(error),
|
||||
});
|
||||
});
|
||||
let imReady = false;
|
||||
try {
|
||||
await ensureIdentityConnection(identityType, userId);
|
||||
imReady = true;
|
||||
try {
|
||||
await withTimeout(
|
||||
new Promise((resolve, reject) => {
|
||||
wx.goEasy.im.subscribeGroup({
|
||||
groupIds: [realGroupId],
|
||||
onSuccess: () => resolve(),
|
||||
onFailed: (error) => reject(error),
|
||||
});
|
||||
}),
|
||||
8000,
|
||||
'订阅群聊超时'
|
||||
);
|
||||
} catch (subErr) {
|
||||
console.warn('订阅群聊失败,仍尝试进入页面', subErr);
|
||||
}
|
||||
} catch (imErr) {
|
||||
console.warn('IM连接失败,仍进入聊天页由页面重连', imErr);
|
||||
}
|
||||
|
||||
const uid = userId.replace(/^(Ds|Sj|Boss)/, '');
|
||||
const param = {
|
||||
groupId: realGroupId,
|
||||
orderId: chatData.orderId || orderId,
|
||||
groupName: chatData.counterpartName || chatData.groupName || groupName || '订单群聊',
|
||||
groupAvatar: avatar,
|
||||
isCross: chatData.isCross != null ? chatData.isCross : (isCross || 0),
|
||||
currentUserId: userId,
|
||||
currentUserName: app.globalData.currentUser?.name || `用户${uid}`,
|
||||
currentUserAvatar: app.globalData.currentUser?.avatar ||
|
||||
(wx.getStorageSync('touxiang') || (app.globalData.ossImageUrl + app.globalData.morentouxiang)),
|
||||
orderZhuangtai: chatData.orderZhuangtai,
|
||||
orderJine: chatData.orderJine,
|
||||
orderDesc: chatData.orderDesc || '',
|
||||
imReady,
|
||||
};
|
||||
|
||||
wx.hideLoading();
|
||||
wx.navigateTo({
|
||||
url: '/pages/qunliaotian/qunliaotian?data=' + encodeURIComponent(JSON.stringify(param)),
|
||||
fail: (navErr) => {
|
||||
wx.showToast({ title: formatError(navErr), icon: 'none', duration: 2500 });
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
wx.hideLoading();
|
||||
console.error('跳转群聊失败:', err);
|
||||
wx.showToast({ title: err.message || '进入聊天失败', icon: 'none' });
|
||||
wx.showToast({ title: formatError(err), icon: 'none', duration: 2500 });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user