index.vue 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. <template>
  2. <s-layout class="chat-wrap" :title="!isReconnecting ? '连接客服成功' : '会话重连中'" navbar="inner">
  3. <!-- <view class="dropdownClass">
  4. <u-dropdown>
  5. <u-dropdown-item v-model="value1" :title="options1[value1 - 1].label" :options="options1"></u-dropdown-item>
  6. </u-dropdown>
  7. </view> -->
  8. <!-- 覆盖头部导航栏背景颜色 -->
  9. <view class="page-bg" :style="{ height: sys_navBar + 'px' }"></view>
  10. <!-- 聊天区域 -->
  11. <MessageList ref="messageListRef">
  12. <template #bottom>
  13. <message-input :loading="loadingInput" v-model="chat.msg" @on-tools="onTools"
  14. @send-message="onSendMessage"></message-input>
  15. </template>
  16. </MessageList>
  17. <!-- 聊天工具 -->
  18. <tools-popup :show-tools="chat.showTools" :tools-mode="chat.toolsMode" @close="handleToolsClose" @on-emoji="onEmoji"
  19. @image-select="onSelect" @on-show-select="onShowSelect">
  20. <message-input v-model="chat.msg" @on-tools="onTools" @send-message="onSendMessage"></message-input>
  21. </tools-popup>
  22. <!-- 产品订单选择 -->
  23. <SelectPopup :mode="chat.selectMode" :show="chat.showSelect" @select="onSelect" @close="chat.showSelect = false" />
  24. <EventSource ref="EventSourceRef" :url="eventSourceUrl" :options="eventSourceOptions" @callback="handleCallback" />
  25. </s-layout>
  26. </template>
  27. <script setup>
  28. import MessageList from '@/pages/chat/components/messageList.vue';
  29. import EventSource from '@/pages/chat/components/eventSource.vue';
  30. import { reactive, ref, toRefs, computed, provide } from 'vue';
  31. import sheep from '@/sheep';
  32. import ToolsPopup from '@/pages/chat/components/toolsPopup.vue';
  33. import MessageInput from '@/pages/chat/components/messageInput.vue';
  34. import SelectPopup from '@/pages/chat/components/select-popup.vue';
  35. import {
  36. KeFuMessageContentTypeEnum,
  37. WebSocketMessageTypeConstants,
  38. } from '@/pages/chat/util/constants';
  39. import FileApi from '@/sheep/api/infra/file';
  40. import KeFuApi from '@/sheep/api/promotion/kefu';
  41. import { useWebSocket } from '@/sheep/hooks/useWebSocket';
  42. import { jsonParse } from '@/sheep/util';
  43. import { onLoad } from '@dcloudio/uni-app';
  44. const EventSourceRef = ref(null); //AIref
  45. const chatMsgData = ref({});
  46. const eventSourceUrl = import.meta.env.SHOPRO_BASE_URL + "/app-api/promotion/kefu-message/sendStream"; //ai客服URL
  47. // const eventSourceUrl = "https://192.168.10.17:9095/app-api/infra/ai-dify/chat-messages-stream"; //ai客服URL
  48. // ai客服流式上传参数
  49. const eventSourceOptions = computed(() => {
  50. return {
  51. headers: {
  52. "content-type": "application/json",
  53. Accept: "text/event-stream",
  54. "tenant-id": 1,
  55. Authorization: "Bearer " + uni.getStorageSync('token'),
  56. },
  57. method: "POST",
  58. body: JSON.stringify({
  59. "contentType": 1,
  60. "content": chatMsgData.value.content || chat.msg,
  61. "relUserId": route.value.relUserId
  62. // type: "律师咨询",
  63. // query: chat.msg
  64. }), // 请求体
  65. };
  66. });
  67. const answerArr = ref('');
  68. const loadingInput = ref(false); // 加载状态
  69. provide('loadingInput', loadingInput); // 依赖注入加载状态
  70. const EventSourceFun = async (data, is = true) => {
  71. chatMsgData.value = data;
  72. const avatarObj = messageListRef.value.getAvatar() || {}
  73. const params = {
  74. id: 1,
  75. conversationId: route.value.conversationId,
  76. senderId: userInfo.value.id,
  77. senderAvatar: avatarObj.senderAvatar || '',
  78. senderType: 1,
  79. receiverId: route.value.relUserId,
  80. receiverAvatar: avatarObj.receiverAvatar || '',
  81. receiverType: null,
  82. contentType: 1,
  83. content: is ? (JSON.stringify({ text: chat.msg })) : data.content,
  84. readStatus: true,
  85. createTime: 1745546275000
  86. }
  87. await messageListRef.value.refreshMessageList(params);
  88. const params1 = {
  89. ids: 1,
  90. isAi: true,
  91. isLoading: true,
  92. conversationId: route.value.conversationId,
  93. senderId: route.value.relUserId,
  94. senderAvatar: avatarObj.receiverAvatar || '',
  95. senderType: 1,
  96. receiverId: userInfo.value.id,
  97. receiverAvatar: avatarObj.senderAvatar || '',
  98. receiverType: null,
  99. contentType: 22,
  100. content: '',
  101. readStatus: true,
  102. createTime: 1745546275000
  103. }
  104. await messageListRef.value.refreshMessageList(params1);
  105. console.log(data, 22222);
  106. await EventSourceRef.value.send(data);
  107. }
  108. provide('EventSourceFun', EventSourceFun); // 依赖注入加载状态
  109. const loadingId = ref(""); // 加载的id
  110. // ai客服发送消息接收回调
  111. const handleCallback = async (e) => {
  112. const { type, msg, data } = e || {};
  113. if (type == "onmessage") {
  114. const datas = JSON.parse(data);
  115. console.log("张耀文", datas)
  116. answerArr.value += datas.content;
  117. loadingId.value = datas.messageId
  118. await messageListRef.value.updateMessage(datas);
  119. }
  120. if (type == "onclose") {
  121. loadingInput.value = false;
  122. await messageListRef.value.updateMessage({}, loadingId.value);
  123. answerArr.value = ""
  124. }
  125. };
  126. const sys_navBar = sheep.$platform.navbar;
  127. const options1 = [{
  128. label: 'ai',
  129. value: 1,
  130. },
  131. {
  132. label: '律师咨询',
  133. value: 2,
  134. },
  135. {
  136. label: '金融相关',
  137. value: 3,
  138. }
  139. ]
  140. const value1 = ref(1)
  141. const chat = reactive({
  142. msg: '',
  143. scrollInto: '',
  144. showTools: false,
  145. toolsMode: '',
  146. showSelect: false,
  147. selectMode: '',
  148. });
  149. const route = ref({})
  150. onLoad((options) => {
  151. route.value = options
  152. });
  153. const userInfo = computed(() => sheep.$store('user').userInfo);
  154. // 发送消息
  155. async function onSendMessage() {
  156. if (!chat.msg) return;
  157. try {
  158. loadingInput.value = true;
  159. const idArr = ['1', '2', '3', '4']
  160. const data = {
  161. conversationId: route.value.conversationId,
  162. contentType: KeFuMessageContentTypeEnum.TEXT,
  163. content: JSON.stringify({ text: chat.msg }),
  164. relUserId: route.value.relUserId
  165. };
  166. // 如果在线就走直接发消息 如果不在线就走ai回复
  167. const res = await KeFuApi.checkUserId({
  168. userId: route.value.relUserId
  169. })
  170. if (res.data) {
  171. await KeFuApi.sendKefuMessageNew(data);
  172. } else {
  173. if (idArr.includes(route.value.relUserId)) {
  174. await EventSourceFun(data);
  175. } else {
  176. await KeFuApi.sendKefuMessageNew(data);
  177. }
  178. }
  179. chat.msg = '';
  180. } finally {
  181. chat.showTools = false;
  182. }
  183. }
  184. const messageListRef = ref();
  185. //======================= 聊天工具相关 start =======================
  186. function handleToolsClose() {
  187. chat.showTools = false;
  188. chat.toolsMode = '';
  189. }
  190. function onEmoji(item) {
  191. chat.msg += item.name;
  192. }
  193. // 点击工具栏开关
  194. function onTools(mode) {
  195. if (isReconnecting.value) {
  196. sheep.$helper.toast('您已掉线!请返回重试');
  197. return;
  198. }
  199. if (!chat.toolsMode || chat.toolsMode === mode) {
  200. chat.showTools = !chat.showTools;
  201. }
  202. chat.toolsMode = mode;
  203. if (!chat.showTools) {
  204. chat.toolsMode = '';
  205. }
  206. }
  207. function onShowSelect(mode) {
  208. chat.showTools = false;
  209. chat.showSelect = true;
  210. chat.selectMode = mode;
  211. }
  212. async function onSelect({ type, data }) {
  213. console.log(data, 555222233)
  214. let msg;
  215. switch (type) {
  216. case 'image':
  217. const res = await FileApi.uploadFile(data.tempFiles[0].path);
  218. msg = {
  219. contentType: KeFuMessageContentTypeEnum.IMAGE,
  220. content: JSON.stringify({ picUrl: res.data }),
  221. conversationId: route.value.conversationId,
  222. };
  223. break;
  224. case 'goods':
  225. msg = {
  226. contentType: KeFuMessageContentTypeEnum.PRODUCT,
  227. content: JSON.stringify(data),
  228. conversationId: route.value.conversationId,
  229. };
  230. break;
  231. case 'order':
  232. msg = {
  233. contentType: KeFuMessageContentTypeEnum.ORDER,
  234. content: JSON.stringify(data),
  235. conversationId: route.value.conversationId,
  236. };
  237. break;
  238. }
  239. if (msg) {
  240. // 发送消息
  241. // scrollBottom();
  242. // await KeFuApi.sendKefuMessage(msg);
  243. await KeFuApi.listSendNew(msg);
  244. await messageListRef.value.refreshMessageList();
  245. chat.showTools = false;
  246. chat.showSelect = false;
  247. chat.selectMode = '';
  248. }
  249. }
  250. //======================= 聊天工具相关 end =======================
  251. const { options } = useWebSocket({
  252. // 连接成功
  253. onConnected: async () => { },
  254. // 收到消息
  255. onMessage: async (data) => {
  256. console.log(data, 'data');
  257. const type = data.type;
  258. if (!type) {
  259. console.error('未知的消息类型:' + data);
  260. return;
  261. }
  262. // 2.2 消息类型:KEFU_MESSAGE_TYPE
  263. if (type === WebSocketMessageTypeConstants.KEFU_MESSAGE_IM) {
  264. console.log('客服消息IM');
  265. // 刷新消息列表
  266. await messageListRef.value.refreshMessageList(jsonParse(data.content));
  267. return;
  268. }
  269. // 2.3 消息类型:KEFU_MESSAGE_ADMIN_READ
  270. if (type === WebSocketMessageTypeConstants.KEFU_MESSAGE_ADMIN_READ) {
  271. console.log('管理员已读消息');
  272. }
  273. },
  274. });
  275. const isReconnecting = toRefs(options).isReconnecting; // 重连状态
  276. </script>
  277. <style scoped lang="scss">
  278. :deep(.z-paging-content-fixed) {
  279. // background: red;
  280. // top: 40px;
  281. }
  282. :deep(.zp-paging-container-content) {
  283. padding: 0px 10px;
  284. }
  285. .dropdownClass {
  286. box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  287. }
  288. .chat-wrap {
  289. .page-bg {
  290. width: 100%;
  291. position: absolute;
  292. top: 0;
  293. left: 0;
  294. background-color: #000;
  295. z-index: 1;
  296. }
  297. .status {
  298. position: relative;
  299. box-sizing: border-box;
  300. z-index: 3;
  301. height: 70rpx;
  302. padding: 0 30rpx;
  303. background: var(--ui-BG-Main-opacity-1);
  304. display: flex;
  305. align-items: center;
  306. font-size: 30rpx;
  307. font-weight: 400;
  308. color: var(--ui-BG-Main);
  309. }
  310. }
  311. </style>