Files
cashier_wx/stores/chat.js
2025-12-04 17:14:47 +08:00

126 lines
2.7 KiB
JavaScript

import {
defineStore
} from "pinia";
// import * as shopApi from "@/http/api/shop.js";
// #ifdef H5
const socketUrl = "http://192.168.1.42:2348";
// #endif
// #ifndef H5
const socketUrl = "ws://192.168.1.42:2348";
// #endif
// 聊天
export const useChatStore = defineStore("chat", {
state: () => {
return {
socketUrl,
isConnect: false,
socketTask: null,
onReceiveMsg: () => {},
chatList: [],
};
},
actions: {
init() {
if (!this.isConnect) {
return uni.showToast({
title: "请先连接socket",
icon: "none",
});
}
this.sendMessage({
type: "OnbocChat",
operate_type: "init",
shop_id: uni.cache.get('shopInfo').id || '',
token: uni.cache.get('token'),
},
false
);
},
sendMessage(msg, isAutoAppend = true) {
if (!this.isConnect) {
return uni.showToast({
title: "请先连接socket",
icon: "none",
});
}
console.log(this.socketTask);
const message = isAutoAppend ? {
type: "OnbocChat",
operate_type: "sendMsg",
shop_id: uni.cache.get('shopInfo').id || '',
token: uni.cache.get('token'),
...msg,
} :
msg;
this.socketTask.send({
data: JSON.stringify(message),
success: (res) => {
console.log("发送成功", message);
},
fail: (error) => {
console.log("发送失败", error);
},
});
},
connectSocket() {
this.socketTask = uni.connectSocket({
url: socketUrl,
success: (res) => {},
fail: (res) => {
console.log(res);
},
});
this.socketTask.onOpen((res) => {
this.isConnect = true;
this.init();
});
this.socketTask.onMessage((res) => {
const data = JSON.parse(res.data);
console.log("收到服务器消息", data);
if (data.msg) {
uni.showToast({
title: data.msg,
icon: "none",
});
}
if (data && data.operate_type == "sendMsg") {
this.chatList.unshift(data.data);
this.onReceiveMsg(data.data);
console.log(this.chatList);
}
if (data && data.operate_type == "receive_msg") {
const msg={
...data.data,
coupon:data.data.coupon?JSON.parse(data.data.coupon):{},
operate_type:"receive_msg",
}
this.chatList.unshift(msg);
this.onReceiveMsg(msg);
console.log(this.chatList);
}
});
this.socketTask.onError((res) => {
this.isConnect = false;
console.log("连接错误", res);
});
this.socketTask.onClose(() => {
this.isConnect = false;
console.log("连接已关闭");
this.connectSocket();
});
},
closeSocket() {
this.socketTask.close();
this.isConnect = false;
},
},
unistorage: false, // 开启后对 state 的数据读写都将持久化
});