Browse Source

feat: 封装socket类

qinyuyue 2 months ago
parent
commit
7a4d829ce4

+ 16 - 20
src/pages/chat/chat-message/index.vue

@@ -1,10 +1,10 @@
-<template v-if="message">
+<template v-if="msg">
   <div class="chat-message" :class="msg.viewType ? 'chat-message--accept' : 'chat-message--send'">
-    <div class="text-center text-sm text-[#000]/40 mb-16">{{ message.createTime }}</div>
+    <div class="text-center text-sm text-[#000]/40 mb-16">{{ msg.createTime }}</div>
     <div class="chat-message__content">
       <van-image
           v-if="msg.viewType === 1"
-          :src="curConversiton?.headImage || defaultAvatar"
+          :src="defaultAvatar"
           width="40px"
           height="40px"
           radius="100%"
@@ -26,7 +26,7 @@
 <!--      <div class="self-center text-sm mx-5 text-black-9">发送中</div>-->
       <van-image
           v-if="msg.viewType === 0"
-          :src="user?.headImageUrl || defaultAvatar"
+          :src="userInfo?.headImageUrl || defaultAvatar"
           width="40px"
           height="40px"
           radius="100%"
@@ -41,11 +41,9 @@ import TextMessage from "~/pages/chat/chat-message/text-message/index.vue";
 import ImageMessage from "~/pages/chat/chat-message/image-message/index.vue";
 import AudioMessage from "~/pages/chat/chat-message/audio-message/index.vue";
 import LinkMessage from "~/pages/chat/chat-message/link-message/index.vue";
-import {isValidJson} from "~/utils";
 
