Browse Source

1、太乙堂聊天窗口为展示问题处理

yys 14 giờ trước cách đây
mục cha
commit
a23744d27f

+ 20 - 4
src/components/conversation/current-conversation.vue

@@ -200,13 +200,13 @@ export default {
   },
   watch: {
     currentUnreadCount(next) {
-      if (!this.hidden && next > 0) {
-        this.OpenIM.markConversationMessageAsRead(this.currentConversation.conversationID)
+      if (document.hasFocus() && next > 0 && this.currentConversation.conversationID) {
+        this.markCurrentConversationAsRead()
       }
     },
     hidden(next) {
-      if (!next && this.currentUnreadCount > 0) {
-        this.OpenIM.markConversationMessageAsRead(this.currentConversation.conversationID )
+      if (!next && this.currentUnreadCount > 0 && this.currentConversation.conversationID) {
+        this.markCurrentConversationAsRead()
       }
     }
   },
@@ -214,6 +214,22 @@ export default {
     this.OpenIM = getOpenIM();
   },
   methods: {
+    markCurrentConversationAsRead() {
+      const conversationID = this.currentConversation.conversationID
+      if (!conversationID) {
+        return
+      }
+      this.OpenIM.markConversationMessageAsRead(conversationID)
+        .then(() => this.OpenIM.getAllConversationList())
+        .then(({ data }) => {
+          this.$store.commit('updateConversationList', data)
+        })
+        .catch(({ errCode }) => {
+          if (errCode !== 10303) {
+            console.error('标记已读失败')
+          }
+        })
+    },
     move(e) {
       let odiv = this.$refs.dropdown.$el.children[0]//e.target        //获取目标元素
       //算出鼠标相对元素的位置

+ 55 - 50
src/store/modules/conversation.js

@@ -1,6 +1,5 @@
-import store from '..'
 import { titleNotify } from '../../utils'
-import { filterCallingMessage } from '../../utils/common'
+import { filterCallingMessage, isMessageInConversation } from '../../utils/common'
 import { getOpenIM } from '@/utils/openIM';
 import da from "element-ui/src/locale/lang/da";
 
@@ -43,12 +42,15 @@ const conversationModules = {
       return state.currentConversation.conversationType
     },
     totalUnreadCount: state => {
+      const currentConversationID = state.currentConversation.conversationID
+      const isWindowFocused = typeof document.hasFocus === 'function' ? document.hasFocus() : !document.hidden
       const result = state.conversationList.reduce((count, conversation) => {
-        // 当前会话不计算总未读
-        if (!store.getters.hidden && state.currentConversation.conversationID === conversation.conversationID) {
+        const unreadCount = conversation.unreadCount || 0
+        // 窗口聚焦且正在查看的会话不计入未读(该会话会在收到消息时自动标记已读)
+        if (isWindowFocused && currentConversationID && currentConversationID === conversation.conversationID) {
           return count
         }
-        return count + conversation.unreadCount
+        return count + unreadCount
       }, 0)
       titleNotify(result)
       return result
@@ -140,6 +142,26 @@ const conversationModules = {
       state.nextReqMessageID = ''
       state.isCompleted = false
     },
+    patchCurrentConversation(state, conversation) {
+      if (state.currentConversation.conversationID === conversation.conversationID) {
+        state.currentConversation = { ...state.currentConversation, ...conversation }
+      }
+    },
+    mergeConversationList(state, changedConversations) {
+      if (!Array.isArray(changedConversations) || changedConversations.length === 0) {
+        return
+      }
+      const list = [...state.conversationList]
+      changedConversations.forEach(changed => {
+        const index = list.findIndex(item => item.conversationID === changed.conversationID)
+        if (index >= 0) {
+          list[index] = changed
+        } else {
+          list.unshift(changed)
+        }
+      })
+      state.conversationList = list
+    },
     /**
      * 更新会话列表
      * 调用时机:触发会话列表更新事件时。C
@@ -218,58 +240,41 @@ const conversationModules = {
      * @returns
      */
     pushCurrentMessageList(state, data) {
-      // 还没当前会话,则跳过
-      console.log("触发消息列表更新",state.currentConversation)
       if (!state.currentConversation.conversationID) {
         return
       }
-      console.log("会话详细信息",state.currentConversation)
-      console.log("消息详细信息",data)
-      if (Array.isArray(data)) {
-        // 筛选出当前会话的消息
-        const result = data.filter(item => item.recvID===JSON.parse(state.currentConversation.latestMsg).recvID&& item.sendID === JSON.parse(state.currentConversation.latestMsg).sendID)
-        console.log("收到消息1")
-        console.log("state.currentConversation.conversationID会话id",state.currentConversation.conversationID)
-        console.log("result[0]",result[0])
-        if(result[0].ex!=null&&result[0].ex!=""){
-          try{
-            var json=JSON.parse(result[0].ex);
-            console.log("消息json",json)
-            if(json.type!=null&&json.type!=""){
-              state.type=json.type;
-              state.orderId=json.orderId;
-              state.imType=json.imType;
-              state.followId=json.followId;
-              state.orderType=json.orderType;
-            }
-          }
-          catch(e){
-          }
+      const appendMessages = (messages) => {
+        if (!messages.length) {
+          return
         }
-        state.currentMessageList = [...state.currentMessageList, ...result]
-        filterCallingMessage(state.currentMessageList)
-      //} else if ("si_"+data.sendID+"_"+data.recvID === state.currentConversation.conversationID) {
-      } else if (data.recvID===JSON.parse(state.currentConversation.latestMsg).recvID&& data.sendID === JSON.parse(state.currentConversation.latestMsg).sendID) {
-        console.log("会话id22222",state.currentConversation.conversationID)
-        state.currentMessageList = [...state.currentMessageList, data]
-        console.log("收到消息2")
-        console.log(data)
-        if(data.ex!=null&&data.ex!=""){
-          var json=JSON.parse(data.ex);
-          console.log(json)
-          try{
-            if(json.type!=null&&json.type!=""){
-              state.type=json.type;
-              state.orderId=json.orderId;
-              state.imType=json.imType;
-              state.followId=json.followId;
-              state.orderType=json.orderType;
+        const firstMessage = messages[0]
+        if (firstMessage.ex) {
+          try {
+            const json = JSON.parse(firstMessage.ex)
+            if (json.type) {
+              state.type = json.type
+              state.orderId = json.orderId
+              state.imType = json.imType
+              state.followId = json.followId
+              state.orderType = json.orderType
             }
+          } catch (e) {
+            // ignore invalid ex
           }
-          catch(e){
-          }
         }
-        filterCallingMessage(state.currentMessageList)
+        const existingIds = new Set(state.currentMessageList.map(item => item.clientMsgID))
+        const newMessages = messages.filter(item => !existingIds.has(item.clientMsgID))
+        if (newMessages.length) {
+          state.currentMessageList = [...state.currentMessageList, ...newMessages]
+          filterCallingMessage(state.currentMessageList)
+        }
+      }
+
+      if (Array.isArray(data)) {
+        const result = data.filter(item => isMessageInConversation(item, state.currentConversation))
+        appendMessages(result)
+      } else if (isMessageInConversation(data, state.currentConversation)) {
+        appendMessages([data])
       }
     },
     /**

+ 14 - 0
src/utils/common.js

@@ -4,6 +4,20 @@
  */
 //import TIM from 'tim-js-sdk/tim-js-friendship'
 
+/**
+ * 判断消息是否属于指定会话(按 conversationID 匹配,避免 latestMsg 方向导致漏消息)
+ */
+export function isMessageInConversation(message, conversation) {
+  if (!message || !conversation || !conversation.conversationID) {
+    return false
+  }
+  if (message.conversationID) {
+    return message.conversationID === conversation.conversationID
+  }
+  const { conversationID } = conversation
+  const { sendID, recvID } = message
+  return sendID && recvID && conversationID.includes(sendID) && conversationID.includes(recvID)
+}
 
 export function translateGroupSystemNotice(message) {
 	const groupName = message.payload.groupProfile.name || message.payload.groupProfile.groupID

+ 6 - 0
src/utils/index.js

@@ -408,7 +408,13 @@ export function throttle(func, wait) {
  * @export
  * @param {Number} count
  */
+let lastTitleNotifyCount = -1
+
 export function titleNotify(count) {
+  if (count === lastTitleNotifyCount) {
+    return
+  }
+  lastTitleNotifyCount = count
   const hasNewMessage = count > 0
   if (hasNewMessage) {
     if (document.title.search(/\((.*?)\)/) >= 0) {

+ 42 - 37
src/views/im/index.vue

@@ -46,7 +46,8 @@ import { translateGroupSystemNotice } from '@/utils/common'
 import GroupLive from '@/components/group-live/index'
 import Calling from '@/components/message/trtc-calling/calling-index'
 import { ACTION } from '@/utils/trtcCustomMessageMap'
-import { getOpenIM,getCbEvents } from '@/utils/openIM';
+import { getOpenIM, getCbEvents } from '@/utils/openIM';
+import { isMessageInConversation } from '@/utils/common';
 import { accountCheck } from '@/api/doctor';
 export default {
   title: 'TIMSDK DEMO',
@@ -255,34 +256,23 @@ export default {
 
         }
       });
-      /*this.OpenIM.on(getCbEvents().OnConversationChanged, (eventData) => {
-        console.log("触发OnConversationChanged事件", eventData);
-
-        try {
-          // 1. 确保数据结构正确
-          if (!eventData || !eventData.data) {
-            console.warn("无效的会话更新数据", eventData);
-            return;
-          }
-
-          // 2. 提取更新后的会话列表
-          const updatedConversations = eventData.data;
-
-          // 3. 打印调试信息
-          console.log("更新的会话列表:", updatedConversations);
-
-          // 4. 更新到Vuex store
-          this.$store.commit('updateConversationList', updatedConversations);
-
-          // 5. 可选:检查特定会话的更新
-          updatedConversations.forEach(conv => {
-            console.log(`会话ID: ${conv.conversationID} 已更新`, conv);
-          });
-
-        } catch (error) {
-          console.error("处理会话更新时出错:", error);
+      this.OpenIM.on(getCbEvents().OnConversationChanged, (eventData) => {
+        if (!eventData || !eventData.data) {
+          return
         }
-      });*/
+        this.$store.commit('mergeConversationList', eventData.data)
+        const currentConversationID = this.$store.state.conversation.currentConversation.conversationID
+        const updatedCurrent = eventData.data.find(item => item.conversationID === currentConversationID)
+        if (updatedCurrent) {
+          this.$store.commit('patchCurrentConversation', updatedCurrent)
+        }
+      });
+      this.OpenIM.on(getCbEvents().OnNewConversation, (eventData) => {
+        if (!eventData || !eventData.data) {
+          return
+        }
+        this.$store.commit('mergeConversationList', eventData.data)
+      });
       // SDK NOT READT
       /*this.OpenIM.on(this.OpenIM.EVENT.SDK_NOT_READY, this.onReadyStateUpdate, this)
       // 被踢出
@@ -319,7 +309,10 @@ export default {
     },
 
     onReceiveMessage({ data: messageList }) {
-      // let totalUnreadCount = this.tim.getTotalUnreadMessageCount();
+      const currentConversation = this.$store.state.conversation.currentConversation
+      const hasCurrentConversationMessage = messageList.some(message =>
+        isMessageInConversation(message, currentConversation)
+      )
 
       messageList.forEach(element => {
         //过滤掉正在输入状态
@@ -332,20 +325,32 @@ export default {
         }
 
       });
-      this.OpenIM.getAllConversationList()
-        .then(({ data }) => {
-          // 调用成功
-          this.$store.commit('updateConversationList', data)
-        })
-        .catch(({ errCode, errMsg }) => {
-          // 调用失败
-        })
+      this.refreshConversationList()
       console.log(messageList)
       //this.handleVideoMessage(messageList)
       this.handleQuitGroupTip(messageList)
       this.handleCloseGroupLive(messageList)
       this.$store.commit('pushCurrentMessageList', messageList)
       this.$store.commit('pushAvChatRoomMessageList', messageList)
+
+      if (hasCurrentConversationMessage && currentConversation.conversationID && document.hasFocus()) {
+        this.OpenIM.markConversationMessageAsRead(currentConversation.conversationID)
+          .then(() => this.refreshConversationList())
+          .catch(({ errCode }) => {
+            if (errCode !== 10303) {
+              console.error('标记已读失败')
+            }
+          })
+      }
+    },
+    refreshConversationList() {
+      this.OpenIM.getAllConversationList()
+        .then(({ data }) => {
+          this.$store.commit('updateConversationList', data)
+        })
+        .catch(({ errCode, errMsg }) => {
+          console.error('刷新会话列表失败', errCode, errMsg)
+        })
     },
 
     onError({ data }) {