index.vue 53 KB

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