-const chatStore = useChatStore()
-const user = computed(() => chatStore.user)
-const {curConversiton} = storeToRefs(chatStore)
+const userInfoStore = useUserInfoStore();
+const {userInfo} = storeToRefs(userInfoStore);
 
 const props = defineProps({
   message: Object,
@@ -54,29 +52,27 @@ const props = defineProps({
     default: false
   }
 });
-
-let msg = ref(null)
-const initMsg = () => {
+const msg = computed(() => {
   try {
-    if (!isValidJson(props.message?.messageContent)) return
-    const {createTime, getUserId, sendUserId, messageContent} = JSON.parse(props.message?.messageContent)
-    msg.value = {
+    const {createTime, getUserId, sendUserId, messageContent, messageType} = props.message
+    console.log(messageType, 'props.message')
+    console.log(sendUserId, userInfo?.value, 'userInfouserInfouserInfo', sendUserId === userInfo?.value.pass)
+    return {
       messageContent: messageContent,
-      type: getMessageType(props.message?.messageType),
-      viewType: props.message?.sendUserId === user.value.pass ? 0 : 1,
+      type: getMessageType(messageType),
+      viewType: sendUserId === userInfo?.value.pass ? 0 : 1,
       createTime: createTime,
       showName: props.message?.showName
     }
   } catch (e) {
-
+    console.log(e, '??')
+    return null
   }
-}
-
+})
 const getMessageType = (messageType) => {
   const types = ['text', 'image', 'audio', 'video', 'link']
   return types[messageType]
 }
-initMsg()
 </script>
 <style scoped lang="scss">
 .chat-message {

+ 1 - 1
src/pages/chat/chat-message/text-message/index.vue

@@ -16,7 +16,7 @@ initMessage()
 
 <template>
   <div class="text-message" :class="viewType ? 'text-message--accept' : 'text-message--send'">
-    {{ textString }}
+    {{messageContent}} <!--{{ textString }}-->
   </div>
 </template>
 

+ 141 - 132
src/pages/chat/single.vue

@@ -3,7 +3,7 @@
     <van-nav-bar @click-left="router.back()" @click-right="onClickRight">
       <template #left>
         <div>
-          <van-icon name="arrow-left" color="black" size="18" />
+          <van-icon name="arrow-left" color="black" size="18"/>
         </div>
       </template>
       <template #title>
@@ -15,142 +15,128 @@
         </div>
       </template>
       <template #right>
-        <van-icon name="ellipsis" color="black" size="18" />
+        <van-icon name="ellipsis" color="black" size="18"/>
       </template>
     </van-nav-bar>
-    <van-list
-        ref="chatListRef"
-        class="flex-1 overflow-y-auto px-12 flex flex-col"
-        :finished="true"
-        finished-text=""
-    >
-      <template v-for="(message, index) in receiveGetter" :key="index">
-        <ChatMessage :message="message"></ChatMessage>
-      </template>
-      <div v-if="false" class="text-[#979797] text-sm text-center mt-auto mb-10">{{followStatus}}在对方关注或回复前,最多只能发送1条信息</div>
-    </van-list>
-    <ChatInput :operates="['image']"  @focus="scrollToBottom" @send="handleSendMessage"></ChatInput>
+    <template v-if="showPage">
+      {{sendUserId}}
+      <van-list
+          ref="chatListRef"
+          class="flex-1 overflow-y-auto px-12 flex flex-col"
+          :finished="true"
+          finished-text=""
+      >
+        <template v-for="(message, index) in currConversationChatList" :key="index">
+          <ChatMessage :message="message" ></ChatMessage>
+        </template>
+        <div v-if="false" class="text-[#979797] text-sm text-center mt-auto mb-10">
+          {{ followStatus }}在对方关注或回复前,最多只能发送1条信息
+        </div>
+      </van-list>
+      <ChatInput :operates="['image']" @focus="scrollToBottom" @send="handleSendMessage"></ChatInput>
+    </template>
+    <template v-else>
+      <div class="flex-1 grid place-items-center text-black-9">
+        <div v-if="pageLoading">创建会话中...</div>
+        <div v-else class="grid place-items-center">
+          <div v-if="groupId">创建成功</div>
+          <div v-else class="grid place-items-center">
+            <div  class="mb-10">创建会话失败</div>
+            <van-button size="small" @click="initGroupId">点击重试</van-button>
+          </div>
+        </div>
+      </div>
+    </template>
   </div>
 </template>
 <script setup>
 import ChatMessage from './chat-message'
 import ChatInput from "./chat-input";
 import {findHyperlinks} from "~/pages/chat/chat-message/link-message/handle";
+import {XYWebSocket} from "~/utils/XYWebSocket";
+import {isValidJson} from "~/utils";
 
 const route = useRoute()
 const router = useRouter()
 const refreshing = ref(false)
-const chatStore = useChatStore();
-const user = computed(() => chatStore.user)
-const {ws, curConversiton, receive, conversations, receiveGetter, connectSta, onNewMessage} = storeToRefs(chatStore)
-console.warn(curConversiton, 'curConversitoncurConversiton')
+const chatsStore = useChatsStore();
+const userInfoStore = useUserInfoStore();
+
+const {userInfo} = storeToRefs(userInfoStore);
 // 单聊的标题
 const title = computed(() => route.query.groupRemark)
 
 // 聊天列表
-const chatListRef = ref(null)
-
-// 当前websocket连接状态 0: 未连接 1: 连接中 2: 已连接 3: 已断开
-// const wsConnect = computed(() => connectSta?.value)
-
-// 消息接收者的用户id
-const getUserId = computed(() => curConversiton?.value.toUserId)
-// 消息发送者:当前登录用户的加密id
-const sendUserId = computed(() => user?.value.pass)
-
-// 会话id
-const groupId = computed(() => route.query.groupId)
+const chatListRef = ref(null);
 
 const followStatus = ref(0)
 
-// 本地生成一个唯一消息id
-function getLocalId() {
-  const random = Math.floor(Math.random() * 10000)
-  return Date.now() + '' + random
-}
-
-// 刷新
-const onRefresh = () => {
-  refreshing.value = false
-}
-
-
-const onClickRight = () => {
-  navigateTo({
-    path: '/chat/set-single',
-    query: {
-      toUserId: route.query.getUserId
-    }
-  })
-}
-
-const pageSize = ref(10)
-
-const messageCount = ref(0)
-
-// 获取聊天记录
-async function getChatHistory(messageId = '') {
-  if (curConversiton.value.isLocal) return
-
-  if (!groupId.value) return
-
-  if (receive.value.length >= messageCount.value && receive.value.length > 0) return
-
-  if (receive.value.length && !messageId) return
-
-  const query = {
-    pageSize: pageSize.value,
-    groupId: groupId.value,
-    messageId
-  }
-
-  const {
-    data: {data = [], count = []}
-  } = await request('/website/tourMessage/getMessageByGroupId', {query})
-
-  messageCount.value = count || 0
+const pageLoading = ref(true);
+const getUserId = ref(route.query?.getUserId); // 消息接收者的用户id
+const sendUserId = computed(() => userInfo?.value.pass) // 消息发送者:当前登录用户的加密id
+const groupId = ref(null); // 会话ID
+const showPage = computed(() => getUserId.value && groupId.value)
+const initGroupId = async () => {
+  try {
+    pageLoading.value = true;
+    if (!getUserId.value) return;
+    const res = await chatsStore.getCurrConversationId(getUserId.value)
+    await handleResponse(res)
+    groupId.value = res.data;
+    await initData()
+  } catch (e) {
 
-  if (Array.isArray(data)) {
-    receive.value = [...data, ...receive.value]
+  } finally {
+    pageLoading.value = false;
   }
-  console.log('历史记录:', data)
-  // 获取到数据后,滚动到底部
-  if (!messageId) await scrollToBottom()
 }
+const currConversationChatList = ref([]);
+const initData = async () => {
+  try {
+    const res = await chatsStore.getChatHistory({
+      pageNum: 1,
+      pageSize: 100,
+      groupId: groupId.value,
+    })
+    await handleResponse(res);
+    currConversationChatList.value = (res.data?.dataList ?? []).filter(o => isValidJson(o.messageContent)).map(o => JSON.parse(o.messageContent));
+    console.log(currConversationChatList.value, 'currConversationChatList')
+    await scrollToBottom()
+    await getFollowStatus()
+  } catch (e) {
+    console.error(e)
+  } finally {
 
-// 获取我与对方的关注情况
-async function getFollowStatus() {
-  const query = {
-    userId: getUserId.value
   }
-  const {data: status = 0} = await request('/website/tourGroup/isFollow', {query})
-  followStatus.value = status
-  console.log('关注情况:', status)
 }
 
 // 发送文本消息
-const sendTextMessage = (text) => {
-  if(!text) return
-  let msg = {
-    groupId: groupId.value,
-    getUserId: getUserId.value,
-    sendUserId: sendUserId.value,
-    specialUserId: '',
-    messageContent: text,
-    messageType: 0,
-    noticeType: 1,
-    object: {
-      id: getLocalId()
+const sendTextMessage = async (text) => {
+  try {
+    console.log(text, 'sendTextMessage')
+    if (!text) return
+    let msg = {
+      groupId: groupId.value,
+      getUserId: getUserId.value,
+      sendUserId: sendUserId.value,
+      specialUserId: '',
+      messageContent: text,
+      messageType: 0,
+      noticeType: 1,
+      object: {
+        id: getLocalId()
+      }
     }
-  }
-  const isLink = !!findHyperlinks(text)
-  if (isLink) msg.messageType = 4;
+    const isLink = !!findHyperlinks(text)
+    if (isLink) msg.messageType = 4;
+/*    currConversationChatList.value.push(msg)*/
+    const res = await chatsStore.sendSocketMessage(msg)
+    console.log('luck:', res)
+  } catch (e) {
+    console.log(e, '2')
+  } finally {
 
-  receive.value.push({
-    ...msg,
-    messageContent: JSON.stringify({messageContent: msg.messageContent})
-  })
-  ws.value.send(JSON.stringify(msg))
+  }
 }
 
 // 选择发送图片
@@ -165,24 +151,20 @@ const sendImageMessage = async (file) => {
       body: formData
     })
 
-    const msg = {
+    let msg = {
       groupId: groupId.value,
       getUserId: getUserId.value,
       sendUserId: sendUserId.value,
       specialUserId: '',
-      messageContent: JSON.stringify({messageContent: data.fileUrl}),
+      messageContent: data.fileUrl,
       messageType: 1,
       noticeType: 1,
       object: {
         id: getLocalId()
       }
     }
-    receive.value.push({
-      ...msg,
-      messageContent: JSON.stringify({messageContent: data.fileUrl})
-    })
-
-    ws.value.send(JSON.stringify(msg))
+    /*currConversationChatList.value.push(msg)*/
+   await chatsStore.sendSocketMessage(msg)
   } catch (e) {
     console.error(e, '??')
   } finally {
@@ -194,11 +176,15 @@ const handleSendMessage = async ({type, messageContent}) => {
   try {
     switch (type) {
       case 'text':
-        sendTextMessage(messageContent)
+        await sendTextMessage(messageContent)
         break;
       case 'image':
         await sendImageMessage(messageContent)
         break;
+
+      default:
+
+        break;
     }
     await scrollToBottom()
   } catch (e) {
@@ -209,7 +195,6 @@ const handleSendMessage = async ({type, messageContent}) => {
 
 }
 
-
 const scrollToBottom = async () => {
   await nextTick(); // 确保DOM已经更新
   const listElement = chatListRef.value?.$el;
@@ -219,26 +204,50 @@ const scrollToBottom = async () => {
   }
 };
 
+// 获取我与对方的关注情况
+const getFollowStatus = async () => {
+  const query = {
+    userId: getUserId.value
+  }
+  const {data: status = 0} = await request('/website/tourGroup/isFollow', {query})
+  followStatus.value = status
+}
+
 
-watch(groupId, () => {
-  // 消息置空
-  // receive.value = []
-})
+// 刷新
+const onRefresh = () => {
+  refreshing.value = false
+}
+
+const onClickRight = () => {
+  navigateTo({
+    path: '/chat/set-single',
+    query: {
+      toUserId: route.query.getUserId
+    }
+  })
+}
 
-watchEffect(onNewMessage, () => {
-  scrollToBottom()
-})
+
+// 本地生成一个唯一消息id
+function getLocalId() {
+  const random = Math.floor(Math.random() * 10000)
+  return Date.now() + '' + random
+}
 
 onMounted(() => {
-  // 获取前会话用户的聊天记录
-  getChatHistory()
+  initGroupId()
+  XYWebSocket.SocketEventsBus.on(XYWebSocket.SocketEvents.chatEvent, async (chat) => {
+    console.log('XYWebSocket', chat)
+    if (chat.groupId && chat.groupId === groupId.value) {
+     // await initData()
+      currConversationChatList.value.push(chat)
+    }
+  })
+})
 
-  // 获取与当前会话用户的关注状态
-  getFollowStatus()
+watchEffect(() => {
 
-  // setTimeout(() => {
-  //   scrollToBottom()
-  // }, 500)
 })
 
 definePageMeta({

+ 142 - 146
src/pages/profile/my-news/index.vue

@@ -1,30 +1,30 @@
 <template>
   <div class="w-full">
-<!--    <audio
-      class="fixed top-0 left-0"
-      ref="audioRef"
-      :src="audioTips"
-      style="opacity: 0; z-index: -1"
-    ></audio>-->
+    <!--    <audio
+          class="fixed top-0 left-0"
+          ref="audioRef"
+          :src="audioTips"
+          style="opacity: 0; z-index: -1"
+        ></audio>-->
 
     <!-- <van-pull-refresh v-model="refreshing" @refresh="onRefresh"> -->
     <van-sticky :offset-top="50">
       <div class="w-full text-xl font-semibold px-16 h-48 flex justify-start items-center bg-white">
         <span
-          @click="showPopover = true"
-          v-if="showPopover"
-          class="iconfont icon-plus text-[#FF9300]"
-          style="font-size: 24px"
+            @click="showPopover = true"
+            v-if="showPopover"
+            class="iconfont icon-plus text-[#FF9300]"
+            style="font-size: 24px"
         ></span>
         <span v-else class="iconfont icon-plus text-black" style="font-size: 24px"></span>
 
         <van-popover
-          v-model:show="showPopover"
-          placement="bottom"
-          theme="dark"
-          :offset="[5,20]"
-          :actions="actionsList"
-          @select="onSelect"
+            v-model:show="showPopover"
+            placement="bottom"
+            theme="dark"
+            :offset="[5,20]"
+            :actions="actionsList"
+            @select="onSelect"
         >
           <template #reference>
             <span :class="`${showPopover ? 'text-[#FF9300]' : 'text-black-3'}`">添加</span>
@@ -35,43 +35,43 @@
     <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
       <div style="height: calc(100vh - 100px)" class="w-full">
         <van-list
-          ref="messageBoxRef"
-          class="flex-1 overflow-y-auto flex flex-col"
-          :finished="true"
-          finished-text=""
+            ref="messageBoxRef"
+            class="flex-1 overflow-y-auto flex flex-col"
+            :finished="true"
+            finished-text=""
         >
           <div
-            @click="
+              @click="
               onChatPage('/profile/system-message', {
                 groupId: chatList[0]?.groupId
               })
             "
-            class="w-full relative h-82 flex justify-start items-center px-16"
+              class="w-full relative h-82 flex justify-start items-center px-16"
           >
             <van-badge
-              v-if="chatList[0]?.unreadMessageCount"
-              v-bind="messageNumber(chatList[0]?.unreadMessageCount)"
-              max="99"
+                v-if="chatList[0]?.unreadMessageCount"
+                v-bind="messageNumber(chatList[0]?.unreadMessageCount)"
+                max="99"
             >
               <div
-                class="w-48 h-48 bg-[#0052D9] rounded-full overflow-hidden flex justify-center items-center"
+                  class="w-48 h-48 bg-[#0052D9] rounded-full overflow-hidden flex justify-center items-center"
               >
                 <img
-                  class="w-24 h-24 shrink-0 object-cover"
-                  src="~/assets/img/chat/remind.svg"
-                  alt=""
+                    class="w-24 h-24 shrink-0 object-cover"
+                    src="~/assets/img/chat/remind.svg"
+                    alt=""
                 />
               </div>
             </van-badge>
 
             <div
-              v-else
-              class="w-48 h-48 bg-[#0052D9] rounded-full overflow-hidden flex justify-center items-center"
+                v-else
+                class="w-48 h-48 bg-[#0052D9] rounded-full overflow-hidden flex justify-center items-center"
             >
               <img
-                class="w-24 h-24 shrink-0 object-cover"
-                src="~/assets/img/chat/remind.svg"
-                alt=""
+                  class="w-24 h-24 shrink-0 object-cover"
+                  src="~/assets/img/chat/remind.svg"
+                  alt=""
               />
             </div>
 
@@ -82,8 +82,8 @@
               <p class="line-clamp-1 h-20 text-sm text-black-6 leading-3xl">
                 {{
                   chatList[0]?.lastMessage
-                    ? messageContentParse(chatList[0]?.lastMessage?.messageContent)
-                    : ''
+                      ? messageContentParse(chatList[0]?.lastMessage?.messageContent)
+                      : ''
                 }}
               </p>
             </div>
@@ -92,8 +92,8 @@
               <p class="text-black/[0.6] text-sm text-end">
                 {{
                   chatList[0]?.lastMessage
-                    ? createTimeSplit(chatList[0]?.lastMessage?.createTime)
-                    : ''
+                      ? createTimeSplit(chatList[0]?.lastMessage?.createTime)
+                      : ''
                 }}
               </p>
             </div>
@@ -101,39 +101,39 @@
           </div>
           <!-- navigateTo('/follow?listType=fans') -->
           <div
-            @click="
+              @click="
               onChatPage('/follow', {
                 listType: 'fans',
                 groupId: chatList[1]?.groupId
               })
             "
-            class="w-full relative h-82 flex justify-start items-center px-16"
+              class="w-full relative h-82 flex justify-start items-center px-16"
           >
             <van-badge
-              v-if="chatList[1]?.unreadMessageCount"
-              v-bind="messageNumber(chatList[1]?.unreadMessageCount)"
-              max="99"
+                v-if="chatList[1]?.unreadMessageCount"
+                v-bind="messageNumber(chatList[1]?.unreadMessageCount)"
+                max="99"
             >
               <div
-                class="w-48 h-48 bg-[#FF9300] rounded-full overflow-hidden flex justify-center items-center"
+                  class="w-48 h-48 bg-[#FF9300] rounded-full overflow-hidden flex justify-center items-center"
               >
                 <img
-                  class="w-24 h-24 shrink-0 object-cover"
-                  src="~/assets/img/chat/user.svg"
-                  alt=""
+                    class="w-24 h-24 shrink-0 object-cover"
+                    src="~/assets/img/chat/user.svg"
+                    alt=""
                 />
               </div>
             </van-badge>
 
             <div
-              v-else
-              @click="navigateTo('/follow?listType=fans')"
-              class="w-48 h-48 bg-[#FF9300] rounded-full overflow-hidden flex justify-center items-center"
+                v-else
+                @click="navigateTo('/follow?listType=fans')"
+                class="w-48 h-48 bg-[#FF9300] rounded-full overflow-hidden flex justify-center items-center"
             >
               <img
-                class="w-24 h-24 shrink-0 object-cover"
-                src="~/assets/img/chat/user.svg"
-                alt=""
+                  class="w-24 h-24 shrink-0 object-cover"
+                  src="~/assets/img/chat/user.svg"
+                  alt=""
               />
             </div>
 
@@ -144,8 +144,8 @@
               <p class="line-clamp-1 h-20 text-sm text-black-6 leading-3xl">
                 {{
                   chatList[1]?.lastMessage
-                    ? messageShowName(chatList[1]?.lastMessage?.messageContent)
-                    : ''
+                      ? messageShowName(chatList[1]?.lastMessage?.messageContent)
+                      : ''
                 }}
               </p>
             </div>
@@ -154,8 +154,8 @@
               <p class="text-black/[0.6] text-sm text-end">
                 {{
                   chatList[1]?.lastMessage
-                    ? createTimeSplit(chatList[1]?.lastMessage?.createTime)
-                    : ''
+                      ? createTimeSplit(chatList[1]?.lastMessage?.createTime)
+                      : ''
                 }}
               </p>
             </div>
@@ -163,37 +163,37 @@
           </div>
 
           <div
-            @click="
+              @click="
               onChatPage('/profile/interaction-message', {
                 groupId: chatList[2]?.groupId
               })
             "
-            class="w-full relative h-82 flex justify-start items-center px-16"
+              class="w-full relative h-82 flex justify-start items-center px-16"
           >
             <van-badge
-              v-if="chatList[2]?.unreadMessageCount > 0"
-              v-bind="messageNumber(chatList[2]?.unreadMessageCount)"
-              max="99"
+                v-if="chatList[2]?.unreadMessageCount > 0"
+                v-bind="messageNumber(chatList[2]?.unreadMessageCount)"
+                max="99"
             >
               <div
-                class="w-48 h-48 bg-[#FF476A] rounded-full overflow-hidden flex justify-center items-center"
+                  class="w-48 h-48 bg-[#FF476A] rounded-full overflow-hidden flex justify-center items-center"
               >
                 <img
-                  class="w-24 h-24 shrink-0 object-cover"
-                  src="~/assets/img/chat/weixin-shake.svg"
-                  alt=""
+                    class="w-24 h-24 shrink-0 object-cover"
+                    src="~/assets/img/chat/weixin-shake.svg"
+                    alt=""
                 />
               </div>
             </van-badge>
 
             <div
-              v-else
-              class="w-48 h-48 bg-[#FF476A] rounded-full overflow-hidden flex justify-center items-center"
+                v-else
+                class="w-48 h-48 bg-[#FF476A] rounded-full overflow-hidden flex justify-center items-center"
             >
               <img
-                class="w-24 h-24 shrink-0 object-cover"
-                src="~/assets/img/chat/weixin-shake.svg"
-                alt=""
+                  class="w-24 h-24 shrink-0 object-cover"
+                  src="~/assets/img/chat/weixin-shake.svg"
+                  alt=""
               />
             </div>
 
@@ -204,8 +204,8 @@
               <p class="line-clamp-1 h-20 text-sm text-black-6 leading-3xl">
                 {{
                   chatList[2]?.lastMessage
-                    ? messageContentParse(chatList[2]?.lastMessage?.messageContent)
-                    : ''
+                      ? messageContentParse(chatList[2]?.lastMessage?.messageContent)
+                      : ''
                 }}
               </p>
             </div>
@@ -214,8 +214,8 @@
               <p class="text-black/[0.6] text-sm text-end">
                 {{
                   chatList[2]?.lastMessage
-                    ? createTimeSplit(chatList[2]?.lastMessage?.createTime)
-                    : ''
+                      ? createTimeSplit(chatList[2]?.lastMessage?.createTime)
+                      : ''
                 }}
               </p>
             </div>
@@ -226,43 +226,36 @@
           <div v-if="isTopList?.length && activeNames" class="w-full">
             <template v-for="(item, index) in isTopList" :key="item?.id">
               <template v-if="index > 2">
-                <!-- 聊会话 -->
+                <!-- 聊会话 -->
                 <ProfileNewsGroupChat
-                  v-if="item?.noticeType == 2"
-                  :item-data="{
+                    v-if="item?.noticeType == 2"
+                    :item-data="{
                     ...item,
                     updateTime: item?.lastMessage
                       ? createTimeSplit(item?.lastMessage?.updateTime)
                       : ''
                   }"
-                  @on-chat-page="
+                    @on-chat-page="
                     onChatPage('/chat/group', { userId: user.userId, groupId: item?.groupId })
                   "
-                  @on-no-bother="noBother(item)"
-                  @on-is-top="onIsTop(item)"
-                  @on-conv-delete="onIsShow(item)"
+                    @on-no-bother="noBother(item)"
+                    @on-is-top="onIsTop(item)"
+                    @on-conv-delete="onIsShow(item)"
                 />
 
-                <!-- 聊会话 -->
+                <!-- 聊会话 -->
                 <ProfileNewsSingleChat
-                  v-if="item?.noticeType == 1"
-                  :item-data="{
+                    v-if="item?.noticeType == 1"
+                    :item-data="{
                     ...item,
                     updateTime: item?.lastMessage
                       ? createTimeSplit(item?.lastMessage?.updateTime)
                       : ''
                   }"
-                  @on-chat-page="
-                    onChatPage('/chat/single', {
-                      sendUserId: userInfo.userId,
-                      groupId: item?.groupId,
-                      getUserId: item?.toUserId,
-                      groupRemark: item?.groupRemark
-                    })
-                  "
-                  @on-no-bother="noBother(item)"
-                  @on-is-top="onIsTop(item)"
-                  @on-conv-delete="onIsShow(item)"
+                    @on-chat-page="goDetails('single', item)"
+                    @on-no-bother="noBother(item)"
+                    @on-is-top="onIsTop(item)"
+                    @on-conv-delete="onIsShow(item)"
                 />
               </template>
               <template v-else></template>
@@ -270,58 +263,47 @@
           </div>
 
           <div
-            v-if="isTopList.length >= 6"
-            @click="activeNames = !activeNames"
-            class="flex justify-between items-center h-20 -mt-20 w-full p-16 box-border"
+              v-if="isTopList.length >= 6"
+              @click="activeNames = !activeNames"
+              class="flex justify-between items-center h-20 -mt-20 w-full p-16 box-border"
           >
             <div class="shrink-0 flex items-center">
-              <van-icon name="bars" size="16" class="mr-5" />
+              <van-icon name="bars" size="16" class="mr-5"/>
               <span class="text-sm">{{ collapseTitle }}</span>
             </div>
             <div class="w-16 h-16 shrink-0">
-              <van-icon name="arrow" size="16" />
+              <van-icon name="arrow" size="16"/>
             </div>
           </div>
 
           <!-- 不置顶的会话列表 -->
           <template v-for="(item, index) in pinnedList" :key="item?.id">
             <ProfileNewsGroupChat
-              v-if="item?.noticeType == 2"
-              :item-data="{
+                v-if="item?.noticeType == 2"
+                :item-data="{
                 ...item,
                 updateTime: item?.lastMessage ? createTimeSplit(item?.lastMessage?.updateTime) : ''
               }"
-              @on-chat-page="
+                @on-chat-page="
                 onChatPage('/chat/group', {
                   userId: userInfo.userId,
                   groupId: item?.groupId
                 })
               "
-              @on-no-bother="noBother(item)"
-              @on-is-top="onIsTop(item)"
-              @on-conv-delete="onIsShow(item)"
+                @on-no-bother="noBother(item)"
+                @on-is-top="onIsTop(item)"
+                @on-conv-delete="onIsShow(item)"
             />
             <ProfileNewsSingleChat
-              v-if="item?.noticeType == 1"
-              :item-data="{
+                v-if="item?.noticeType == 1"
+                :item-data="{
                 ...item,
                 updateTime: item?.lastMessage ? createTimeSplit(item?.lastMessage?.updateTime) : ''
               }"
-              @on-chat-page="
-                onChatPage(
-                  '/chat/single',
-                  {
-                    sendUserId: userInfo.userId,
-                    groupId: item?.groupId,
-                    getUserId: item?.toUserId,
-                    groupRemark: item?.groupRemark
-                  },
-                  item
-                )
-              "
-              @on-no-bother="noBother(item)"
-              @on-is-top="onIsTop(item)"
-              @on-conv-delete="onIsShow(item)"
+                @on-chat-page="goDetails('single', item)"
+                @on-no-bother="noBother(item)"
+                @on-is-top="onIsTop(item)"
+                @on-conv-delete="onIsShow(item)"
             />
           </template>
         </van-list>
@@ -335,20 +317,20 @@ import comments from '~/assets/img/chat/comments-white.svg'
 import plaza from '~/assets/img/chat/guangchang.svg'
 import userAdd from '~/assets/img/chat/user-add.svg'
 import audioTips from '@/assets/audio/message.mp3'
-import { messageContentParse } from '~/utils/detalTime.js'
+import {messageContentParse} from '~/utils/detalTime.js'
 import {XYWebSocket} from '~/utils/XYWebSocket.ts'
 
 const actionsList = [
-  { text: '创建群聊', icon: comments },
-  { text: '群聊广场', icon: plaza },
-  { text: '加入群聊', icon: plaza },
-  { text: '添加用户', icon: userAdd }
+  {text: '创建群聊', icon: comments},
+  {text: '群聊广场', icon: plaza},
+  {text: '加入群聊', icon: plaza},
+  {text: '添加用户', icon: userAdd}
 ]
 const userInfoStore = useUserInfoStore()
-const { userInfo } = storeToRefs(userInfoStore)
+const {userInfo} = storeToRefs(userInfoStore)
 
 const chatsStore = useChatsStore();
-const { chatList, chatListLoading } = storeToRefs(chatsStore)
+const {chatList, chatListLoading} = storeToRefs(chatsStore)
 
 const showPopover = ref(false)
 
@@ -389,30 +371,31 @@ const onRefresh = () => {
 
 // 打扰和免打扰得
 const noBother = (parmas) => {
-  handleBoolean({ groupId: parmas.groupId, isNotDisturb: parmas.isNotDisturb })
+  handleBoolean({groupId: parmas.groupId, isNotDisturb: parmas.isNotDisturb})
 }
 
 // 是否置顶
 const onIsTop = (parmas) => {
-  handleBoolean({ groupId: parmas.groupId, isTop: parmas.isTop })
+  handleBoolean({groupId: parmas.groupId, isTop: parmas.isTop})
 }
 
 // 是否显示会话
 const onIsShow = (parmas) => {
-  handleBoolean({ groupId: parmas.groupId, isShow: parmas.isShow })
+  handleBoolean({groupId: parmas.groupId, isShow: parmas.isShow})
 }
 
 // 是否免打扰和 是否置顶 公共
 const handleBoolean = async (body) => {
   try {
-    let { data } = await request('/website/tourMember/updateSingleTourMember', {
+    let {data} = await request('/website/tourMember/updateSingleTourMember', {
       method: 'post',
       body
     })
     if (data) {
       chatsStore.getChatList()
     }
-  } catch (error) {}
+  } catch (error) {
+  }
 }
 
 // 消息数量通知的展示  需要动态的展示
@@ -447,21 +430,17 @@ const messageNumber = (content) => {
 
 // 跳转聊天页面
 const onChatPage = async (path, query, itemParams) => {
-  console.log(itemParams, '6666')
-
+  navigateTo({
+    path,
+    query
+  })
   const res = await request('/website/tourMessage/updateRead', {
     query: {
       groupId: query.groupId
     }
   })
-
-  if (res && res?.success) {
-    chatsStore.getChatList()
-    navigateTo({
-      path,
-      query
-    })
-  }
+  await handleResponse(res, false)
+  await chatsStore.getChatList()
 }
 
 // 选中的是那个页面
@@ -472,6 +451,23 @@ const onSelect = (action) => {
   if (action.text === '添加用户') onChatPage('/chat/user-add', {})
 }
 
+const goDetails = (type, item) => {
+  console.log(type, item, 'itemitem')
+  switch (type) {
+    case 'single': // 单聊消息
+      navigateTo({
+        path: '/chat/single', query: {
+          getUserId: item?.toUserId,
+          groupRemark: item?.groupRemark
+        }
+      })
+      break;
+    default:
+
+      break;
+  }
+}
+
 // 消息的内容转换
 function messageShowName(messageContent) {
   try {

+ 50 - 9
src/stores/useChats.js

@@ -3,23 +3,59 @@ import {XYWebSocket} from "~/utils/XYWebSocket";
 export const useChatsStore = defineStore('chats', () => {
   let socket = null;
   const initWebSocket = (url) => {
-    if (!socket) socket = new XYWebSocket.WebSocketClass(url);
+    if (!socket) {
+      socket = new XYWebSocket.WebSocketClass(url);
+      console.warn(socket, 'socket')
+    }
+  }
+  const sendSocketMessage = async (message) => {
+    return socket.sendMessage(message)
+  }
+
+  // 当前聊天会话管理
+  /**
+   *
+   * @param type 聊天类型 单聊或者群聊
+   * @param userId 聊天对象Id
+   * @returns {Promise<void>}
+   */
+  const currConversationLoading = ref(false)
+  const getCurrConversationId = async (userId) => {
+    try {
+      return await request('/website/tourGroup/createMember', {
+        method: 'post', body: {
+          getUserId: userId,
+          groupId: createGroupId()
+        }
+      })
+    } catch (e) {
+
+    } finally {
+      currConversationLoading.value = false
+
+    }
   }
 
-  // 当前会话管理
-  const currConversation = ref(null);
-  const setCurrConversation = (conversation) => {
-    currConversation.value = conversation
+  const getChatHistory = async (query) => {
+    try {
+      return await request('/website/tourMessage/getMessageByGroupIdPage', {query})
+    } catch (e) {
+
+    } finally {
+
+    }
   }
 
+
   // 会话列表
   let chatList = ref([]);
   let chatListLoading = ref(false);
   const getChatList = async () => {
     try {
-      const res= await request('/website/tourism/fans/getTourMemberList');
+      if (chatListLoading.value) return
+      const res = await request('/website/tourism/fans/getTourMemberList');
       await handleResponse(res)
-      const { list } = res.data;
+      const {list} = res.data;
       chatList.value = list;
     } catch (e) {
 
@@ -36,6 +72,9 @@ export const useChatsStore = defineStore('chats', () => {
     socketStatus.value = status
   })
 
+
+  const createGroupId = () => Date.now() + '' + Math.floor(Math.random() * 100000)
+
   const MESSAGE_TYPE = {
     'text': 0,
     'image': 1,
@@ -48,13 +87,15 @@ export const useChatsStore = defineStore('chats', () => {
   return {
     // 注册socket
     initWebSocket,
+    sendSocketMessage,
+
     // socket状态
     socketStatus,
     socketStatusText,
 
     // 当前会话
-    currConversation,
-    setCurrConversation,
+    getCurrConversationId,
+    getChatHistory,
 
     // 会话列表
     chatList,

+ 7 - 7
src/utils/XYWebSocket.ts

@@ -46,7 +46,7 @@ export namespace XYWebSocket {
                 if (!e.data) return;
                 const messagePackage = JSON.parse(e.data) || {};
                 console.log('---------接收---------', messagePackage, '-----------消息包------');
-                const {web_request_id} = messagePackage;
+                const {web_request_id = null} = messagePackage.map || {};
 
                 /**
                  * 1、回复客户端消息
@@ -90,7 +90,7 @@ export namespace XYWebSocket {
             this.socket.removeEventListener('close', this.websocketOnclose.bind(this));
         }
 
-        public sendMessage(path: string, data?: any): Promise<any> { // string | ArrayBuffer | Blob | ArrayBufferView
+        public async sendMessage(data?: any): Promise<any> { // string | ArrayBuffer | Blob | ArrayBufferView
             const requestId = uuid();
 
             let timer: any = 0;
@@ -115,12 +115,13 @@ export namespace XYWebSocket {
                 this.eventPoll.set(requestId, eventItemProxy);
 
                 const request = {
-                    web_request_id: requestId,
-                    ...data
+                    ...data,
+                    map: {
+                        web_request_id: requestId,
+                    }
                 };
                 console.warn('---------发送---------', request, '-----------消息包------');
-                console.warn('---------发送---------', JSON.stringify(request), '-----------消息包------');
-                this.socket.send(JSON.stringify(request) + 'AD8C0A5F-3CF1-BEE2-3FE1-84209A3E9BD2');
+                this.socket.send(JSON.stringify(request));
 
                 // 判断超时
                 let loop = 0;
@@ -143,7 +144,6 @@ export namespace XYWebSocket {
                     this.eventPoll.delete(requestId);
                 });
         }
-
     }
 
     export enum SocketStatusType {