123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328 |
- <template>
- <s-layout class="chat-wrap" :title="!isReconnecting ? '连接客服成功' : '会话重连中'" navbar="inner">
- <!-- <view class="dropdownClass">
- <u-dropdown>
- <u-dropdown-item v-model="value1" :title="options1[value1 - 1].label" :options="options1"></u-dropdown-item>
- </u-dropdown>
- </view> -->
- <!-- 覆盖头部导航栏背景颜色 -->
- <view class="page-bg" :style="{ height: sys_navBar + 'px' }"></view>
- <!-- 聊天区域 -->
- <MessageList ref="messageListRef">
- <template #bottom>
- <message-input :loading="loadingInput" v-model="chat.msg" @on-tools="onTools"
- @send-message="onSendMessage"></message-input>
- </template>
- </MessageList>
- <!-- 聊天工具 -->
- <tools-popup :show-tools="chat.showTools" :tools-mode="chat.toolsMode" @close="handleToolsClose" @on-emoji="onEmoji"
- @image-select="onSelect" @on-show-select="onShowSelect">
- <message-input v-model="chat.msg" @on-tools="onTools" @send-message="onSendMessage"></message-input>
- </tools-popup>
- <!-- 产品订单选择 -->
- <SelectPopup :mode="chat.selectMode" :show="chat.showSelect" @select="onSelect" @close="chat.showSelect = false" />
- <EventSource ref="EventSourceRef" :url="eventSourceUrl" :options="eventSourceOptions" @callback="handleCallback" />
- </s-layout>
- </template>
- <script setup>
- import MessageList from '@/pages/chat/components/messageList.vue';
- import EventSource from '@/pages/chat/components/eventSource.vue';
- import { reactive, ref, toRefs, computed, provide } from 'vue';
- import sheep from '@/sheep';
- import ToolsPopup from '@/pages/chat/components/toolsPopup.vue';
- import MessageInput from '@/pages/chat/components/messageInput.vue';
- import SelectPopup from '@/pages/chat/components/select-popup.vue';
- import {
- KeFuMessageContentTypeEnum,
- WebSocketMessageTypeConstants,
- } from '@/pages/chat/util/constants';
- import FileApi from '@/sheep/api/infra/file';
- import KeFuApi from '@/sheep/api/promotion/kefu';
- import { useWebSocket } from '@/sheep/hooks/useWebSocket';
- import { jsonParse } from '@/sheep/util';
- import { onLoad } from '@dcloudio/uni-app';
- const EventSourceRef = ref(null); //AIref
- const chatMsgData = ref({});
- const eventSourceUrl = import.meta.env.SHOPRO_BASE_URL + "/app-api/promotion/kefu-message/sendStream"; //ai客服URL
- // const eventSourceUrl = "https://192.168.10.17:9095/app-api/infra/ai-dify/chat-messages-stream"; //ai客服URL
- // ai客服流式上传参数
- const eventSourceOptions = computed(() => {
- return {
- headers: {
- "content-type": "application/json",
- Accept: "text/event-stream",
- "tenant-id": 1,
- Authorization: "Bearer " + uni.getStorageSync('token'),
- },
- method: "POST",
- body: JSON.stringify({
- "contentType": 1,
- "content": chatMsgData.value.content || chat.msg,
- "relUserId": route.value.relUserId
- // type: "律师咨询",
- // query: chat.msg
- }), // 请求体
- };
- });
- const answerArr = ref('');
- const loadingInput = ref(false); // 加载状态
- provide('loadingInput', loadingInput); // 依赖注入加载状态
- const EventSourceFun = async (data, is = true) => {
- chatMsgData.value = data;
- const avatarObj = messageListRef.value.getAvatar() || {}
- const params = {
- id: 1,
- conversationId: route.value.conversationId,
- senderId: userInfo.value.id,
- senderAvatar: avatarObj.senderAvatar || '',
- senderType: 1,
- receiverId: route.value.relUserId,
- receiverAvatar: avatarObj.receiverAvatar || '',
- receiverType: null,
- contentType: 1,
- content: is ? (JSON.stringify({ text: chat.msg })) : data.content,
- readStatus: true,
- createTime: 1745546275000
- }
- await messageListRef.value.refreshMessageList(params);
- const params1 = {
- ids: 1,
- isAi: true,
- isLoading: true,
- conversationId: route.value.conversationId,
- senderId: route.value.relUserId,
- senderAvatar: avatarObj.receiverAvatar || '',
- senderType: 1,
- receiverId: userInfo.value.id,
- receiverAvatar: avatarObj.senderAvatar || '',
- receiverType: null,
- contentType: 22,
- content: '',
- readStatus: true,
- createTime: 1745546275000
- }
- await messageListRef.value.refreshMessageList(params1);
- console.log(data, 22222);
- await EventSourceRef.value.send(data);
- }
- provide('EventSourceFun', EventSourceFun); // 依赖注入加载状态
- const loadingId = ref(""); // 加载的id
- // ai客服发送消息接收回调
- const handleCallback = async (e) => {
- const { type, msg, data } = e || {};
- if (type == "onmessage") {
- const datas = JSON.parse(data);
- console.log("张耀文", datas)
- answerArr.value += datas.content;
- loadingId.value = datas.messageId
- await messageListRef.value.updateMessage(datas);
- }
- if (type == "onclose") {
- loadingInput.value = false;
- await messageListRef.value.updateMessage({}, loadingId.value);
- answerArr.value = ""
- }
- };
- const sys_navBar = sheep.$platform.navbar;
- const options1 = [{
- label: 'ai',
- value: 1,
- },
- {
- label: '律师咨询',
- value: 2,
- },
- {
- label: '金融相关',
- value: 3,
- }
- ]
- const value1 = ref(1)
- const chat = reactive({
- msg: '',
- scrollInto: '',
- showTools: false,
- toolsMode: '',
- showSelect: false,
- selectMode: '',
- });
- const route = ref({})
- onLoad((options) => {
- route.value = options
- });
- const userInfo = computed(() => sheep.$store('user').userInfo);
- // 发送消息
- async function onSendMessage() {
- if (!chat.msg) return;
- try {
- loadingInput.value = true;
- const idArr = ['1', '2', '3', '4']
- const data = {
- conversationId: route.value.conversationId,
- contentType: KeFuMessageContentTypeEnum.TEXT,
- content: JSON.stringify({ text: chat.msg }),
- relUserId: route.value.relUserId
- };
- // 如果在线就走直接发消息 如果不在线就走ai回复
- const res = await KeFuApi.checkUserId({
- userId: route.value.relUserId
- })
- if (res.data) {
- await KeFuApi.sendKefuMessageNew(data);
- } else {
- if (idArr.includes(route.value.relUserId)) {
- await EventSourceFun(data);
- } else {
- await KeFuApi.sendKefuMessageNew(data);
- }
- }
- chat.msg = '';
- } finally {
- chat.showTools = false;
- }
- }
- const messageListRef = ref();
- //======================= 聊天工具相关 start =======================
- function handleToolsClose() {
- chat.showTools = false;
- chat.toolsMode = '';
- }
- function onEmoji(item) {
- chat.msg += item.name;
- }
- // 点击工具栏开关
- function onTools(mode) {
- if (isReconnecting.value) {
- sheep.$helper.toast('您已掉线!请返回重试');
- return;
- }
- if (!chat.toolsMode || chat.toolsMode === mode) {
- chat.showTools = !chat.showTools;
- }
- chat.toolsMode = mode;
- if (!chat.showTools) {
- chat.toolsMode = '';
- }
- }
- function onShowSelect(mode) {
- chat.showTools = false;
- chat.showSelect = true;
- chat.selectMode = mode;
- }
- async function onSelect({ type, data }) {
- console.log(data, 555222233)
- let msg;
- switch (type) {
- case 'image':
- const res = await FileApi.uploadFile(data.tempFiles[0].path);
- msg = {
- contentType: KeFuMessageContentTypeEnum.IMAGE,
- content: JSON.stringify({ picUrl: res.data }),
- conversationId: route.value.conversationId,
- };
- break;
- case 'goods':
- msg = {
- contentType: KeFuMessageContentTypeEnum.PRODUCT,
- content: JSON.stringify(data),
- conversationId: route.value.conversationId,
- };
- break;
- case 'order':
- msg = {
- contentType: KeFuMessageContentTypeEnum.ORDER,
- content: JSON.stringify(data),
- conversationId: route.value.conversationId,
- };
- break;
- }
- if (msg) {
- // 发送消息
- // scrollBottom();
- // await KeFuApi.sendKefuMessage(msg);
- await KeFuApi.listSendNew(msg);
- await messageListRef.value.refreshMessageList();
- chat.showTools = false;
- chat.showSelect = false;
- chat.selectMode = '';
- }
- }
- //======================= 聊天工具相关 end =======================
- const { options } = useWebSocket({
- // 连接成功
- onConnected: async () => { },
- // 收到消息
- onMessage: async (data) => {
- console.log(data, 'data');
- const type = data.type;
- if (!type) {
- console.error('未知的消息类型:' + data);
- return;
- }
- // 2.2 消息类型:KEFU_MESSAGE_TYPE
- if (type === WebSocketMessageTypeConstants.KEFU_MESSAGE_IM) {
- console.log('客服消息IM');
- // 刷新消息列表
- await messageListRef.value.refreshMessageList(jsonParse(data.content));
- return;
- }
- // 2.3 消息类型:KEFU_MESSAGE_ADMIN_READ
- if (type === WebSocketMessageTypeConstants.KEFU_MESSAGE_ADMIN_READ) {
- console.log('管理员已读消息');
- }
- },
- });
- const isReconnecting = toRefs(options).isReconnecting; // 重连状态
- </script>
- <style scoped lang="scss">
- :deep(.z-paging-content-fixed) {
- // background: red;
- // top: 40px;
- }
- :deep(.zp-paging-container-content) {
- padding: 0px 10px;
- }
- .dropdownClass {
- box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
- }
- .chat-wrap {
- .page-bg {
- width: 100%;
- position: absolute;
- top: 0;
- left: 0;
- background-color: #000;
- z-index: 1;
- }
- .status {
- position: relative;
- box-sizing: border-box;
- z-index: 3;
- height: 70rpx;
- padding: 0 30rpx;
- background: var(--ui-BG-Main-opacity-1);
- display: flex;
- align-items: center;
- font-size: 30rpx;
- font-weight: 400;
- color: var(--ui-BG-Main);
- }
- }
- </style>
|