本地备份:消息系统改造前完整版本(未推送,便于回退)
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1325
utils/chat-core.js
1325
utils/chat-core.js
File diff suppressed because it is too large
Load Diff
25
utils/grab-order-gate.js
Normal file
25
utils/grab-order-gate.js
Normal file
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* 抢单前检查(仅点击抢单时调用)
|
||||
*/
|
||||
import request from './request.js';
|
||||
|
||||
/** 检查是否有待处理罚款(待缴纳 / 申诉中) */
|
||||
export async function checkPenaltyForGrab() {
|
||||
try {
|
||||
const res = await request({ url: '/yonghu/cffktjhq', method: 'POST' });
|
||||
if (res?.data?.code === 0) {
|
||||
const fk = res.data.data?.fakuan || {};
|
||||
const pending = Number(fk.daijiaona || 0) + Number(fk.shensuzhong || 0);
|
||||
if (pending > 0) {
|
||||
return {
|
||||
blocked: true,
|
||||
msg: '您有未缴纳或申诉中的罚单,请先处理后再抢单',
|
||||
url: '/pages/penalty/penalty/penalty',
|
||||
};
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('checkPenaltyForGrab failed', e);
|
||||
}
|
||||
return { blocked: false };
|
||||
}
|
||||
241
utils/group-chat.js
Normal file
241
utils/group-chat.js
Normal file
@@ -0,0 +1,241 @@
|
||||
/**
|
||||
* 打手-商家/老板配对群:group_Ds{打手}_Sj{商家}
|
||||
*/
|
||||
export const ORDER_CARD_PREFIX = '[ORDER_CARD]';
|
||||
|
||||
const ZHUANGTAI_MAP = {
|
||||
1: '已下单', 2: '进行中', 3: '已完成', 4: '退款中',
|
||||
5: '已退款', 6: '退款失败', 7: '指定中', 8: '结算中',
|
||||
};
|
||||
|
||||
export function getZhuangtaiText(zhuangtai) {
|
||||
if (zhuangtai == null || zhuangtai === '') return '';
|
||||
const n = Number(zhuangtai);
|
||||
return ZHUANGTAI_MAP[n] || ZHUANGTAI_MAP[zhuangtai] || '';
|
||||
}
|
||||
|
||||
export function buildDashouShangjiaGroupId(dashouUid, shangjiaUid) {
|
||||
return `group_Ds${dashouUid}_Sj${shangjiaUid}`;
|
||||
}
|
||||
|
||||
export function buildDashouBossGroupId(dashouUid, bossUid) {
|
||||
return `group_Ds${dashouUid}_Boss${bossUid}`;
|
||||
}
|
||||
|
||||
export function resolveLocalGroupId(identityType, myUid, partnerUid, fadanPingtai, orderId, isCross) {
|
||||
const cross = isCross === 1 || isCross === true || String(isCross) === '1';
|
||||
if (cross && orderId) {
|
||||
return `group_${orderId}`;
|
||||
}
|
||||
if (!myUid) return orderId ? `group_${orderId}` : null;
|
||||
if (!partnerUid) return orderId ? `group_${orderId}` : null;
|
||||
if (identityType === 'shangjia') {
|
||||
return buildDashouShangjiaGroupId(partnerUid, myUid);
|
||||
}
|
||||
if (identityType === 'dashou') {
|
||||
if (fadanPingtai === 2 || String(fadanPingtai) === '2') {
|
||||
return buildDashouShangjiaGroupId(myUid, partnerUid);
|
||||
}
|
||||
return buildDashouBossGroupId(myUid, partnerUid);
|
||||
}
|
||||
return orderId ? `group_${orderId}` : null;
|
||||
}
|
||||
|
||||
export function isPairGroupId(groupId) {
|
||||
return /^group_Ds\w+_(Sj|Boss)\w+$/.test(groupId || '');
|
||||
}
|
||||
|
||||
export function parsePairGroupId(groupId) {
|
||||
if (!groupId) return null;
|
||||
let m = /^group_Ds(\w+)_Sj(\w+)$/.exec(groupId);
|
||||
if (m) return { dashouId: `Ds${m[1]}`, partnerId: `Sj${m[2]}`, partnerRole: 'shangjia' };
|
||||
m = /^group_Ds(\w+)_Boss(\w+)$/.exec(groupId);
|
||||
if (m) return { dashouId: `Ds${m[1]}`, partnerId: `Boss${m[2]}`, partnerRole: 'boss' };
|
||||
return null;
|
||||
}
|
||||
|
||||
export function getCounterpartGoEasyId(groupId, myGoEasyId) {
|
||||
const parsed = parsePairGroupId(groupId);
|
||||
if (!parsed || !myGoEasyId) return null;
|
||||
if (myGoEasyId === parsed.dashouId) return parsed.partnerId;
|
||||
if (myGoEasyId === parsed.partnerId) return parsed.dashouId;
|
||||
return null;
|
||||
}
|
||||
|
||||
function fixAvatarUrl(avatar, defaultAvatar, ossBase) {
|
||||
if (!avatar) return defaultAvatar;
|
||||
if (avatar.startsWith('http')) return avatar;
|
||||
return (ossBase || '') + avatar.replace(/^\//, '');
|
||||
}
|
||||
|
||||
/** 根据群 to.data 与当前身份,解析对方/双方展示信息 */
|
||||
export function applyPairMetaToConversation(item, myGoEasyId, defaultAvatar, ossBase) {
|
||||
if (!item || !item.data) return;
|
||||
const d = item.data;
|
||||
|
||||
if (d.dashouGoEasyId && d.partnerGoEasyId) {
|
||||
const isDashou = myGoEasyId === d.dashouGoEasyId;
|
||||
const isPartner = myGoEasyId === d.partnerGoEasyId;
|
||||
d.dashouNicheng = d.dashouName || d.dashouNicheng || '';
|
||||
d.partnerNicheng = d.partnerName || d.partnerNicheng || '';
|
||||
d.dashouAvatar = fixAvatarUrl(d.dashouAvatar, defaultAvatar, ossBase);
|
||||
d.partnerAvatar = fixAvatarUrl(d.partnerAvatar, defaultAvatar, ossBase);
|
||||
|
||||
if (isDashou) {
|
||||
d.counterpartId = d.partnerGoEasyId;
|
||||
d.counterpartYonghuid = d.partnerYonghuid || d.partnerGoEasyId.replace(/^(Sj|Boss)/, '');
|
||||
d.partnerRoleLabel = d.partnerGoEasyId.startsWith('Boss') ? '老板' : '商家';
|
||||
d.name = d.partnerNicheng || `${d.partnerRoleLabel}${d.counterpartYonghuid}`;
|
||||
d.avatar = d.partnerAvatar || defaultAvatar;
|
||||
} else if (isPartner) {
|
||||
d.counterpartId = d.dashouGoEasyId;
|
||||
d.counterpartYonghuid = d.dashouYonghuid || d.dashouGoEasyId.replace(/^Ds/, '');
|
||||
d.name = d.dashouNicheng || `打手${d.counterpartYonghuid}`;
|
||||
d.avatar = d.dashouAvatar || defaultAvatar;
|
||||
} else {
|
||||
const cpId = getCounterpartGoEasyId(item.groupId, myGoEasyId);
|
||||
if (cpId === d.partnerGoEasyId) {
|
||||
d.name = d.partnerNicheng;
|
||||
d.avatar = d.partnerAvatar || defaultAvatar;
|
||||
} else if (cpId === d.dashouGoEasyId) {
|
||||
d.name = d.dashouNicheng;
|
||||
d.avatar = d.dashouAvatar || defaultAvatar;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const counterpartId = getCounterpartGoEasyId(item.groupId, myGoEasyId);
|
||||
if (counterpartId) {
|
||||
d.counterpartId = counterpartId;
|
||||
d.counterpartYonghuid = counterpartId.replace(/^(Ds|Sj|Boss)/, '');
|
||||
if (!d.name || d.name === item.groupId) {
|
||||
d.name = `用户${d.counterpartYonghuid.slice(-6)}`;
|
||||
}
|
||||
}
|
||||
|
||||
if (item.lastMessage && item.lastMessage.senderId && item.lastMessage.senderId !== myGoEasyId) {
|
||||
const sd = item.lastMessage.senderData || {};
|
||||
if (sd.avatar) d.avatar = fixAvatarUrl(sd.avatar, defaultAvatar, ossBase);
|
||||
if (sd.name) d.name = sd.name;
|
||||
}
|
||||
|
||||
d.avatar = fixAvatarUrl(d.avatar, defaultAvatar, ossBase);
|
||||
}
|
||||
|
||||
export function parseOrderCardText(text) {
|
||||
if (!text || !text.startsWith(ORDER_CARD_PREFIX)) return null;
|
||||
try {
|
||||
const data = JSON.parse(text.slice(ORDER_CARD_PREFIX.length));
|
||||
return {
|
||||
orderId: data.dingdan_id,
|
||||
jieshao: data.jieshao || '',
|
||||
jine: data.jine || '',
|
||||
beizhu: data.beizhu || '',
|
||||
zhuangtai: data.zhuangtai,
|
||||
nicheng: data.nicheng || '',
|
||||
create_time: data.create_time || '',
|
||||
};
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
import { getChatImageUrl } from '../static/lib/utils.js';
|
||||
|
||||
export function normalizeGroupMessage(msg) {
|
||||
if (!msg) return msg;
|
||||
if (msg.type === 'text' && msg.payload && msg.payload.text) {
|
||||
const card = parseOrderCardText(msg.payload.text);
|
||||
if (card) {
|
||||
msg.type = 'order';
|
||||
msg.payload = card;
|
||||
}
|
||||
}
|
||||
if (msg.type === 'custom' && msg.payload) {
|
||||
const inner = msg.payload.payload || msg.payload;
|
||||
if (inner && (inner.orderId || inner.dingdan_id)) {
|
||||
msg.type = 'order';
|
||||
msg.payload = {
|
||||
orderId: inner.orderId || inner.dingdan_id,
|
||||
jieshao: inner.jieshao || '',
|
||||
jine: inner.jine || '',
|
||||
beizhu: inner.beizhu || '',
|
||||
zhuangtai: inner.zhuangtai,
|
||||
nicheng: inner.nicheng || '',
|
||||
create_time: inner.create_time || '',
|
||||
};
|
||||
}
|
||||
}
|
||||
if (msg.type === 'image') {
|
||||
const url = getChatImageUrl(msg);
|
||||
msg.payload = { ...(msg.payload || {}), url };
|
||||
msg.imageUrl = url;
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
|
||||
export function formatLastMessagePreview(msg) {
|
||||
if (!msg) return '';
|
||||
if (msg.type === 'text' && msg.payload && msg.payload.text) {
|
||||
const card = parseOrderCardText(msg.payload.text);
|
||||
if (card) return `[订单] ${card.jieshao || card.orderId}`;
|
||||
return msg.payload.text;
|
||||
}
|
||||
if (msg.type === 'order' && msg.payload) {
|
||||
return `[订单] ${msg.payload.jieshao || msg.payload.orderId || ''}`;
|
||||
}
|
||||
if (msg.type === 'image') return '[图片]';
|
||||
return '[消息]';
|
||||
}
|
||||
|
||||
export function enrichGroupConversation(item, myGoEasyId, defaultAvatar, ossBase) {
|
||||
if (!item || item.type !== 'group') return item;
|
||||
if (!item.data) item.data = {};
|
||||
|
||||
applyPairMetaToConversation(item, myGoEasyId, defaultAvatar, ossBase);
|
||||
|
||||
if (item.data.orderZhuangtai != null) {
|
||||
item.data.orderZhuangtaiText = ZHUANGTAI_MAP[item.data.orderZhuangtai] || '';
|
||||
}
|
||||
|
||||
item.displayLastMsg = formatLastMessagePreview(item.lastMessage);
|
||||
if (!item.data.avatar) item.data.avatar = defaultAvatar;
|
||||
return item;
|
||||
}
|
||||
|
||||
export function isOrderGroupConversation(c) {
|
||||
if (!c || c.type !== 'group') return false;
|
||||
if (c.data && c.data.orderId) return true;
|
||||
if (c.data && c.data.dashouGoEasyId) return true;
|
||||
return isPairGroupId(c.groupId) || /^group_\w+$/.test(c.groupId || '');
|
||||
}
|
||||
|
||||
export function getConversationSortTime(conversation, openTimes) {
|
||||
const id = conversation.groupId || conversation.userId || '';
|
||||
const msgTs = conversation.lastMessage?.timestamp || 0;
|
||||
const openTs = (openTimes && id && openTimes[id]) ? openTimes[id] : 0;
|
||||
return Math.max(msgTs, openTs);
|
||||
}
|
||||
|
||||
export function sortConversations(list, openTimes) {
|
||||
return list.sort((a, b) => {
|
||||
if (a.top && !b.top) return -1;
|
||||
if (!a.top && b.top) return 1;
|
||||
if (a.unread > 0 && b.unread <= 0) return -1;
|
||||
if (a.unread <= 0 && b.unread > 0) return 1;
|
||||
const ta = getConversationSortTime(a, openTimes);
|
||||
const tb = getConversationSortTime(b, openTimes);
|
||||
return tb - ta;
|
||||
});
|
||||
}
|
||||
|
||||
export function recordConversationOpen(conversation) {
|
||||
const id = conversation?.groupId || conversation?.userId;
|
||||
if (!id) return;
|
||||
try {
|
||||
const times = wx.getStorageSync('conversationOpenTimes') || {};
|
||||
times[id] = Date.now();
|
||||
wx.setStorageSync('conversationOpenTimes', times);
|
||||
} catch (e) {}
|
||||
}
|
||||
@@ -1,218 +1,269 @@
|
||||
/**
|
||||
* 连接管理模块 - xiaoxilj.js (根治发送失败:跳转前确保群组已订阅)
|
||||
* 从详情页跳转订单群聊时,提前订阅群组,避免发送消息时订阅未完成而失败
|
||||
*/
|
||||
const app = getApp();
|
||||
|
||||
function waitForConnection(expectedUserId, timeout = 10000) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
app.off('connectionChanged', handler);
|
||||
reject(new Error('连接超时'));
|
||||
}, timeout);
|
||||
|
||||
const handler = (event) => {
|
||||
if (event.status === 'connected') {
|
||||
if (event.userId === expectedUserId) {
|
||||
clearTimeout(timer);
|
||||
app.off('connectionChanged', handler);
|
||||
resolve();
|
||||
} else {
|
||||
console.error(`连接身份不匹配: 期望 ${expectedUserId}, 实际 ${event.userId}`);
|
||||
wx.removeStorageSync('savedGoEasyConnection');
|
||||
wx.removeStorageSync('goEasyUserId');
|
||||
wx.removeStorageSync('currentGoEasyIdentity');
|
||||
if (app.clearSavedConnection) app.clearSavedConnection();
|
||||
clearTimeout(timer);
|
||||
app.off('connectionChanged', handler);
|
||||
reject(new Error(`连接身份不匹配: 期望 ${expectedUserId}, 实际 ${event.userId}`));
|
||||
}
|
||||
} else if (event.status === 'disconnected' && !event.manual) {
|
||||
wx.removeStorageSync('savedGoEasyConnection');
|
||||
wx.removeStorageSync('goEasyUserId');
|
||||
wx.removeStorageSync('currentGoEasyIdentity');
|
||||
if (app.clearSavedConnection) app.clearSavedConnection();
|
||||
clearTimeout(timer);
|
||||
app.off('connectionChanged', handler);
|
||||
reject(new Error('连接失败'));
|
||||
}
|
||||
};
|
||||
app.on('connectionChanged', handler);
|
||||
});
|
||||
}
|
||||
|
||||
class ConnectionManager {
|
||||
// 原有的私聊方法保持不变
|
||||
async connectAndChat(params) {
|
||||
const { identityType, userId, targetUser } = params;
|
||||
if (!identityType || !userId || !targetUser || !targetUser.id) {
|
||||
throw new Error('参数不完整');
|
||||
}
|
||||
|
||||
if (identityType === 'dashou' && !userId.startsWith('Ds')) {
|
||||
throw new Error(`接单员身份的用户ID必须以Ds开头,实际为 ${userId}`);
|
||||
}
|
||||
if (identityType === 'shangjia' && !userId.startsWith('Sj')) {
|
||||
throw new Error(`商家身份的用户ID必须以Sj开头,实际为 ${userId}`);
|
||||
}
|
||||
if (identityType === 'boss' && !userId.startsWith('Boss')) {
|
||||
throw new Error(`老板身份的用户ID必须以Boss开头,实际为 ${userId}`);
|
||||
}
|
||||
|
||||
wx.removeStorageSync('savedGoEasyConnection');
|
||||
wx.removeStorageSync('goEasyUserId');
|
||||
wx.removeStorageSync('currentGoEasyIdentity');
|
||||
if (app.clearSavedConnection) app.clearSavedConnection();
|
||||
|
||||
if (wx.goEasy && wx.goEasy.getConnectionStatus() === 'connected') {
|
||||
wx.goEasy.disconnect();
|
||||
}
|
||||
|
||||
const waitPromise = waitForConnection(userId);
|
||||
app.connectWithIdentity(identityType, userId, false);
|
||||
|
||||
try {
|
||||
await waitPromise;
|
||||
|
||||
const currentUser = {
|
||||
id: userId,
|
||||
name: app.globalData.currentUser?.name || '用户',
|
||||
avatar: app.globalData.currentUser?.avatar || (app.globalData.ossImageUrl + app.globalData.morentouxiang)
|
||||
};
|
||||
|
||||
const to = {
|
||||
id: targetUser.id,
|
||||
name: targetUser.name || '用户',
|
||||
avatar: targetUser.avatar || (app.globalData.ossImageUrl + app.globalData.morentouxiang)
|
||||
};
|
||||
|
||||
const param = { to, currentUser };
|
||||
const path = '/pages/chat/chat?data=' + encodeURIComponent(JSON.stringify(param));
|
||||
wx.navigateTo({ url: path });
|
||||
} catch (err) {
|
||||
console.error('连接失败:', err);
|
||||
wx.showToast({ title: err.message || '连接失败', icon: 'none' });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async connectToGroupChat(params) {
|
||||
const { identityType, userId, orderId, groupName, groupAvatar, isCross } = params;
|
||||
if (!identityType || !userId || !orderId) {
|
||||
throw new Error('参数不完整:identityType, userId, orderId 必填');
|
||||
}
|
||||
|
||||
// 校验 userId 前缀
|
||||
if (identityType === 'dashou' && !userId.startsWith('Ds')) {
|
||||
throw new Error(`接单员身份的用户ID必须以Ds开头,实际为 ${userId}`);
|
||||
}
|
||||
if (identityType === 'shangjia' && !userId.startsWith('Sj')) {
|
||||
throw new Error(`商家身份的用户ID必须以Sj开头,实际为 ${userId}`);
|
||||
}
|
||||
if (identityType === 'boss' && !userId.startsWith('Boss')) {
|
||||
throw new Error(`老板身份的用户ID必须以Boss开头,实际为 ${userId}`);
|
||||
}
|
||||
|
||||
|
||||
// 1. 同步全局角色,确保群聊页初始化正确
|
||||
app.globalData.currentRole = identityType;
|
||||
wx.setStorageSync('currentRole', identityType);
|
||||
|
||||
const uid = userId.replace(/^(Ds|Sj|Boss|Gs|Zz)/, '');
|
||||
const avatar = wx.getStorageSync('touxiang') ||
|
||||
(app.globalData.ossImageUrl + app.globalData.morentouxiang);
|
||||
app.globalData.currentUser = {
|
||||
id: userId,
|
||||
name: app.globalData.currentUser?.name || `用户${uid}`,
|
||||
avatar: avatar
|
||||
};
|
||||
|
||||
// 2. 确保 GoEasy 已使用目标身份连接
|
||||
let needConnect = false;
|
||||
if (!wx.goEasy || !wx.goEasy.getConnectionStatus || wx.goEasy.getConnectionStatus() !== 'connected') {
|
||||
needConnect = true;
|
||||
} else {
|
||||
const currentUserId = wx.goEasy.im?.userId;
|
||||
if (currentUserId !== userId) {
|
||||
needConnect = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (needConnect) {
|
||||
wx.removeStorageSync('savedGoEasyConnection');
|
||||
wx.removeStorageSync('goEasyUserId');
|
||||
if (app.clearSavedConnection) app.clearSavedConnection();
|
||||
if (wx.goEasy && wx.goEasy.getConnectionStatus() === 'connected') {
|
||||
wx.goEasy.disconnect();
|
||||
}
|
||||
const waitPromise = waitForConnection(userId);
|
||||
app.connectWithIdentity(identityType, userId, false);
|
||||
try {
|
||||
await waitPromise;
|
||||
} catch (err) {
|
||||
wx.showToast({ title: '连接失败', icon: 'none' });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 从会话列表查找群组;找不到则用订单号作为 groupId(首聊场景)
|
||||
const orderIdStr = String(orderId);
|
||||
let realGroupId = orderIdStr;
|
||||
try {
|
||||
const result = await new Promise((resolve, reject) => {
|
||||
wx.goEasy.im.latestConversations({
|
||||
onSuccess: (res) => {
|
||||
const conversations = res.content?.conversations || [];
|
||||
const found = conversations.find((c) => {
|
||||
if (c.type !== 'group') return false;
|
||||
if (c.groupId === orderIdStr) return true;
|
||||
const data = c.data || {};
|
||||
return String(data.orderId || '') === orderIdStr;
|
||||
});
|
||||
resolve(found ? found.groupId : orderIdStr);
|
||||
},
|
||||
onFailed: reject,
|
||||
});
|
||||
});
|
||||
realGroupId = result || orderIdStr;
|
||||
} catch (err) {
|
||||
console.warn('获取会话列表失败,使用订单号作为群ID', err);
|
||||
realGroupId = orderIdStr;
|
||||
}
|
||||
|
||||
// 4. 🔥 关键:主动订阅群组并等待成功,确保发送消息时订阅已完成
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
wx.goEasy.im.subscribeGroup({
|
||||
groupIds: [realGroupId],
|
||||
onSuccess: () => {
|
||||
resolve();
|
||||
},
|
||||
onFailed: (error) => {
|
||||
console.error('订阅群组失败:', error);
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
});
|
||||
} catch (err) {
|
||||
wx.showToast({ title: '订阅群组失败', icon: 'none' });
|
||||
throw err;
|
||||
}
|
||||
|
||||
// 5. 跳转群聊页(参数与消息列表完全一致)
|
||||
const param = {
|
||||
groupId: realGroupId,
|
||||
orderId: orderIdStr,
|
||||
groupName: groupName || '订单群聊',
|
||||
groupAvatar: groupAvatar || '',
|
||||
isCross: isCross || 0,
|
||||
currentUserId: userId,
|
||||
currentUserName: app.globalData.currentUser?.name || `用户${uid}`,
|
||||
currentUserAvatar: avatar,
|
||||
};
|
||||
const path = '/pages/group-chat/group-chat?data=' + encodeURIComponent(JSON.stringify(param));
|
||||
wx.navigateTo({ url: path });
|
||||
}
|
||||
}
|
||||
|
||||
export default new ConnectionManager();
|
||||
/**
|
||||
* 订单群聊跳转:先确定群 ID,IM 连接失败也尽量能进聊天页
|
||||
*/
|
||||
import request from './request';
|
||||
import { persistGroupMeta } from './im-user.js';
|
||||
import { resolveLocalGroupId } from './group-chat.js';
|
||||
|
||||
const app = getApp();
|
||||
|
||||
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 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);
|
||||
|
||||
const uid = userId.replace(/^(Ds|Sj|Boss|Gs|Zz|Kh)/, '');
|
||||
const avatar = wx.getStorageSync('touxiang') ||
|
||||
(app.globalData.ossImageUrl + app.globalData.morentouxiang);
|
||||
app.globalData.currentUser = {
|
||||
id: userId,
|
||||
name: app.globalData.currentUser?.name || `用户${uid}`,
|
||||
avatar: avatar,
|
||||
};
|
||||
|
||||
if (!app.globalData.chatEnabled || !wx.goEasy?.im) {
|
||||
throw new Error('聊天服务未就绪,请稍后重试');
|
||||
}
|
||||
|
||||
if (isImConnected() && getConnectedUserId() === userId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const connectedId = getConnectedUserId();
|
||||
if (connectedId && connectedId !== userId && app.disconnectGoEasy) {
|
||||
await app.disconnectGoEasy();
|
||||
}
|
||||
|
||||
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 {
|
||||
async connectAndChat(params) {
|
||||
const { identityType, userId, targetUser } = params;
|
||||
if (!identityType || !userId || !targetUser || !targetUser.id) {
|
||||
throw new Error('参数不完整');
|
||||
}
|
||||
|
||||
await ensureIdentityConnection(identityType, userId);
|
||||
|
||||
const currentUser = {
|
||||
id: userId,
|
||||
name: app.globalData.currentUser?.name || '用户',
|
||||
avatar: app.globalData.currentUser?.avatar || (app.globalData.ossImageUrl + app.globalData.morentouxiang),
|
||||
};
|
||||
|
||||
const to = {
|
||||
id: targetUser.id,
|
||||
name: targetUser.name || '用户',
|
||||
avatar: targetUser.avatar || (app.globalData.ossImageUrl + app.globalData.morentouxiang),
|
||||
};
|
||||
|
||||
const param = { to, currentUser };
|
||||
wx.navigateTo({ url: '/pages/chat/chat?data=' + encodeURIComponent(JSON.stringify(param)) });
|
||||
}
|
||||
|
||||
async connectToGroupChat(params) {
|
||||
const {
|
||||
identityType, userId, orderId, groupName, groupAvatar, isCross,
|
||||
partnerUid, fadanPingtai,
|
||||
} = params;
|
||||
|
||||
if (!identityType || !userId || !orderId) {
|
||||
throw new Error('参数不完整');
|
||||
}
|
||||
|
||||
app.globalData.currentRole = identityType;
|
||||
wx.setStorageSync('currentRole', identityType);
|
||||
|
||||
wx.showLoading({ title: '建立联系中...', mask: true });
|
||||
|
||||
try {
|
||||
const chatData = await prepareGroupChat(
|
||||
identityType, userId, orderId, partnerUid, fadanPingtai || isCross, groupName, isCross
|
||||
);
|
||||
|
||||
const realGroupId = chatData.groupId;
|
||||
let avatar = chatData.counterpartAvatar || chatData.groupAvatar || groupAvatar || '';
|
||||
if (avatar && !avatar.startsWith('http')) {
|
||||
avatar = app.globalData.ossImageUrl + avatar.replace(/^\//, '');
|
||||
}
|
||||
|
||||
if (!app.globalData.groupInfoMap) app.globalData.groupInfoMap = {};
|
||||
const meta = {
|
||||
name: chatData.counterpartName || chatData.groupName || groupName,
|
||||
avatar,
|
||||
orderId: chatData.orderId || orderId,
|
||||
orderDesc: chatData.orderDesc || '',
|
||||
orderZhuangtai: chatData.orderZhuangtai,
|
||||
dashouGoEasyId: chatData.dashouGoEasyId,
|
||||
partnerGoEasyId: chatData.partnerGoEasyId,
|
||||
dashouYonghuid: chatData.dashouYonghuid,
|
||||
partnerYonghuid: chatData.partnerYonghuid,
|
||||
dashouName: chatData.dashouName,
|
||||
partnerName: chatData.partnerName,
|
||||
dashouAvatar: chatData.dashouAvatar,
|
||||
partnerAvatar: chatData.partnerAvatar,
|
||||
counterpartId: chatData.counterpartId,
|
||||
counterpartYonghuid: chatData.counterpartYonghuid,
|
||||
};
|
||||
app.globalData.groupInfoMap[realGroupId] = meta;
|
||||
persistGroupMeta(app, realGroupId, meta);
|
||||
|
||||
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/group-chat/group-chat?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: formatError(err), icon: 'none', duration: 2500 });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default new ConnectionManager();
|
||||
|
||||
Reference in New Issue
Block a user