index.vue 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877
  1. <template>
  2. <view class="message-page">
  3. <!-- 顶部标题栏 -->
  4. <view class="header">
  5. <text class="header-title">💬 消息</text>
  6. <view class="header-actions">
  7. <text class="action-icon" @click="showSearchPanel = true">🔍</text>
  8. </view>
  9. </view>
  10. <!-- 搜索面板 -->
  11. <view v-if="showSearchPanel" class="search-panel">
  12. <view class="search-bar">
  13. <input
  14. class="search-input"
  15. v-model="searchKeyword"
  16. placeholder="搜索好友或消息内容"
  17. @input="onSearch" />
  18. <text class="search-cancel" @click="cancelSearch">取消</text>
  19. </view>
  20. </view>
  21. <!-- 会话列表 -->
  22. <scroll-view
  23. class="conversation-list"
  24. scroll-y
  25. refresher-enabled
  26. :refresher-triggered="refreshing"
  27. @refresherrefresh="onRefresh"
  28. @scrolltolower="loadMore">
  29. <!-- 骨架屏加载状态 -->
  30. <view v-if="loading && conversations.length === 0" class="skeleton-container">
  31. <view v-for="i in 6" :key="i" class="skeleton-item">
  32. <view class="skeleton-avatar"></view>
  33. <view class="skeleton-content">
  34. <view class="skeleton-line skeleton-line-title"></view>
  35. <view class="skeleton-line skeleton-line-text"></view>
  36. </view>
  37. </view>
  38. </view>
  39. <!-- 空状态(初次/无搜索) -->
  40. <view v-if="conversations.length === 0 && !loading && !searchKeyword" class="empty-container">
  41. <view class="empty-icon-wrapper">
  42. <text class="empty-icon">💬</text>
  43. </view>
  44. <text class="empty-text">暂无消息</text>
  45. <text class="empty-hint">开始和心仪的TA聊天吧~</text>
  46. <view class="empty-action">
  47. <button class="empty-btn" @click="switchTab('recommend')">去推荐页面</button>
  48. </view>
  49. </view>
  50. <!-- 系统消息作为第一条会话项展示(整合到同列表,突出样式) -->
  51. <view v-else-if="!searchKeyword" class="conversation-item-wrapper system-highlight" @click="openSystemMessages">
  52. <view class="conversation-item">
  53. <view class="avatar-wrapper">
  54. <text class="system-icon">📢</text>
  55. <view v-if="systemUnread > 0" class="unread-badge">{{ systemUnread > 99 ? '99+' : systemUnread }}</view>
  56. </view>
  57. <view class="conversation-content">
  58. <view class="content-top">
  59. <text class="user-name system-title">系统通知</text>
  60. <text class="last-time">{{ systemLatestTime ? formatTime(systemLatestTime) : '' }}</text>
  61. </view>
  62. <view class="content-bottom">
  63. <text class="last-message system-preview">{{ systemLatestPreview || '平台公告及处理通知' }}</text>
  64. <text class="system-tag"></text>
  65. </view>
  66. </view>
  67. </view>
  68. </view>
  69. <!-- 搜索无结果 -->
  70. <view v-else-if="searchKeyword && filteredConversations.length === 0" class="empty-container">
  71. <view class="empty-icon-wrapper">
  72. <text class="empty-icon">🔍</text>
  73. </view>
  74. <text class="empty-text">没有找到相关内容</text>
  75. <text class="empty-hint">试试搜索其他关键词</text>
  76. </view>
  77. <!-- 会话列表项(带滑动) -->
  78. <view
  79. v-for="conv in filteredConversations"
  80. :key="conv.id"
  81. class="conversation-item-wrapper">
  82. <movable-area class="movable-area">
  83. <movable-view
  84. class="movable-view"
  85. direction="horizontal"
  86. :x="conv.id === swipingConvId ? -150 : 0"
  87. @change="handleSwipe($event, conv)"
  88. @touchend="handleSwipeEnd(conv)">
  89. <view class="conversation-item" @click="openChat(conv)" @longpress="showActionMenu(conv)">
  90. <!-- 置顶标记 -->
  91. <view v-if="conv.isPinned" class="pinned-badge">📌</view>
  92. <!-- 头像 -->
  93. <view class="avatar-wrapper">
  94. <image
  95. class="avatar"
  96. :src="conv.targetUserAvatar || 'http://115.190.125.125:9001/static-images/default-avatar.svg'"
  97. mode="aspectFill"
  98. lazy-load />
  99. <view v-if="conv.isOnline" class="online-badge"></view>
  100. <view v-if="conv.unreadCount > 0" class="unread-badge">
  101. {{ conv.unreadCount > 99 ? '99+' : conv.unreadCount }}
  102. </view>
  103. </view>
  104. <!-- 会话内容 -->
  105. <view class="conversation-content">
  106. <view class="content-top">
  107. <view class="user-info">
  108. <text class="user-name">{{ conv.targetUserName }}</text>
  109. <text v-if="conv.isMatchmaker" class="matchmaker-tag">红娘</text>
  110. </view>
  111. <text class="last-time">{{formatTime(conv.lastMessageTime) }}</text>
  112. </view>
  113. <view class="content-bottom">
  114. <text class="last-message" :class="{ unread: conv.unreadCount > 0 }">
  115. {{ formatLastMessage(conv) }}
  116. </text>
  117. <text v-if="conv.lastMessageType === 1" class="message-type-icon">📝</text>
  118. <text v-else-if="conv.lastMessageType === 2" class="message-type-icon">🖼️</text>
  119. <text v-else-if="conv.lastMessageType === 3" class="message-type-icon">🎤</text>
  120. <text v-else-if="conv.lastMessageType === 4" class="message-type-icon">📹</text>
  121. </view>
  122. </view>
  123. </view>
  124. </movable-view>
  125. <!-- 右滑操作按钮 -->
  126. <view class="conversation-actions">
  127. <view class="action-btn pin-btn" @click.stop="togglePin(conv)">
  128. {{ conv.isPinned ? '取消' : '置顶' }}
  129. </view>
  130. <view class="action-btn delete-btn" @click.stop="confirmDeleteConversation(conv)">
  131. 删除
  132. </view>
  133. </view>
  134. </movable-area>
  135. </view>
  136. <!-- 加载更多 -->
  137. <view v-if="hasMore && conversations.length > 0" class="load-more">
  138. <text class="load-more-text">{{ loading ? '加载中...' : '上拉加载更多' }}</text>
  139. </view>
  140. <view v-else-if="!hasMore && conversations.length > 0" class="load-more">
  141. <text class="load-more-text">没有更多了</text>
  142. </view>
  143. </scroll-view>
  144. <!-- 底部导航栏 -->
  145. <view class="tabbar">
  146. <view class="tabbar-item" @click="switchTab('index')">
  147. <text class="tabbar-icon">🏠</text>
  148. <text class="tabbar-text">首页</text>
  149. </view>
  150. <view class="tabbar-item" @click="switchTab('plaza')">
  151. <text class="tabbar-icon">💕</text>
  152. <text class="tabbar-text">动态</text>
  153. </view>
  154. <view class="tabbar-item" @click="switchTab('recommend')">
  155. <text class="tabbar-icon">👍</text>
  156. <text class="tabbar-text">推荐</text>
  157. </view>
  158. <!-- <view class="tabbar-item active">
  159. <text class="tabbar-icon">💬</text>
  160. <text class="tabbar-text">消息</text>
  161. <view v-if="totalUnread > 0" class="tab-badge">
  162. {{ totalUnread > 99 ? '99+' : totalUnread }}
  163. </view>
  164. </view> -->
  165. <view class="tabbar-item" @click="switchTab('mine')">
  166. <text class="tabbar-icon">👤</text>
  167. <text class="tabbar-text">我的</text>
  168. </view>
  169. </view>
  170. <!-- 操作菜单 -->
  171. <uni-popup ref="actionMenu" type="bottom">
  172. <view class="action-menu">
  173. <view class="menu-item" @click="markAsRead">标为已读</view>
  174. <view class="menu-item" @click="deleteCurrentConversation">删除会话</view>
  175. <view class="menu-item cancel" @click="closeActionMenu">取消</view>
  176. </view>
  177. </uni-popup>
  178. </view>
  179. </template>
  180. <script>
  181. import { getConversations, getUnreadCount, deleteConversation, checkOnlineStatus } from '@/utils/chat-api.js';
  182. import wsManager from '@/utils/websocket.js';
  183. import timManager from '@/utils/tim-manager.js';
  184. import TIM from 'tim-wx-sdk';
  185. export default {
  186. data() {
  187. return {
  188. blacklistUsers: [], // 拉黑用户ID列表
  189. blacklistLoaded: false, // 拉黑列表是否加载完成
  190. userId: null,
  191. conversations: [],
  192. loading: false,
  193. refreshing: false,
  194. hasMore: false, // TIM 一次性返回所有会话,不分页
  195. currentPage: 1,
  196. pageSize: 20,
  197. totalUnread: 0,
  198. showSearchPanel: false,
  199. searchKeyword: '',
  200. selectedConversation: null,
  201. onlineCheckTimer: null,
  202. timInitialized: false,
  203. // 滑动相关
  204. swipingConvId: null,
  205. // 置顶会话列表(本地存储)
  206. pinnedConversations: []
  207. , systemUnread: 0
  208. , systemLatestTime: null
  209. , systemLatestPreview: ''
  210. };
  211. },
  212. computed: {
  213. // 过滤和排序会话列表
  214. filteredConversations() {
  215. let list = [...this.conversations];
  216. // 搜索过滤
  217. if (this.searchKeyword) {
  218. list = list.filter(conv => {
  219. return conv.targetUserName.includes(this.searchKeyword) ||
  220. conv.lastMessage.includes(this.searchKeyword);
  221. });
  222. }
  223. // 按置顶和时间排序
  224. list.sort((a, b) => {
  225. // 置顶优先
  226. if (a.isPinned && !b.isPinned) return -1;
  227. if (!a.isPinned && b.isPinned) return 1;
  228. // 时间倒序
  229. return new Date(b.lastMessageTime) - new Date(a.lastMessageTime);
  230. });
  231. return list;
  232. }
  233. },
  234. onLoad() {
  235. // 获取登录凭证
  236. const token = uni.getStorageSync('token');
  237. const userInfo = uni.getStorageSync('userInfo');
  238. const storedUserId = uni.getStorageSync('userId');
  239. console.log('=== 消息页面登录状态检查 ===');
  240. console.log('token:', token ? '存在' : '不存在');
  241. console.log('userInfo:', userInfo);
  242. console.log('storedUserId:', storedUserId);
  243. // 严格验证登录状态
  244. if (!token || !userInfo) {
  245. console.error('❌ 未登录或登录信息不完整');
  246. uni.showModal({
  247. title: '需要登录',
  248. content: '请先登录后再查看消息',
  249. showCancel: false,
  250. success: () => {
  251. uni.reLaunch({
  252. url: '/pages/page3/page3'
  253. });
  254. }
  255. });
  256. return;
  257. }
  258. // 优先使用 storage 中的 userId,确保一致性
  259. this.userId = storedUserId || userInfo.userId || userInfo.id || userInfo.user_id;
  260. // 转换为数字类型(如果是字符串)
  261. if (typeof this.userId === 'string') {
  262. this.userId = parseInt(this.userId);
  263. }
  264. // 最终验证 userId
  265. if (!this.userId || isNaN(this.userId)) {
  266. console.error('❌ 无法获取有效的用户ID');
  267. console.error('userInfo:', JSON.stringify(userInfo));
  268. console.error('storedUserId:', storedUserId);
  269. uni.showModal({
  270. title: '用户信息错误',
  271. content: '无法获取用户ID,请重新登录',
  272. showCancel: false,
  273. success: () => {
  274. // 清除错误的登录信息
  275. uni.removeStorageSync('token');
  276. uni.removeStorageSync('userInfo');
  277. uni.removeStorageSync('userId');
  278. uni.reLaunch({
  279. url: '/pages/page3/page3'
  280. });
  281. }
  282. });
  283. return;
  284. }
  285. console.log('✅ 当前登录用户ID:', this.userId, '(类型:', typeof this.userId, ')');
  286. // 确保 userId 同步到 storage(以防不一致)
  287. if (storedUserId !== this.userId) {
  288. console.log('⚠️ 同步 userId 到 storage');
  289. uni.setStorageSync('userId', this.userId);
  290. }
  291. // 加载置顶会话列表(基于当前用户ID)
  292. this.loadPinnedConversations();
  293. // 初始化腾讯云IM(确保使用正确的用户ID登录)
  294. this.initTIM();
  295. // 拉取系统消息未读
  296. this.loadSystemUnread();
  297. // 监听刷新事件(从聊天页面返回时触发)
  298. uni.$on('refreshConversations', this.refreshConversations);
  299. uni.$on('blacklistUpdated', this.handleBlacklistUpdate);
  300. // 初始化在线状态监听
  301. this.initOnlineStatusListener();
  302. },
  303. onShow() {
  304. console.log('=== 消息页面显示 ===');
  305. // 重新验证登录状态
  306. const token = uni.getStorageSync('token');
  307. const storedUserId = uni.getStorageSync('userId');
  308. console.log('onShow - 检查登录状态:');
  309. console.log(' - token:', token ? '存在' : '不存在');
  310. console.log(' - storedUserId:', storedUserId);
  311. console.log(' - this.userId:', this.userId);
  312. // 如果未登录,跳转登录页
  313. if (!token || !storedUserId) {
  314. console.warn('⚠️ 未登录,跳转登录页');
  315. uni.reLaunch({
  316. url: '/pages/page3/page3'
  317. });
  318. return;
  319. }
  320. // 如果用户ID改变,更新页面userId并重新初始化TIM
  321. if (storedUserId !== this.userId) {
  322. console.warn('⚠️ 用户ID改变,从', this.userId, '到', storedUserId);
  323. console.log('🔄 更新页面userId并重新初始化TIM...');
  324. this.userId = storedUserId;
  325. this.timInitialized = false;
  326. // 重新初始化TIM
  327. this.initTIM().catch(error => {
  328. console.error('❌ 重新初始化TIM失败:', error);
  329. uni.showToast({
  330. title: '初始化失败',
  331. icon: 'none'
  332. });
  333. });
  334. return;
  335. }
  336. console.log('✅ 登录状态正常,用户ID:', this.userId);
  337. // 页面显示时刷新会话列表
  338. this.refreshConversations();
  339. this.loadSystemUnread();
  340. // 刷新在线状态
  341. this.refreshOnlineStatus();
  342. },
  343. onUnload() {
  344. // 清除定时器
  345. if (this.onlineCheckTimer) {
  346. clearInterval(this.onlineCheckTimer);
  347. }
  348. // 移除事件监听
  349. uni.$off('refreshConversations', this.refreshConversations);
  350. // 移除拉黑状态变更监听
  351. uni.$off('blacklistUpdated', this.handleBlacklistUpdate);
  352. // 清理在线状态轮询定时器
  353. if (this.onlineStatusTimer) {
  354. clearInterval(this.onlineStatusTimer);
  355. this.onlineStatusTimer = null;
  356. console.log('✅ 已停止在线状态轮询');
  357. }
  358. // 清理 WebSocket 在线状态监听
  359. const timPresenceManager = require('@/utils/tim-presence-manager.js').default;
  360. this.conversations.forEach(conv => {
  361. if (conv.onlineStatusCallback) {
  362. timPresenceManager.offStatusChange(conv.targetUserId, conv.onlineStatusCallback);
  363. }
  364. });
  365. console.log('✅ 已清理 WebSocket 监听');
  366. },
  367. methods: {
  368. /**
  369. * 处理拉黑列表更新事件
  370. */
  371. async handleBlacklistUpdate() {
  372. console.log('🔄 检测到拉黑列表更新,开始刷新会话列表');
  373. // 重置拉黑列表加载状态
  374. this.blacklistLoaded = false;
  375. // 重新加载拉黑列表
  376. await this.loadBlacklist();
  377. // 重新加载系统消息未读
  378. await this.loadSystemUnread();
  379. // 重新加载会话列表(会自动过滤拉黑用户)
  380. this.loadConversations();
  381. // 显示提示
  382. uni.showToast({
  383. title: '已更新会话列表',
  384. icon: 'success',
  385. duration: 1500
  386. });
  387. },
  388. /**
  389. * 初始化腾讯云IM
  390. */
  391. async initTIM() {
  392. try {
  393. console.log('📱 初始化腾讯云IM...');
  394. console.log('📱 当前用户ID:', this.userId);
  395. // 如果未初始化,先初始化
  396. if (!timManager.tim) {
  397. timManager.init(1600109674); // SDKAppID
  398. console.log('✅ TIM SDK 实例已创建');
  399. }
  400. // 检查是否已登录,以及登录的用户是否匹配
  401. if (timManager.isLogin && timManager.userId) {
  402. // 如果已登录但用户ID不匹配,先登出
  403. if (String(timManager.userId) !== String(this.userId)) {
  404. console.warn('⚠️ 检测到用户切换,从', timManager.userId, '到', this.userId);
  405. console.log('⚠️ 执行登出操作...');
  406. await timManager.logout();
  407. } else {
  408. console.log('✅ TIM 已登录,用户ID匹配:', this.userId);
  409. this.timInitialized = true;
  410. // 直接加载会话列表
  411. this.loadConversations();
  412. return;
  413. }
  414. }
  415. // 执行登录流程
  416. console.log('🔐 开始登录流程,用户ID:', this.userId);
  417. // 先导入用户到腾讯云IM
  418. await this.importUser();
  419. // 获取 UserSig 并登录
  420. const userSig = await this.getUserSig();
  421. console.log('🔑 获取到 UserSig');
  422. // 登录到 TIM
  423. await timManager.login(this.userId, userSig);
  424. console.log('✅ TIM 登录成功,用户ID:', this.userId);
  425. // 监听会话列表更新
  426. timManager.tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, (event) => {
  427. console.log('📋 会话列表更新事件触发');
  428. console.log('📋 当前登录用户:', this.userId);
  429. this.loadConversations();
  430. });
  431. this.timInitialized = true;
  432. console.log('✅ TIM 初始化完成');
  433. // 加载会话列表
  434. this.loadConversations();
  435. } catch (error) {
  436. console.error('❌ TIM 初始化失败:', error);
  437. console.error('❌ 错误详情:', error.message || error);
  438. uni.showToast({
  439. title: '初始化失败: ' + (error.message || '请重试'),
  440. icon: 'none',
  441. duration: 3000
  442. });
  443. }
  444. },
  445. /**
  446. * 导入用户到腾讯云IM
  447. */
  448. async importUser() {
  449. try {
  450. await uni.request({
  451. url: 'https://api.zhongruanke.cn/api/im/importUser',
  452. method: 'POST',
  453. data: {
  454. userId: String(this.userId)
  455. }
  456. });
  457. console.log('✅ 用户导入成功');
  458. } catch (error) {
  459. console.log('⚠️ 用户导入失败(可能已存在):', error);
  460. // 导入失败不影响登录
  461. }
  462. },
  463. /**
  464. * 获取 UserSig
  465. */
  466. async getUserSig() {
  467. try {
  468. const res = await uni.request({
  469. url: `https://api.zhongruanke.cn/api/im/getUserSig?userId=${this.userId}`,
  470. method: 'GET'
  471. });
  472. if (res[1].data.code === 200) {
  473. return res[1].data.data.userSig;
  474. } else {
  475. throw new Error(res[1].data.message);
  476. }
  477. } catch (error) {
  478. console.error('❌ 获取 UserSig 失败:', error);
  479. throw error;
  480. }
  481. },
  482. /**
  483. * 加载会话列表(从腾讯云IM)
  484. */
  485. async loadConversations() {
  486. if (this.loading || !this.timInitialized) {
  487. console.log('⏸️ 跳过加载会话列表:', this.loading ? '正在加载中' : 'TIM未初始化');
  488. return;
  489. }
  490. // 确保先加载拉黑列表
  491. if (!this.blacklistLoaded) {
  492. await this.loadBlacklist();
  493. }
  494. // 验证登录状态
  495. if (!timManager.isLogin || !timManager.userId) {
  496. console.error('❌ TIM 未登录或用户ID为空');
  497. return;
  498. }
  499. // 验证用户ID是否匹配
  500. if (String(timManager.userId) !== String(this.userId)) {
  501. console.error('❌ 用户ID不匹配!TIM:', timManager.userId, '页面:', this.userId);
  502. console.log('🔄 自动切换用户,重新登录TIM...');
  503. // 自动重新初始化TIM(会自动登出旧用户并登录新用户)
  504. this.timInitialized = false;
  505. try {
  506. await this.initTIM();
  507. // 初始化完成后会自动调用loadConversations
  508. } catch (error) {
  509. console.error('❌ 重新初始化TIM失败:', error);
  510. uni.showModal({
  511. title: '切换用户失败',
  512. content: '请重新登录',
  513. showCancel: false,
  514. success: () => {
  515. uni.reLaunch({
  516. url: '/pages/page3/page3'
  517. });
  518. }
  519. });
  520. }
  521. return;
  522. }
  523. this.loading = true;
  524. console.log('🔄 开始加载会话列表,用户ID:', this.userId);
  525. try {
  526. // 从腾讯云IM获取会话列表(仅当前登录用户的会话)
  527. const conversationList = await timManager.getConversationList();
  528. console.log('📋 从TIM获取到会话数:', conversationList.length);
  529. // 转换为UI需要的格式
  530. let formattedConversations = conversationList.map(conv => {
  531. const formatted = this.formatConversation(conv);
  532. // 验证会话是否属于当前用户
  533. if (formatted.userId !== this.userId) {
  534. console.warn('⚠️ 发现不属于当前用户的会话:', formatted);
  535. }
  536. return formatted;
  537. });
  538. // 过滤掉不属于当前用户的会话(双重保险)
  539. formattedConversations = formattedConversations.filter(conv => conv.userId === this.userId);
  540. // 先计算所有会话的未读数(包括拉黑用户)
  541. const allUnreadCount = formattedConversations.reduce((total, conv) => total + conv.unreadCount, 0);
  542. // 过滤掉拉黑用户的会话 🌟
  543. formattedConversations = formattedConversations.filter(conv => {
  544. return !this.blacklistUsers.includes(conv.targetUserId.toString());
  545. });
  546. this.conversations = formattedConversations;
  547. // 批量获取用户头像信息
  548. await this.loadUserAvatars();
  549. // 计算总未读数(包括所有会话的未读 + 系统消息未读)
  550. this.totalUnread = allUnreadCount + this.systemUnread;
  551. // 同步到Vuex
  552. this.$store.dispatch('updateTotalUnread', this.totalUnread);
  553. console.log('✅ 会话列表加载成功');
  554. console.log(' - 当前用户ID:', this.userId);
  555. console.log(' - 会话数量:', this.conversations.length);
  556. console.log(' - 拉黑用户数:', this.blacklistUsers.length);
  557. console.log(' - 会话未读数:', allUnreadCount);
  558. console.log(' - 系统消息未读数:', this.systemUnread);
  559. console.log(' - 总未读数:', this.totalUnread);
  560. // 输出前3个会话的详细信息(调试用)
  561. if (this.conversations.length > 0) {
  562. console.log('📋 会话预览(前3个):');
  563. this.conversations.slice(0, 3).forEach((conv, idx) => {
  564. console.log(` ${idx + 1}. ${conv.targetUserName} (ID:${conv.targetUserId}) 头像: ${conv.targetUserAvatar}, 未读: ${conv.unreadCount}`);
  565. });
  566. }
  567. if (this.blacklistUsers.length > 0) {
  568. console.log('🚫 已过滤拉黑用户:', this.blacklistUsers);
  569. }
  570. // 加载完会话列表后,立即查询一次在线状态
  571. await this.refreshOnlineStatus();
  572. } catch (e) {
  573. console.error('❌ 加载会话列表失败:', e);
  574. console.error('❌ 错误详情:', e.message || e);
  575. uni.showToast({
  576. title: '加载失败: ' + (e.message || '请重试'),
  577. icon: 'none',
  578. duration: 2000
  579. });
  580. } finally {
  581. this.loading = false;
  582. this.refreshing = false;
  583. }
  584. },
  585. /**
  586. * 获取拉黑用户列表
  587. */
  588. async loadBlacklist() {
  589. try {
  590. console.log('🔄 加载拉黑用户列表,用户ID:', this.userId);
  591. const res = await uni.request({
  592. url: 'https://api.zhongruanke.cn/api/chatfriend/getBlacklist', // 替换为你的后端接口
  593. method: 'GET',
  594. data: {
  595. userId: this.userId
  596. }
  597. });
  598. if (res[1].statusCode === 200 && res[1].data.code === 200) {
  599. // 假设返回格式: {data: [{targetUserId: 'xxx'}, ...]}
  600. const blacklistData = res[1].data.data || [];
  601. this.blacklistUsers = blacklistData.map(item => {
  602. // 确保用户ID为字符串格式,避免类型不一致问题
  603. return String(item.targetUserId || item.userId || item.id);
  604. });
  605. console.log('✅ 拉黑列表加载成功,共', this.blacklistUsers.length, '个拉黑用户:', this.blacklistUsers);
  606. } else {
  607. console.warn('⚠️ 拉黑列表接口返回异常:', res[1].data);
  608. }
  609. } catch (error) {
  610. console.error('❌ 加载拉黑列表失败:', error);
  611. // 加载失败不影响会话列表显示,只记录错误
  612. } finally {
  613. this.blacklistLoaded = true; // 标记为已加载,避免重复请求
  614. }
  615. },
  616. /**
  617. * 批量获取用户头像信息
  618. */
  619. async loadUserAvatars() {
  620. try {
  621. // 分离普通用户和红娘ID
  622. const normalUserIds = [];
  623. const matchmakerIds = [];
  624. this.conversations.forEach(conv => {
  625. if (!conv.targetUserId) return;
  626. if (conv.targetUserId.startsWith('m_')) {
  627. // 红娘ID,去掉 m_ 前缀
  628. const matchmakerId = conv.targetUserId.substring(2);
  629. matchmakerIds.push(matchmakerId);
  630. } else {
  631. // 普通用户ID
  632. normalUserIds.push(conv.targetUserId);
  633. }
  634. });
  635. console.log('🔄 开始批量获取信息 - 用户:', normalUserIds.length, '个, 红娘:', matchmakerIds.length, '个');
  636. // 创建ID到信息的映射
  637. const userInfoMap = {};
  638. // 1. 批量查询普通用户
  639. if (normalUserIds.length > 0) {
  640. const userRes = await uni.request({
  641. url: 'https://api.zhongruanke.cn/api/user/batch',
  642. method: 'GET',
  643. data: {
  644. userIds: normalUserIds.join(',')
  645. }
  646. });
  647. if (userRes[1].statusCode === 200 && userRes[1].data.code === 200) {
  648. const userList = userRes[1].data.data || [];
  649. userList.forEach(user => {
  650. userInfoMap[user.userId] = {
  651. nickname: user.nickname,
  652. avatarUrl: user.avatarUrl
  653. };
  654. });
  655. console.log('✅ 批量获取用户信息成功,数量:', userList.length);
  656. }
  657. }
  658. // 2. 批量查询红娘
  659. if (matchmakerIds.length > 0) {
  660. const matchmakerRes = await uni.request({
  661. url: 'http://localhost:8081/api/matchmaker/batch',
  662. method: 'GET',
  663. data: {
  664. matchmakerIds: matchmakerIds.join(',')
  665. }
  666. });
  667. if (matchmakerRes[1].statusCode === 200 && matchmakerRes[1].data.code === 200) {
  668. const matchmakerList = matchmakerRes[1].data.data || [];
  669. matchmakerList.forEach(matchmaker => {
  670. // 红娘的 IM ID 是 m_ + matchmakerId
  671. const imUserId = 'm_' + matchmaker.matchmakerId;
  672. userInfoMap[imUserId] = {
  673. nickname: matchmaker.realName,
  674. avatarUrl: matchmaker.avatarUrl
  675. };
  676. });
  677. console.log('✅ 批量获取红娘信息成功,数量:', matchmakerList.length);
  678. }
  679. }
  680. // 收集数据库中不存在的用户ID(排除红娘)
  681. const deletedUserIds = [];
  682. // 3. 更新会话列表中的头像和昵称
  683. for (const conv of this.conversations) {
  684. const userInfo = userInfoMap[conv.targetUserId];
  685. if (userInfo) {
  686. // 更新头像
  687. if (userInfo.avatarUrl) {
  688. conv.targetUserAvatar = userInfo.avatarUrl;
  689. }
  690. // 更新昵称
  691. if (userInfo.nickname && userInfo.nickname !== `用户${conv.targetUserId}`) {
  692. conv.targetUserName = userInfo.nickname;
  693. }
  694. console.log(`🖼️ 更新用户 ${conv.targetUserId} 的信息:`, {
  695. 昵称: conv.targetUserName,
  696. 头像: conv.targetUserAvatar
  697. });
  698. } else {
  699. // 只有普通用户不存在时才标记为删除(红娘不删除)
  700. if (!conv.targetUserId.startsWith('m_')) {
  701. console.warn(`⚠️ 用户 ${conv.targetUserId} 在数据库中不存在`);
  702. deletedUserIds.push(conv.targetUserId);
  703. } else {
  704. console.warn(`⚠️ 红娘 ${conv.targetUserId} 在数据库中不存在`);
  705. }
  706. }
  707. }
  708. // 4. 如果有不存在的普通用户,删除TIM中的会话和好友
  709. if (deletedUserIds.length > 0) {
  710. console.log(`🗑️ 发现 ${deletedUserIds.length} 个不存在的用户,开始清理TIM数据...`);
  711. await this.cleanupDeletedUsers(deletedUserIds);
  712. }
  713. } catch (error) {
  714. console.error('❌ 批量获取用户头像失败:', error);
  715. // 头像获取失败不影响会话列表显示,只记录错误
  716. }
  717. },
  718. /**
  719. * 格式化会话数据
  720. */
  721. formatConversation(timConv) {
  722. // conversationID 格式: C2C{userId}
  723. const targetUserId = timConv.conversationID.replace('C2C', '');
  724. // 检查是否在本地置顶列表中
  725. const isPinned = this.pinnedConversations.includes(timConv.conversationID) ? 1 : 0;
  726. // 判断是否是红娘:ID 以 m_ 开头
  727. const isMatchmaker = targetUserId.startsWith('m_');
  728. return {
  729. id: timConv.conversationID,
  730. userId: this.userId,
  731. targetUserId: targetUserId,
  732. targetUserName: timConv.userProfile?.nick || `用户${targetUserId}`,
  733. targetUserAvatar: timConv.userProfile?.avatar || '',
  734. lastMessage: this.getLastMessageText(timConv.lastMessage),
  735. lastMessageType: this.getMessageType(timConv.lastMessage),
  736. lastMessageTime: timConv.lastMessage?.lastTime ? timConv.lastMessage.lastTime * 1000 : Date.now(),
  737. unreadCount: timConv.unreadCount || 0,
  738. isOnline: false,
  739. isPinned: isPinned,
  740. isMatchmaker: isMatchmaker
  741. };
  742. },
  743. /**
  744. * 获取最后一条消息的文本
  745. */
  746. getLastMessageText(message) {
  747. if (!message) return '暂无消息';
  748. switch (message.type) {
  749. case 'TIMTextElem':
  750. return message.payload?.text || '';
  751. case 'TIMImageElem':
  752. return '[图片]';
  753. case 'TIMSoundElem':
  754. return '[语音]';
  755. case 'TIMVideoFileElem':
  756. return '[视频]';
  757. case 'TIMFileElem':
  758. return '[文件]';
  759. case 'TIMCustomElem':
  760. // 处理自定义消息(我们的语音消息)
  761. try {
  762. const customData = JSON.parse(message.payload.data);
  763. if (customData.type === 'voice') {
  764. return '[语音]';
  765. }
  766. } catch (e) {
  767. console.error('解析自定义消息失败:', e);
  768. }
  769. return '[自定义消息]';
  770. default:
  771. return '[未知消息]';
  772. }
  773. },
  774. /**
  775. * 获取消息类型
  776. */
  777. getMessageType(message) {
  778. if (!message) return 1;
  779. const typeMap = {
  780. 'TIMTextElem': 1, // 文本
  781. 'TIMImageElem': 2, // 图片
  782. 'TIMSoundElem': 3, // 语音
  783. 'TIMVideoFileElem': 4 // 视频
  784. };
  785. return typeMap[message.type] || 1;
  786. },
  787. /**
  788. * 下拉刷新
  789. */
  790. onRefresh() {
  791. this.refreshing = true;
  792. this.loadConversations();
  793. },
  794. /**
  795. * 加载更多(TIM一次性返回所有会话,不需要分页)
  796. */
  797. loadMore() {
  798. // TIM SDK 一次性返回所有会话,不需要分页加载
  799. },
  800. /**
  801. * 加载系统消息未读
  802. */
  803. async loadSystemUnread() {
  804. try {
  805. const userId = this.userId;
  806. const res = await this.$api?.message?.getSystemUnreadCount ? this.$api.message.getSystemUnreadCount(userId) : null;
  807. if (res && (res.code === 200 || res.code === 0)) {
  808. this.systemUnread = res.data || 0;
  809. } else {
  810. // 直接调用工具方法
  811. const api = require('@/utils/api.js').default;
  812. const r = await api.message.getSystemUnreadCount(userId);
  813. this.systemUnread = r.data || 0;
  814. }
  815. // 预览最新一条
  816. const api2 = require('@/utils/api.js').default;
  817. const listRes = await api2.message.getSystemList(userId, 1, 1);
  818. const list = listRes.data?.list || listRes.data || [];
  819. if (list.length > 0) {
  820. this.systemLatestTime = list[0].createdAt || list[0].created_at;
  821. this.systemLatestPreview = list[0].title || '系统通知';
  822. }
  823. // 更新总未读数
  824. const allUnreadCount = this.conversations.reduce((total, conv) => total + conv.unreadCount, 0);
  825. this.totalUnread = allUnreadCount + this.systemUnread;
  826. // 同步到Vuex
  827. this.$store.dispatch('updateTotalUnread', this.totalUnread);
  828. } catch (e) {
  829. console.log('加载系统未读失败', e);
  830. }
  831. },
  832. openSystemMessages() {
  833. uni.navigateTo({ url: '/subpkg-message/system/system' });
  834. },
  835. /**
  836. * 刷新会话列表
  837. */
  838. refreshConversations() {
  839. if (this.timInitialized) {
  840. // 先刷新系统消息未读
  841. this.loadSystemUnread();
  842. // 再刷新会话列表
  843. this.loadConversations();
  844. }
  845. },
  846. /**
  847. * 打开聊天页面
  848. */
  849. openChat(conversation) {
  850. uni.navigateTo({
  851. url: `/subpkg-message/chat/chat?targetUserId=${conversation.targetUserId}&targetUserName=${conversation.targetUserName}&targetUserAvatar=${conversation.targetUserAvatar || ''}`
  852. });
  853. },
  854. /**
  855. * 显示操作菜单
  856. */
  857. showActionMenu(conversation) {
  858. this.selectedConversation = conversation;
  859. this.$refs.actionMenu.open();
  860. },
  861. /**
  862. * 关闭操作菜单
  863. */
  864. closeActionMenu() {
  865. this.$refs.actionMenu.close();
  866. this.selectedConversation = null;
  867. },
  868. /**
  869. * 标记为已读
  870. */
  871. async markAsRead() {
  872. if (!this.selectedConversation) {
  873. return;
  874. }
  875. try {
  876. // 调用 TIM SDK 标记已读
  877. await timManager.setMessageRead(this.selectedConversation.id);
  878. // 更新本地显示
  879. this.selectedConversation.unreadCount = 0;
  880. // 重新计算总未读数(包含所有会话+系统消息)
  881. const allUnreadCount = this.conversations.reduce((total, conv) => total + conv.unreadCount, 0);
  882. this.totalUnread = allUnreadCount + this.systemUnread;
  883. // 同步到Vuex
  884. this.$store.dispatch('updateTotalUnread', this.totalUnread);
  885. uni.showToast({
  886. title: '已标记为已读',
  887. icon: 'success'
  888. });
  889. } catch (e) {
  890. console.error('标记已读失败', e);
  891. }
  892. this.closeActionMenu();
  893. },
  894. /**
  895. * 删除会话
  896. */
  897. async deleteCurrentConversation() {
  898. if (!this.selectedConversation) {
  899. return;
  900. }
  901. // 先保存引用,避免被 closeActionMenu 清空
  902. const conversation = this.selectedConversation;
  903. uni.showModal({
  904. title: '确认删除',
  905. content: '确定要删除该会话吗?',
  906. success: async (res) => {
  907. if (res.confirm) {
  908. try {
  909. // 调用 TIM SDK 删除会话
  910. await timManager.tim.deleteConversation(conversation.id);
  911. // 从列表中移除
  912. const index = this.conversations.findIndex(c => c.id === conversation.id);
  913. if (index > -1) {
  914. this.conversations.splice(index, 1);
  915. }
  916. // 重新计算总未读数(包含所有会话+系统消息)
  917. const allUnreadCount = this.conversations.reduce((total, conv) => total + conv.unreadCount, 0);
  918. this.totalUnread = allUnreadCount + this.systemUnread;
  919. // 同步到Vuex
  920. this.$store.dispatch('updateTotalUnread', this.totalUnread);
  921. uni.showToast({
  922. title: '删除成功',
  923. icon: 'success'
  924. });
  925. } catch (e) {
  926. console.error('删除会话失败', e);
  927. uni.showToast({
  928. title: '删除失败',
  929. icon: 'none'
  930. });
  931. }
  932. }
  933. // 在回调结束后关闭菜单
  934. this.closeActionMenu();
  935. }
  936. });
  937. },
  938. /**
  939. * 搜索(实时过滤在computed中实现)
  940. */
  941. onSearch() {
  942. console.log('搜索:', this.searchKeyword);
  943. // filteredConversations computed属性会自动过滤
  944. },
  945. /**
  946. * 取消搜索
  947. */
  948. cancelSearch() {
  949. this.showSearchPanel = false;
  950. this.searchKeyword = '';
  951. },
  952. /**
  953. * 处理滑动
  954. */
  955. handleSwipe(e, conv) {
  956. if (e.detail.x < -50) {
  957. this.swipingConvId = conv.id;
  958. } else if (e.detail.x > -10) {
  959. this.swipingConvId = null;
  960. }
  961. },
  962. /**
  963. * 滑动结束
  964. */
  965. handleSwipeEnd(conv) {
  966. // 如果滑动距离不够,自动回弹
  967. setTimeout(() => {
  968. if (this.swipingConvId === conv.id) {
  969. // 保持显示操作按钮
  970. }
  971. }, 100);
  972. },
  973. /**
  974. * 切换置顶状态
  975. */
  976. togglePin(conv) {
  977. conv.isPinned = conv.isPinned ? 0 : 1;
  978. // 保存到本地存储
  979. this.savePinnedConversations();
  980. // 重置滑动状态
  981. this.swipingConvId = null;
  982. uni.showToast({
  983. title: conv.isPinned ? '已置顶' : '已取消置顶',
  984. icon: 'success'
  985. });
  986. },
  987. /**
  988. * 加载置顶会话列表
  989. */
  990. loadPinnedConversations() {
  991. try {
  992. const pinned = uni.getStorageSync('pinnedConversations_' + this.userId);
  993. if (pinned) {
  994. this.pinnedConversations = JSON.parse(pinned);
  995. }
  996. } catch (e) {
  997. console.error('加载置顶列表失败:', e);
  998. }
  999. },
  1000. /**
  1001. * 保存置顶会话列表
  1002. */
  1003. savePinnedConversations() {
  1004. try {
  1005. const pinnedIds = this.conversations
  1006. .filter(conv => conv.isPinned)
  1007. .map(conv => conv.id);
  1008. uni.setStorageSync('pinnedConversations_' + this.userId, JSON.stringify(pinnedIds));
  1009. } catch (e) {
  1010. console.error('保存置顶列表失败:', e);
  1011. }
  1012. },
  1013. /**
  1014. * 确认删除会话
  1015. */
  1016. confirmDeleteConversation(conv) {
  1017. uni.showModal({
  1018. title: '确认删除',
  1019. content: '确定要删除该会话吗?',
  1020. success: (res) => {
  1021. if (res.confirm) {
  1022. this.deleteConversationItem(conv);
  1023. }
  1024. }
  1025. });
  1026. // 重置滑动状态
  1027. this.swipingConvId = null;
  1028. },
  1029. /**
  1030. * 删除会话
  1031. */
  1032. async deleteConversationItem(conv) {
  1033. try {
  1034. // 调用 TIM SDK 删除会话
  1035. await timManager.tim.deleteConversation(conv.id);
  1036. // 从列表中移除
  1037. const index = this.conversations.findIndex(c => c.id === conv.id);
  1038. if (index > -1) {
  1039. this.conversations.splice(index, 1);
  1040. }
  1041. // 重新计算总未读数(包含所有会话+系统消息)
  1042. const allUnreadCount = this.conversations.reduce((total, c) => total + c.unreadCount, 0);
  1043. this.totalUnread = allUnreadCount + this.systemUnread;
  1044. // 同步到Vuex
  1045. this.$store.dispatch('updateTotalUnread', this.totalUnread);
  1046. uni.showToast({
  1047. title: '删除成功',
  1048. icon: 'success'
  1049. });
  1050. } catch (e) {
  1051. console.error('删除会话失败', e);
  1052. uni.showToast({
  1053. title: '删除失败',
  1054. icon: 'none'
  1055. });
  1056. }
  1057. },
  1058. /**
  1059. * 格式化最后一条消息
  1060. */
  1061. formatLastMessage(conv) {
  1062. if (!conv.lastMessage) {
  1063. return '暂无消息';
  1064. }
  1065. // 限制长度
  1066. const maxLen = 30;
  1067. if (conv.lastMessage.length > maxLen) {
  1068. return conv.lastMessage.substring(0, maxLen) + '...';
  1069. }
  1070. return conv.lastMessage;
  1071. },
  1072. /**
  1073. * 格式化时间
  1074. */
  1075. formatTime(time) {
  1076. if (!time) return '';
  1077. const date = new Date(time);
  1078. const now = new Date();
  1079. const diff = now - date;
  1080. // 今天
  1081. if (date.toDateString() === now.toDateString()) {
  1082. return date.toLocaleTimeString('zh-CN', {
  1083. hour: '2-digit',
  1084. minute: '2-digit'
  1085. });
  1086. }
  1087. // 昨天
  1088. const yesterday = new Date(now);
  1089. yesterday.setDate(yesterday.getDate() - 1);
  1090. if (date.toDateString() === yesterday.toDateString()) {
  1091. return '昨天';
  1092. }
  1093. // 本周
  1094. if (diff < 7 * 24 * 60 * 60 * 1000) {
  1095. const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  1096. return days[date.getDay()];
  1097. }
  1098. // 更早
  1099. return date.toLocaleDateString('zh-CN', {
  1100. month: '2-digit',
  1101. day: '2-digit'
  1102. });
  1103. },
  1104. /**
  1105. * 初始化在线状态监听(WebSocket 实时推送 + HTTP 轮询)
  1106. */
  1107. async initOnlineStatusListener() {
  1108. console.log('🔄 初始化在线状态监听(WebSocket + HTTP)');
  1109. const timPresenceManager = require('@/utils/tim-presence-manager.js').default;
  1110. // 1. 立即查询一次
  1111. await this.refreshOnlineStatus();
  1112. // 2. 为每个会话用户注册 WebSocket 监听
  1113. this.conversations.forEach(conv => {
  1114. const callback = (status) => {
  1115. console.log(`⚡ 实时收到用户 ${conv.targetUserId} 状态变更: ${status}`);
  1116. // 更新会话列表中的在线状态
  1117. const conversation = this.conversations.find(c => c.targetUserId === conv.targetUserId);
  1118. if (conversation) {
  1119. this.$set(conversation, 'isOnline', status === 'online');
  1120. }
  1121. };
  1122. // 保存回调引用
  1123. conv.onlineStatusCallback = callback;
  1124. // 注册监听
  1125. timPresenceManager.onStatusChange(conv.targetUserId, callback);
  1126. });
  1127. // 3. 启动 HTTP 轮询作为补充(30秒间隔)
  1128. this.onlineStatusTimer = setInterval(() => {
  1129. this.refreshOnlineStatus();
  1130. }, 30000);
  1131. console.log('✅ 在线状态监听已启动(WebSocket 实时 + HTTP 轮询)');
  1132. },
  1133. /**
  1134. * 刷新在线状态(HTTP 查询方式)
  1135. */
  1136. async refreshOnlineStatus() {
  1137. console.log('🔄 刷新在线状态(HTTP 查询)');
  1138. // 批量查询所有会话用户的在线状态
  1139. for (const conv of this.conversations) {
  1140. try {
  1141. const [err, res] = await uni.request({
  1142. url: 'https://api.zhongruanke.cn/api/online/checkStatus',
  1143. method: 'GET',
  1144. data: {
  1145. userId: conv.targetUserId
  1146. }
  1147. });
  1148. if (!err && res.data && res.data.code === 200) {
  1149. this.$set(conv, 'isOnline', res.data.data.online || false);
  1150. }
  1151. } catch (error) {
  1152. console.error(`❌ 查询用户 ${conv.targetUserId} 在线状态失败:`, error);
  1153. }
  1154. }
  1155. console.log('✅ 在线状态刷新完成');
  1156. },
  1157. /**
  1158. * 清理已删除用户的TIM数据
  1159. * @param {Array} deletedUserIds 已删除的用户ID列表
  1160. */
  1161. async cleanupDeletedUsers(deletedUserIds) {
  1162. try {
  1163. console.log('🗑️ 开始清理已删除用户的TIM数据:', deletedUserIds);
  1164. let successCount = 0;
  1165. let failCount = 0;
  1166. for (const userId of deletedUserIds) {
  1167. try {
  1168. // 1. 删除TIM会话
  1169. const conversationID = `C2C${userId}`;
  1170. await timManager.tim.deleteConversation(conversationID);
  1171. console.log(`✅ 已删除会话: ${conversationID}`);
  1172. // 2. 删除TIM好友关系
  1173. await timManager.tim.deleteFriend({
  1174. userIDList: [String(userId)],
  1175. type: timManager.tim.TYPES.SNS_DELETE_TYPE_BOTH // 双向删除
  1176. });
  1177. console.log(`✅ 已删除好友: ${userId}`);
  1178. // 3. 从本地会话列表中移除
  1179. const index = this.conversations.findIndex(conv => conv.targetUserId === userId);
  1180. if (index > -1) {
  1181. this.conversations.splice(index, 1);
  1182. console.log(`✅ 已从本地列表移除: ${userId}`);
  1183. }
  1184. successCount++;
  1185. } catch (error) {
  1186. console.error(`❌ 清理用户 ${userId} 失败:`, error);
  1187. failCount++;
  1188. }
  1189. }
  1190. // 重新计算总未读数
  1191. const allUnreadCount = this.conversations.reduce((total, conv) => total + conv.unreadCount, 0);
  1192. this.totalUnread = allUnreadCount + this.systemUnread;
  1193. this.$store.dispatch('updateTotalUnread', this.totalUnread);
  1194. console.log(`✅ TIM数据清理完成: 成功${successCount}个, 失败${failCount}个`);
  1195. // 显示提示
  1196. if (successCount > 0) {
  1197. uni.showToast({
  1198. title: `已清理${successCount}个无效会话`,
  1199. icon: 'success',
  1200. duration: 2000
  1201. });
  1202. }
  1203. } catch (error) {
  1204. console.error('❌ 清理TIM数据失败:', error);
  1205. }
  1206. },
  1207. /**
  1208. * 切换标签页
  1209. */
  1210. switchTab(tab) {
  1211. if (tab === 'message') return;
  1212. const tabPages = {
  1213. index: '/pages/index/index',
  1214. plaza: '/pages/plaza/index',
  1215. recommend: '/pages/recommend/index',
  1216. mine: '/pages/mine/index'
  1217. };
  1218. if (tabPages[tab]) {
  1219. uni.redirectTo({
  1220. url: tabPages[tab]
  1221. });
  1222. }
  1223. }
  1224. }
  1225. };
  1226. </script>
  1227. <style lang="scss" scoped>
  1228. .message-page {
  1229. min-height: 100vh;
  1230. background-color: #F5F5F5;
  1231. padding-bottom: 120rpx;
  1232. }
  1233. /* 顶部标题栏 */
  1234. .header {
  1235. display: flex;
  1236. align-items: center;
  1237. justify-content: space-between;
  1238. padding: 30rpx;
  1239. background-color: #FFFFFF;
  1240. border-bottom: 1rpx solid #F0F0F0;
  1241. .header-title {
  1242. font-size: 40rpx;
  1243. font-weight: bold;
  1244. color: #E91E63;
  1245. }
  1246. .header-actions {
  1247. display: flex;
  1248. gap: 30rpx;
  1249. .action-icon {
  1250. font-size: 40rpx;
  1251. cursor: pointer;
  1252. }
  1253. }
  1254. }
  1255. /* 搜索面板 */
  1256. .search-panel {
  1257. background-color: #FFFFFF;
  1258. padding: 20rpx 30rpx;
  1259. border-bottom: 1rpx solid #F0F0F0;
  1260. .search-bar {
  1261. display: flex;
  1262. align-items: center;
  1263. gap: 20rpx;
  1264. .search-input {
  1265. flex: 1;
  1266. height: 70rpx;
  1267. padding: 0 20rpx;
  1268. background-color: #F5F5F5;
  1269. border-radius: 35rpx;
  1270. font-size: 28rpx;
  1271. }
  1272. .search-cancel {
  1273. font-size: 28rpx;
  1274. color: #E91E63;
  1275. }
  1276. }
  1277. }
  1278. /* 会话列表 */
  1279. .conversation-list {
  1280. height: calc(100vh - 200rpx);
  1281. background-color: #FFFFFF;
  1282. }
  1283. /* 骨架屏 */
  1284. .skeleton-container {
  1285. padding: 20rpx 0;
  1286. }
  1287. .skeleton-item {
  1288. display: flex;
  1289. align-items: center;
  1290. padding: 25rpx 30rpx;
  1291. background-color: #FFFFFF;
  1292. border-bottom: 1rpx solid #F5F5F5;
  1293. .skeleton-avatar {
  1294. width: 100rpx;
  1295. height: 100rpx;
  1296. border-radius: 12rpx;
  1297. background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  1298. background-size: 200% 100%;
  1299. animation: skeleton-loading 1.5s ease-in-out infinite;
  1300. margin-right: 25rpx;
  1301. }
  1302. .skeleton-content {
  1303. flex: 1;
  1304. .skeleton-line {
  1305. height: 30rpx;
  1306. border-radius: 6rpx;
  1307. background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  1308. background-size: 200% 100%;
  1309. animation: skeleton-loading 1.5s ease-in-out infinite;
  1310. &.skeleton-line-title {
  1311. width: 40%;
  1312. margin-bottom: 20rpx;
  1313. }
  1314. &.skeleton-line-text {
  1315. width: 60%;
  1316. }
  1317. }
  1318. }
  1319. }
  1320. @keyframes skeleton-loading {
  1321. 0% {
  1322. background-position: 200% 0;
  1323. }
  1324. 100% {
  1325. background-position: -200% 0;
  1326. }
  1327. }
  1328. /* 空状态 */
  1329. .empty-container {
  1330. display: flex;
  1331. flex-direction: column;
  1332. align-items: center;
  1333. justify-content: center;
  1334. padding: 150rpx 60rpx;
  1335. .empty-icon-wrapper {
  1336. width: 200rpx;
  1337. height: 200rpx;
  1338. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  1339. border-radius: 50%;
  1340. display: flex;
  1341. align-items: center;
  1342. justify-content: center;
  1343. margin-bottom: 40rpx;
  1344. box-shadow: 0 20rpx 60rpx rgba(102, 126, 234, 0.3);
  1345. animation: float 3s ease-in-out infinite;
  1346. }
  1347. .empty-icon {
  1348. font-size: 100rpx;
  1349. filter: brightness(1.2);
  1350. }
  1351. .empty-text {
  1352. font-size: 36rpx;
  1353. font-weight: 600;
  1354. color: #333333;
  1355. margin-bottom: 15rpx;
  1356. }
  1357. .empty-hint {
  1358. font-size: 28rpx;
  1359. color: #999999;
  1360. margin-bottom: 40rpx;
  1361. }
  1362. .empty-action {
  1363. margin-top: 20rpx;
  1364. .empty-btn {
  1365. padding: 20rpx 60rpx;
  1366. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  1367. color: #FFFFFF;
  1368. border-radius: 50rpx;
  1369. font-size: 28rpx;
  1370. border: none;
  1371. box-shadow: 0 10rpx 30rpx rgba(102, 126, 234, 0.3);
  1372. &::after {
  1373. border: none;
  1374. }
  1375. }
  1376. }
  1377. }
  1378. @keyframes float {
  1379. 0%, 100% {
  1380. transform: translateY(0);
  1381. }
  1382. 50% {
  1383. transform: translateY(-20rpx);
  1384. }
  1385. }
  1386. /* 会话列表项包装器 */
  1387. .conversation-item-wrapper {
  1388. position: relative;
  1389. background-color: #FFFFFF;
  1390. border-bottom: 1rpx solid #F5F5F5;
  1391. overflow: hidden;
  1392. }
  1393. /* 系统消息高亮样式 */
  1394. .system-highlight { background: #fff7f7; }
  1395. .system-icon { font-size: 44rpx; color: #E91E63; }
  1396. .system-title { color: #E91E63; font-weight: 600; }
  1397. .system-preview { color: #d25d6b; }
  1398. .system-tag { font-size: 22rpx; color: #fff; background-color: #E91E63; padding: 4rpx 10rpx; border-radius: 8rpx; }
  1399. /* 滑动区域 */
  1400. .movable-area {
  1401. width: 100%;
  1402. height: 160rpx;
  1403. position: relative;
  1404. }
  1405. .movable-view {
  1406. width: 100%;
  1407. height: 100%;
  1408. background-color: #FFFFFF;
  1409. }
  1410. /* 会话列表项 */
  1411. .conversation-item {
  1412. display: flex;
  1413. align-items: center;
  1414. padding: 25rpx 30rpx;
  1415. background-color: #FFFFFF;
  1416. position: relative;
  1417. width: 94%;
  1418. height: 100%;
  1419. &:active {
  1420. background-color: #F8F8F8;
  1421. }
  1422. /* 置顶标记 */
  1423. .pinned-badge {
  1424. position: absolute;
  1425. top: 10rpx;
  1426. left: 10rpx;
  1427. font-size: 28rpx;
  1428. opacity: 0.7;
  1429. }
  1430. .avatar-wrapper {
  1431. position: relative;
  1432. margin-right: 25rpx;
  1433. .avatar {
  1434. width: 100rpx;
  1435. height: 100rpx;
  1436. border-radius: 12rpx;
  1437. }
  1438. .online-badge {
  1439. position: absolute;
  1440. bottom: 2rpx;
  1441. right: 2rpx;
  1442. width: 26rpx;
  1443. height: 26rpx;
  1444. background-color: #07C160;
  1445. border: 4rpx solid #FFFFFF;
  1446. border-radius: 50%;
  1447. box-shadow: 0 0 8rpx rgba(7, 193, 96, 0.5);
  1448. z-index: 10;
  1449. }
  1450. .unread-badge {
  1451. position: absolute;
  1452. top: -10rpx;
  1453. right: -10rpx;
  1454. min-width: 36rpx;
  1455. height: 36rpx;
  1456. line-height: 36rpx;
  1457. padding: 0 8rpx;
  1458. background-color: #FA5151;
  1459. border-radius: 18rpx;
  1460. font-size: 20rpx;
  1461. color: #FFFFFF;
  1462. text-align: center;
  1463. }
  1464. }
  1465. .conversation-content {
  1466. flex: 1;
  1467. .content-top {
  1468. display: flex;
  1469. align-items: center;
  1470. justify-content: space-between;
  1471. margin-bottom: 12rpx;
  1472. .user-info {
  1473. display: flex;
  1474. align-items: center;
  1475. }
  1476. .user-name {
  1477. font-size: 32rpx;
  1478. font-weight: 500;
  1479. color: #333333;
  1480. }
  1481. .matchmaker-tag {
  1482. background: linear-gradient(135deg, #ff6b6b, #ee5a24);
  1483. color: #fff;
  1484. font-size: 20rpx;
  1485. padding: 4rpx 12rpx;
  1486. border-radius: 6rpx;
  1487. margin-left: 10rpx;
  1488. }
  1489. .last-time {
  1490. font-size: 24rpx;
  1491. color: #999999;
  1492. }
  1493. }
  1494. .content-bottom {
  1495. display: flex;
  1496. align-items: center;
  1497. gap: 10rpx;
  1498. .last-message {
  1499. flex: 1;
  1500. font-size: 28rpx;
  1501. color: #999999;
  1502. overflow: hidden;
  1503. text-overflow: ellipsis;
  1504. white-space: nowrap;
  1505. &.unread {
  1506. color: #666666;
  1507. font-weight: 500;
  1508. }
  1509. }
  1510. .message-type-icon {
  1511. font-size: 28rpx;
  1512. }
  1513. }
  1514. }
  1515. /* 右滑操作按钮 */
  1516. .conversation-actions {
  1517. position: absolute;
  1518. right: 0;
  1519. top: 0;
  1520. height: 100%;
  1521. display: flex;
  1522. z-index: 1;
  1523. .action-btn {
  1524. width: 150rpx;
  1525. height: 100%;
  1526. display: flex;
  1527. align-items: center;
  1528. justify-content: center;
  1529. color: #FFFFFF;
  1530. font-size: 28rpx;
  1531. }
  1532. .pin-btn {
  1533. background-color: #576B95;
  1534. }
  1535. .delete-btn {
  1536. background-color: #FA5151;
  1537. }
  1538. }
  1539. }
  1540. .load-more {
  1541. padding: 30rpx;
  1542. text-align: center;
  1543. .load-more-text {
  1544. font-size: 26rpx;
  1545. color: #999999;
  1546. }
  1547. }
  1548. /* 底部导航栏 */
  1549. .tabbar {
  1550. position: fixed;
  1551. bottom: 0;
  1552. left: 0;
  1553. right: 0;
  1554. display: flex;
  1555. background-color: #FFFFFF;
  1556. border-top: 1rpx solid #F0F0F0;
  1557. padding-bottom: constant(safe-area-inset-bottom);
  1558. padding-bottom: env(safe-area-inset-bottom);
  1559. z-index: 999;
  1560. .tabbar-item {
  1561. flex: 1;
  1562. display: flex;
  1563. flex-direction: column;
  1564. align-items: center;
  1565. justify-content: center;
  1566. padding: 15rpx 0;
  1567. position: relative;
  1568. .tabbar-icon {
  1569. font-size: 44rpx;
  1570. margin-bottom: 5rpx;
  1571. }
  1572. .tabbar-text {
  1573. font-size: 22rpx;
  1574. color: #666666;
  1575. }
  1576. .tab-badge {
  1577. position: absolute;
  1578. top: 8rpx;
  1579. right: 50%;
  1580. margin-right: -40rpx;
  1581. min-width: 32rpx;
  1582. height: 32rpx;
  1583. line-height: 32rpx;
  1584. padding: 0 6rpx;
  1585. background-color: #FA5151;
  1586. border-radius: 16rpx;
  1587. font-size: 20rpx;
  1588. color: #FFFFFF;
  1589. text-align: center;
  1590. }
  1591. &.active {
  1592. .tabbar-text {
  1593. color: #E91E63;
  1594. font-weight: bold;
  1595. }
  1596. }
  1597. }
  1598. }
  1599. /* 操作菜单 */
  1600. .action-menu {
  1601. background-color: #FFFFFF;
  1602. border-radius: 20rpx 20rpx 0 0;
  1603. .menu-item {
  1604. padding: 30rpx;
  1605. text-align: center;
  1606. font-size: 32rpx;
  1607. color: #333333;
  1608. border-bottom: 1rpx solid #F0F0F0;
  1609. &:active {
  1610. background-color: #F8F8F8;
  1611. }
  1612. &.cancel {
  1613. color: #999999;
  1614. border: none;
  1615. margin-top: 20rpx;
  1616. }
  1617. }
  1618. }
  1619. </style>