index.vue 9.1 KB

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