You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
shop-app/common/utils/websocket.js

107 lines
3.2 KiB

3 years ago
/*
* @Author: ch
* @Date: 2022-04-25 14:39:19
* @LastEditors: ch
* @LastEditTime: 2022-04-26 16:28:01
* @Description: file content
*/
import store from "../store";
import {createUUID, formatDate} from '@/common/utils';
export const MsbWebSkt = uni.connectSocket({
url : `ws://192.168.10.92:8090/ws?client=${store.state.token}`, // url是websocket连接ip
success: () => {
console.log('websocket连接成功')
},
fail: e => {
console.log('连接失败' + e)
}
});
MsbWebSkt.onClose(()=>{
console.log('WebSocket关闭...')
})
let sessionListFlag = false;
MsbWebSkt.onMessage((res)=>{
const data = JSON.parse(res.data || {});
if(data.code === 200){
const ctx = data.content;
switch(data.traceType){
// 会话列表
case 1 :
sessionListFlag = true;
// 来新消息先查会话列表是否一存在,存在则加消息数。不存在则向会话列表加一个会话框
ctx.sessionVOS.forEach(item => {
item.lastMessage.createTimeStamp = formatDate(item.lastMessage.createTimeStamp, 'mm-dd hh:ii')
item.lastMessage.payload = JSON.parse(item.lastMessage.payload || {});
let historyData = store.state.sessionData;
let hisIndex = historyData.findIndex(i => i.id === item.id);
if(hisIndex >= 0){
historyData[hisIndex].lastMessage = item.lastMessage;
historyData[hisIndex].unreadCount++;
store.commit('SET_SESSION_DATA', historyData);
}else{
item.messageList = [];
store.commit('SET_SESSION_DATA',[...historyData, item]);
}
});
// 消息总数
store.commit('SET_SESSION_MSG_COUNT', ctx.totalUnreadCount || 10);
break;
// 历史消息
case 2 :
let newData = store.state.sessionData;
const hisIdx = newData.findIndex(i => i.id === ctx[0].sessionId);
ctx.forEach(item => {
item.createTimeStamp = formatDate(item.createTimeStamp, 'mm-dd hh:ii')
item.payload = JSON.parse(item.payload)
})
newData[hisIdx].messageList = ctx.concat(newData[hisIdx].messageList);
store.commit('SET_SESSION_DATA', newData);
console.log(newData);
break;
// 会话消息
case 7 :
// 没接到会话列表时接到的消息不做处理
if(!sessionListFlag){
break;
}
// ctx.forEach(item => {
ctx.payload = JSON.parse(ctx.payload || {});
let historyData = store.state.sessionData;
const hisIndex = historyData.findIndex(i => i.id === ctx.sessionId);
store.commit('SET_SESSION_MSG_COUNT', store.state.sessionMsgCount + 1);
if(hisIndex >= 0){
// 存在会话往现有会话增加一条消息
const curHisData = historyData[hisIndex];
curHisData.messageList = [ ...(curHisData.messageList || []), ctx]
curHisData.unreadCount++;
store.commit('SET_SESSION_DATA', historyData);
}else{
// 会话列表不存在,则创建一个会话
store.commit('SET_SESSION_DATA',[...historyData, {
fromAvatar : ctx.fromAvatar,
fromId : ctx.fromId,
fromNickname : ctx.fromNickname,
id : ctx.id,
lastMessage : ctx,
messageList : [ctx],
unreadCount : 1
}]);
}
// });
break;
default :
break;
}
}
})
MsbWebSkt.onError(()=>{
console.log('WebSocket连接错误')
})