index.vue 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821
  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. if (this.conversations.length === 0) {
  619. return;
  620. }
  621. // 收集所有需要获取头像的用户ID
  622. const userIds = this.conversations
  623. .map(conv => conv.targetUserId)
  624. .filter(id => id) // 过滤掉空值
  625. .join(',');
  626. if (!userIds) {
  627. console.log('⚠️ 没有需要获取头像的用户');
  628. return;
  629. }
  630. console.log('🔄 开始批量获取用户头像,用户ID列表:', userIds);
  631. // 调用批量获取用户信息接口
  632. const res = await uni.request({
  633. url: 'http://localhost:8083/api/user/batch',
  634. method: 'GET',
  635. data: {
  636. userIds: userIds
  637. }
  638. });
  639. if (res[1].statusCode === 200 && res[1].data.code === 200) {
  640. const userList = res[1].data.data || [];
  641. console.log('✅ 批量获取用户信息成功,数量:', userList.length);
  642. // 创建用户ID到用户信息的映射
  643. const userMap = {};
  644. userList.forEach(user => {
  645. userMap[user.userId] = user;
  646. });
  647. // 收集数据库中不存在的用户ID
  648. const deletedUserIds = [];
  649. // 更新会话列表中的头像和昵称
  650. for (const conv of this.conversations) {
  651. const userInfo = userMap[conv.targetUserId];
  652. if (userInfo) {
  653. // 更新头像(如果数据库中有头像)
  654. if (userInfo.avatarUrl) {
  655. conv.targetUserAvatar = userInfo.avatarUrl;
  656. }
  657. // 更新昵称(如果数据库中的昵称更准确)
  658. if (userInfo.nickname && userInfo.nickname !== `用户${conv.targetUserId}`) {
  659. conv.targetUserName = userInfo.nickname;
  660. }
  661. console.log(`🖼️ 更新用户 ${conv.targetUserId} 的信息:`, {
  662. 昵称: conv.targetUserName,
  663. 头像: conv.targetUserAvatar
  664. });
  665. } else {
  666. // 数据库中不存在该用户,标记为需要删除
  667. console.warn(`⚠️ 用户 ${conv.targetUserId} 在数据库中不存在`);
  668. deletedUserIds.push(conv.targetUserId);
  669. }
  670. }
  671. // 如果有不存在的用户,删除TIM中的会话和好友
  672. if (deletedUserIds.length > 0) {
  673. console.log(`🗑️ 发现 ${deletedUserIds.length} 个不存在的用户,开始清理TIM数据...`);
  674. await this.cleanupDeletedUsers(deletedUserIds);
  675. }
  676. } else {
  677. console.error('❌ 批量获取用户信息失败:', res[1].data);
  678. }
  679. } catch (error) {
  680. console.error('❌ 批量获取用户头像失败:', error);
  681. // 头像获取失败不影响会话列表显示,只记录错误
  682. }
  683. },
  684. /**
  685. * 格式化会话数据
  686. * 将TIM的会话格式转换为UI需要的格式
  687. */
  688. formatConversation(timConv) {
  689. // conversationID 格式: C2C{userId}
  690. const targetUserId = timConv.conversationID.replace('C2C', '');
  691. // 检查是否在本地置顶列表中
  692. const isPinned = this.pinnedConversations.includes(timConv.conversationID) ? 1 : 0;
  693. return {
  694. id: timConv.conversationID,
  695. userId: this.userId,
  696. targetUserId: targetUserId,
  697. targetUserName: timConv.userProfile?.nick || `用户${targetUserId}`,
  698. targetUserAvatar: timConv.userProfile?.avatar || '',
  699. lastMessage: this.getLastMessageText(timConv.lastMessage),
  700. lastMessageType: this.getMessageType(timConv.lastMessage),
  701. lastMessageTime: timConv.lastMessage?.lastTime ? timConv.lastMessage.lastTime * 1000 : Date.now(),
  702. unreadCount: timConv.unreadCount || 0,
  703. isOnline: false,
  704. isPinned: isPinned
  705. };
  706. },
  707. /**
  708. * 获取最后一条消息的文本
  709. */
  710. getLastMessageText(message) {
  711. if (!message) return '暂无消息';
  712. switch (message.type) {
  713. case 'TIMTextElem':
  714. return message.payload?.text || '';
  715. case 'TIMImageElem':
  716. return '[图片]';
  717. case 'TIMSoundElem':
  718. return '[语音]';
  719. case 'TIMVideoFileElem':
  720. return '[视频]';
  721. case 'TIMFileElem':
  722. return '[文件]';
  723. case 'TIMCustomElem':
  724. // 处理自定义消息(我们的语音消息)
  725. try {
  726. const customData = JSON.parse(message.payload.data);
  727. if (customData.type === 'voice') {
  728. return '[语音]';
  729. }
  730. } catch (e) {
  731. console.error('解析自定义消息失败:', e);
  732. }
  733. return '[自定义消息]';
  734. default:
  735. return '[未知消息]';
  736. }
  737. },
  738. /**
  739. * 获取消息类型
  740. */
  741. getMessageType(message) {
  742. if (!message) return 1;
  743. const typeMap = {
  744. 'TIMTextElem': 1, // 文本
  745. 'TIMImageElem': 2, // 图片
  746. 'TIMSoundElem': 3, // 语音
  747. 'TIMVideoFileElem': 4 // 视频
  748. };
  749. return typeMap[message.type] || 1;
  750. },
  751. /**
  752. * 下拉刷新
  753. */
  754. onRefresh() {
  755. this.refreshing = true;
  756. this.loadConversations();
  757. },
  758. /**
  759. * 加载更多(TIM一次性返回所有会话,不需要分页)
  760. */
  761. loadMore() {
  762. // TIM SDK 一次性返回所有会话,不需要分页加载
  763. },
  764. /**
  765. * 加载系统消息未读
  766. */
  767. async loadSystemUnread() {
  768. try {
  769. const userId = this.userId;
  770. const res = await this.$api?.message?.getSystemUnreadCount ? this.$api.message.getSystemUnreadCount(userId) : null;
  771. if (res && (res.code === 200 || res.code === 0)) {
  772. this.systemUnread = res.data || 0;
  773. } else {
  774. // 直接调用工具方法
  775. const api = require('@/utils/api.js').default;
  776. const r = await api.message.getSystemUnreadCount(userId);
  777. this.systemUnread = r.data || 0;
  778. }
  779. // 预览最新一条
  780. const api2 = require('@/utils/api.js').default;
  781. const listRes = await api2.message.getSystemList(userId, 1, 1);
  782. const list = listRes.data?.list || listRes.data || [];
  783. if (list.length > 0) {
  784. this.systemLatestTime = list[0].createdAt || list[0].created_at;
  785. this.systemLatestPreview = list[0].title || '系统通知';
  786. }
  787. // 更新总未读数
  788. const allUnreadCount = this.conversations.reduce((total, conv) => total + conv.unreadCount, 0);
  789. this.totalUnread = allUnreadCount + this.systemUnread;
  790. // 同步到Vuex
  791. this.$store.dispatch('updateTotalUnread', this.totalUnread);
  792. } catch (e) {
  793. console.log('加载系统未读失败', e);
  794. }
  795. },
  796. openSystemMessages() {
  797. uni.navigateTo({ url: '/pages/message/system' });
  798. },
  799. /**
  800. * 刷新会话列表
  801. */
  802. refreshConversations() {
  803. if (this.timInitialized) {
  804. // 先刷新系统消息未读
  805. this.loadSystemUnread();
  806. // 再刷新会话列表
  807. this.loadConversations();
  808. }
  809. },
  810. /**
  811. * 打开聊天页面
  812. */
  813. openChat(conversation) {
  814. uni.navigateTo({
  815. url: `/pages/message/chat?targetUserId=${conversation.targetUserId}&targetUserName=${conversation.targetUserName}&targetUserAvatar=${conversation.targetUserAvatar || ''}`
  816. });
  817. },
  818. /**
  819. * 显示操作菜单
  820. */
  821. showActionMenu(conversation) {
  822. this.selectedConversation = conversation;
  823. this.$refs.actionMenu.open();
  824. },
  825. /**
  826. * 关闭操作菜单
  827. */
  828. closeActionMenu() {
  829. this.$refs.actionMenu.close();
  830. this.selectedConversation = null;
  831. },
  832. /**
  833. * 标记为已读
  834. */
  835. async markAsRead() {
  836. if (!this.selectedConversation) {
  837. return;
  838. }
  839. try {
  840. // 调用 TIM SDK 标记已读
  841. await timManager.setMessageRead(this.selectedConversation.id);
  842. // 更新本地显示
  843. this.selectedConversation.unreadCount = 0;
  844. // 重新计算总未读数(包含所有会话+系统消息)
  845. const allUnreadCount = this.conversations.reduce((total, conv) => total + conv.unreadCount, 0);
  846. this.totalUnread = allUnreadCount + this.systemUnread;
  847. // 同步到Vuex
  848. this.$store.dispatch('updateTotalUnread', this.totalUnread);
  849. uni.showToast({
  850. title: '已标记为已读',
  851. icon: 'success'
  852. });
  853. } catch (e) {
  854. console.error('标记已读失败', e);
  855. }
  856. this.closeActionMenu();
  857. },
  858. /**
  859. * 删除会话
  860. */
  861. async deleteCurrentConversation() {
  862. if (!this.selectedConversation) {
  863. return;
  864. }
  865. uni.showModal({
  866. title: '确认删除',
  867. content: '确定要删除该会话吗?',
  868. success: async (res) => {
  869. if (res.confirm) {
  870. try {
  871. // 调用 TIM SDK 删除会话
  872. await timManager.tim.deleteConversation(this.selectedConversation.id);
  873. // 从列表中移除
  874. const index = this.conversations.findIndex(c => c.id === this.selectedConversation.id);
  875. if (index > -1) {
  876. this.conversations.splice(index, 1);
  877. }
  878. // 重新计算总未读数(包含所有会话+系统消息)
  879. const allUnreadCount = this.conversations.reduce((total, conv) => total + conv.unreadCount, 0);
  880. this.totalUnread = allUnreadCount + this.systemUnread;
  881. // 同步到Vuex
  882. this.$store.dispatch('updateTotalUnread', this.totalUnread);
  883. uni.showToast({
  884. title: '删除成功',
  885. icon: 'success'
  886. });
  887. } catch (e) {
  888. console.error('删除会话失败', e);
  889. uni.showToast({
  890. title: '删除失败',
  891. icon: 'none'
  892. });
  893. }
  894. }
  895. }
  896. });
  897. this.closeActionMenu();
  898. },
  899. /**
  900. * 搜索(实时过滤在computed中实现)
  901. */
  902. onSearch() {
  903. console.log('搜索:', this.searchKeyword);
  904. // filteredConversations computed属性会自动过滤
  905. },
  906. /**
  907. * 取消搜索
  908. */
  909. cancelSearch() {
  910. this.showSearchPanel = false;
  911. this.searchKeyword = '';
  912. },
  913. /**
  914. * 处理滑动
  915. */
  916. handleSwipe(e, conv) {
  917. if (e.detail.x < -50) {
  918. this.swipingConvId = conv.id;
  919. } else if (e.detail.x > -10) {
  920. this.swipingConvId = null;
  921. }
  922. },
  923. /**
  924. * 滑动结束
  925. */
  926. handleSwipeEnd(conv) {
  927. // 如果滑动距离不够,自动回弹
  928. setTimeout(() => {
  929. if (this.swipingConvId === conv.id) {
  930. // 保持显示操作按钮
  931. }
  932. }, 100);
  933. },
  934. /**
  935. * 切换置顶状态
  936. */
  937. togglePin(conv) {
  938. conv.isPinned = conv.isPinned ? 0 : 1;
  939. // 保存到本地存储
  940. this.savePinnedConversations();
  941. // 重置滑动状态
  942. this.swipingConvId = null;
  943. uni.showToast({
  944. title: conv.isPinned ? '已置顶' : '已取消置顶',
  945. icon: 'success'
  946. });
  947. },
  948. /**
  949. * 加载置顶会话列表
  950. */
  951. loadPinnedConversations() {
  952. try {
  953. const pinned = uni.getStorageSync('pinnedConversations_' + this.userId);
  954. if (pinned) {
  955. this.pinnedConversations = JSON.parse(pinned);
  956. }
  957. } catch (e) {
  958. console.error('加载置顶列表失败:', e);
  959. }
  960. },
  961. /**
  962. * 保存置顶会话列表
  963. */
  964. savePinnedConversations() {
  965. try {
  966. const pinnedIds = this.conversations
  967. .filter(conv => conv.isPinned)
  968. .map(conv => conv.id);
  969. uni.setStorageSync('pinnedConversations_' + this.userId, JSON.stringify(pinnedIds));
  970. } catch (e) {
  971. console.error('保存置顶列表失败:', e);
  972. }
  973. },
  974. /**
  975. * 确认删除会话
  976. */
  977. confirmDeleteConversation(conv) {
  978. uni.showModal({
  979. title: '确认删除',
  980. content: '确定要删除该会话吗?',
  981. success: (res) => {
  982. if (res.confirm) {
  983. this.deleteConversationItem(conv);
  984. }
  985. }
  986. });
  987. // 重置滑动状态
  988. this.swipingConvId = null;
  989. },
  990. /**
  991. * 删除会话
  992. */
  993. async deleteConversationItem(conv) {
  994. try {
  995. // 调用 TIM SDK 删除会话
  996. await timManager.tim.deleteConversation(conv.id);
  997. // 从列表中移除
  998. const index = this.conversations.findIndex(c => c.id === conv.id);
  999. if (index > -1) {
  1000. this.conversations.splice(index, 1);
  1001. }
  1002. // 重新计算总未读数(包含所有会话+系统消息)
  1003. const allUnreadCount = this.conversations.reduce((total, c) => total + c.unreadCount, 0);
  1004. this.totalUnread = allUnreadCount + this.systemUnread;
  1005. // 同步到Vuex
  1006. this.$store.dispatch('updateTotalUnread', this.totalUnread);
  1007. uni.showToast({
  1008. title: '删除成功',
  1009. icon: 'success'
  1010. });
  1011. } catch (e) {
  1012. console.error('删除会话失败', e);
  1013. uni.showToast({
  1014. title: '删除失败',
  1015. icon: 'none'
  1016. });
  1017. }
  1018. },
  1019. /**
  1020. * 格式化最后一条消息
  1021. */
  1022. formatLastMessage(conv) {
  1023. if (!conv.lastMessage) {
  1024. return '暂无消息';
  1025. }
  1026. // 限制长度
  1027. const maxLen = 30;
  1028. if (conv.lastMessage.length > maxLen) {
  1029. return conv.lastMessage.substring(0, maxLen) + '...';
  1030. }
  1031. return conv.lastMessage;
  1032. },
  1033. /**
  1034. * 格式化时间
  1035. */
  1036. formatTime(time) {
  1037. if (!time) return '';
  1038. const date = new Date(time);
  1039. const now = new Date();
  1040. const diff = now - date;
  1041. // 今天
  1042. if (date.toDateString() === now.toDateString()) {
  1043. return date.toLocaleTimeString('zh-CN', {
  1044. hour: '2-digit',
  1045. minute: '2-digit'
  1046. });
  1047. }
  1048. // 昨天
  1049. const yesterday = new Date(now);
  1050. yesterday.setDate(yesterday.getDate() - 1);
  1051. if (date.toDateString() === yesterday.toDateString()) {
  1052. return '昨天';
  1053. }
  1054. // 本周
  1055. if (diff < 7 * 24 * 60 * 60 * 1000) {
  1056. const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  1057. return days[date.getDay()];
  1058. }
  1059. // 更早
  1060. return date.toLocaleDateString('zh-CN', {
  1061. month: '2-digit',
  1062. day: '2-digit'
  1063. });
  1064. },
  1065. /**
  1066. * 初始化在线状态监听(WebSocket 实时推送 + HTTP 轮询)
  1067. */
  1068. async initOnlineStatusListener() {
  1069. console.log('🔄 初始化在线状态监听(WebSocket + HTTP)');
  1070. const timPresenceManager = require('@/utils/tim-presence-manager.js').default;
  1071. // 1. 立即查询一次
  1072. await this.refreshOnlineStatus();
  1073. // 2. 为每个会话用户注册 WebSocket 监听
  1074. this.conversations.forEach(conv => {
  1075. const callback = (status) => {
  1076. console.log(`⚡ 实时收到用户 ${conv.targetUserId} 状态变更: ${status}`);
  1077. // 更新会话列表中的在线状态
  1078. const conversation = this.conversations.find(c => c.targetUserId === conv.targetUserId);
  1079. if (conversation) {
  1080. this.$set(conversation, 'isOnline', status === 'online');
  1081. }
  1082. };
  1083. // 保存回调引用
  1084. conv.onlineStatusCallback = callback;
  1085. // 注册监听
  1086. timPresenceManager.onStatusChange(conv.targetUserId, callback);
  1087. });
  1088. // 3. 启动 HTTP 轮询作为补充(30秒间隔)
  1089. this.onlineStatusTimer = setInterval(() => {
  1090. this.refreshOnlineStatus();
  1091. }, 30000);
  1092. console.log('✅ 在线状态监听已启动(WebSocket 实时 + HTTP 轮询)');
  1093. },
  1094. /**
  1095. * 刷新在线状态(HTTP 查询方式)
  1096. */
  1097. async refreshOnlineStatus() {
  1098. console.log('🔄 刷新在线状态(HTTP 查询)');
  1099. // 批量查询所有会话用户的在线状态
  1100. for (const conv of this.conversations) {
  1101. try {
  1102. const [err, res] = await uni.request({
  1103. url: 'http://localhost:8083/api/online/checkStatus',
  1104. method: 'GET',
  1105. data: {
  1106. userId: conv.targetUserId
  1107. }
  1108. });
  1109. if (!err && res.data && res.data.code === 200) {
  1110. this.$set(conv, 'isOnline', res.data.data.online || false);
  1111. }
  1112. } catch (error) {
  1113. console.error(`❌ 查询用户 ${conv.targetUserId} 在线状态失败:`, error);
  1114. }
  1115. }
  1116. console.log('✅ 在线状态刷新完成');
  1117. },
  1118. /**
  1119. * 清理已删除用户的TIM数据
  1120. * @param {Array} deletedUserIds 已删除的用户ID列表
  1121. */
  1122. async cleanupDeletedUsers(deletedUserIds) {
  1123. try {
  1124. console.log('🗑️ 开始清理已删除用户的TIM数据:', deletedUserIds);
  1125. let successCount = 0;
  1126. let failCount = 0;
  1127. for (const userId of deletedUserIds) {
  1128. try {
  1129. // 1. 删除TIM会话
  1130. const conversationID = `C2C${userId}`;
  1131. await timManager.tim.deleteConversation(conversationID);
  1132. console.log(`✅ 已删除会话: ${conversationID}`);
  1133. // 2. 删除TIM好友关系
  1134. await timManager.tim.deleteFriend({
  1135. userIDList: [String(userId)],
  1136. type: timManager.tim.TYPES.SNS_DELETE_TYPE_BOTH // 双向删除
  1137. });
  1138. console.log(`✅ 已删除好友: ${userId}`);
  1139. // 3. 从本地会话列表中移除
  1140. const index = this.conversations.findIndex(conv => conv.targetUserId === userId);
  1141. if (index > -1) {
  1142. this.conversations.splice(index, 1);
  1143. console.log(`✅ 已从本地列表移除: ${userId}`);
  1144. }
  1145. successCount++;
  1146. } catch (error) {
  1147. console.error(`❌ 清理用户 ${userId} 失败:`, error);
  1148. failCount++;
  1149. }
  1150. }
  1151. // 重新计算总未读数
  1152. const allUnreadCount = this.conversations.reduce((total, conv) => total + conv.unreadCount, 0);
  1153. this.totalUnread = allUnreadCount + this.systemUnread;
  1154. this.$store.dispatch('updateTotalUnread', this.totalUnread);
  1155. console.log(`✅ TIM数据清理完成: 成功${successCount}个, 失败${failCount}个`);
  1156. // 显示提示
  1157. if (successCount > 0) {
  1158. uni.showToast({
  1159. title: `已清理${successCount}个无效会话`,
  1160. icon: 'success',
  1161. duration: 2000
  1162. });
  1163. }
  1164. } catch (error) {
  1165. console.error('❌ 清理TIM数据失败:', error);
  1166. }
  1167. },
  1168. /**
  1169. * 切换标签页
  1170. */
  1171. switchTab(tab) {
  1172. if (tab === 'message') return;
  1173. const tabPages = {
  1174. index: '/pages/index/index',
  1175. plaza: '/pages/plaza/index',
  1176. recommend: '/pages/recommend/index',
  1177. mine: '/pages/mine/index'
  1178. };
  1179. if (tabPages[tab]) {
  1180. uni.redirectTo({
  1181. url: tabPages[tab]
  1182. });
  1183. }
  1184. }
  1185. }
  1186. };
  1187. </script>
  1188. <style lang="scss" scoped>
  1189. .message-page {
  1190. min-height: 100vh;
  1191. background-color: #F5F5F5;
  1192. padding-bottom: 120rpx;
  1193. }
  1194. /* 顶部标题栏 */
  1195. .header {
  1196. display: flex;
  1197. align-items: center;
  1198. justify-content: space-between;
  1199. padding: 30rpx;
  1200. background-color: #FFFFFF;
  1201. border-bottom: 1rpx solid #F0F0F0;
  1202. .header-title {
  1203. font-size: 40rpx;
  1204. font-weight: bold;
  1205. color: #E91E63;
  1206. }
  1207. .header-actions {
  1208. display: flex;
  1209. gap: 30rpx;
  1210. .action-icon {
  1211. font-size: 40rpx;
  1212. cursor: pointer;
  1213. }
  1214. }
  1215. }
  1216. /* 搜索面板 */
  1217. .search-panel {
  1218. background-color: #FFFFFF;
  1219. padding: 20rpx 30rpx;
  1220. border-bottom: 1rpx solid #F0F0F0;
  1221. .search-bar {
  1222. display: flex;
  1223. align-items: center;
  1224. gap: 20rpx;
  1225. .search-input {
  1226. flex: 1;
  1227. height: 70rpx;
  1228. padding: 0 20rpx;
  1229. background-color: #F5F5F5;
  1230. border-radius: 35rpx;
  1231. font-size: 28rpx;
  1232. }
  1233. .search-cancel {
  1234. font-size: 28rpx;
  1235. color: #E91E63;
  1236. }
  1237. }
  1238. }
  1239. /* 会话列表 */
  1240. .conversation-list {
  1241. height: calc(100vh - 200rpx);
  1242. background-color: #FFFFFF;
  1243. }
  1244. /* 骨架屏 */
  1245. .skeleton-container {
  1246. padding: 20rpx 0;
  1247. }
  1248. .skeleton-item {
  1249. display: flex;
  1250. align-items: center;
  1251. padding: 25rpx 30rpx;
  1252. background-color: #FFFFFF;
  1253. border-bottom: 1rpx solid #F5F5F5;
  1254. .skeleton-avatar {
  1255. width: 100rpx;
  1256. height: 100rpx;
  1257. border-radius: 12rpx;
  1258. background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  1259. background-size: 200% 100%;
  1260. animation: skeleton-loading 1.5s ease-in-out infinite;
  1261. margin-right: 25rpx;
  1262. }
  1263. .skeleton-content {
  1264. flex: 1;
  1265. .skeleton-line {
  1266. height: 30rpx;
  1267. border-radius: 6rpx;
  1268. background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  1269. background-size: 200% 100%;
  1270. animation: skeleton-loading 1.5s ease-in-out infinite;
  1271. &.skeleton-line-title {
  1272. width: 40%;
  1273. margin-bottom: 20rpx;
  1274. }
  1275. &.skeleton-line-text {
  1276. width: 60%;
  1277. }
  1278. }
  1279. }
  1280. }
  1281. @keyframes skeleton-loading {
  1282. 0% {
  1283. background-position: 200% 0;
  1284. }
  1285. 100% {
  1286. background-position: -200% 0;
  1287. }
  1288. }
  1289. /* 空状态 */
  1290. .empty-container {
  1291. display: flex;
  1292. flex-direction: column;
  1293. align-items: center;
  1294. justify-content: center;
  1295. padding: 150rpx 60rpx;
  1296. .empty-icon-wrapper {
  1297. width: 200rpx;
  1298. height: 200rpx;
  1299. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  1300. border-radius: 50%;
  1301. display: flex;
  1302. align-items: center;
  1303. justify-content: center;
  1304. margin-bottom: 40rpx;
  1305. box-shadow: 0 20rpx 60rpx rgba(102, 126, 234, 0.3);
  1306. animation: float 3s ease-in-out infinite;
  1307. }
  1308. .empty-icon {
  1309. font-size: 100rpx;
  1310. filter: brightness(1.2);
  1311. }
  1312. .empty-text {
  1313. font-size: 36rpx;
  1314. font-weight: 600;
  1315. color: #333333;
  1316. margin-bottom: 15rpx;
  1317. }
  1318. .empty-hint {
  1319. font-size: 28rpx;
  1320. color: #999999;
  1321. margin-bottom: 40rpx;
  1322. }
  1323. .empty-action {
  1324. margin-top: 20rpx;
  1325. .empty-btn {
  1326. padding: 20rpx 60rpx;
  1327. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  1328. color: #FFFFFF;
  1329. border-radius: 50rpx;
  1330. font-size: 28rpx;
  1331. border: none;
  1332. box-shadow: 0 10rpx 30rpx rgba(102, 126, 234, 0.3);
  1333. &::after {
  1334. border: none;
  1335. }
  1336. }
  1337. }
  1338. }
  1339. @keyframes float {
  1340. 0%, 100% {
  1341. transform: translateY(0);
  1342. }
  1343. 50% {
  1344. transform: translateY(-20rpx);
  1345. }
  1346. }
  1347. /* 会话列表项包装器 */
  1348. .conversation-item-wrapper {
  1349. position: relative;
  1350. background-color: #FFFFFF;
  1351. border-bottom: 1rpx solid #F5F5F5;
  1352. overflow: hidden;
  1353. }
  1354. /* 系统消息高亮样式 */
  1355. .system-highlight { background: #fff7f7; }
  1356. .system-icon { font-size: 44rpx; color: #E91E63; }
  1357. .system-title { color: #E91E63; font-weight: 600; }
  1358. .system-preview { color: #d25d6b; }
  1359. .system-tag { font-size: 22rpx; color: #fff; background-color: #E91E63; padding: 4rpx 10rpx; border-radius: 8rpx; }
  1360. /* 滑动区域 */
  1361. .movable-area {
  1362. width: 100%;
  1363. height: 160rpx;
  1364. position: relative;
  1365. }
  1366. .movable-view {
  1367. width: 100%;
  1368. height: 100%;
  1369. background-color: #FFFFFF;
  1370. }
  1371. /* 会话列表项 */
  1372. .conversation-item {
  1373. display: flex;
  1374. align-items: center;
  1375. padding: 25rpx 30rpx;
  1376. background-color: #FFFFFF;
  1377. position: relative;
  1378. width: 94%;
  1379. height: 100%;
  1380. &:active {
  1381. background-color: #F8F8F8;
  1382. }
  1383. /* 置顶标记 */
  1384. .pinned-badge {
  1385. position: absolute;
  1386. top: 10rpx;
  1387. left: 10rpx;
  1388. font-size: 28rpx;
  1389. opacity: 0.7;
  1390. }
  1391. .avatar-wrapper {
  1392. position: relative;
  1393. margin-right: 25rpx;
  1394. .avatar {
  1395. width: 100rpx;
  1396. height: 100rpx;
  1397. border-radius: 12rpx;
  1398. }
  1399. .online-badge {
  1400. position: absolute;
  1401. bottom: 2rpx;
  1402. right: 2rpx;
  1403. width: 26rpx;
  1404. height: 26rpx;
  1405. background-color: #07C160;
  1406. border: 4rpx solid #FFFFFF;
  1407. border-radius: 50%;
  1408. box-shadow: 0 0 8rpx rgba(7, 193, 96, 0.5);
  1409. z-index: 10;
  1410. }
  1411. .unread-badge {
  1412. position: absolute;
  1413. top: -10rpx;
  1414. right: -10rpx;
  1415. min-width: 36rpx;
  1416. height: 36rpx;
  1417. line-height: 36rpx;
  1418. padding: 0 8rpx;
  1419. background-color: #FA5151;
  1420. border-radius: 18rpx;
  1421. font-size: 20rpx;
  1422. color: #FFFFFF;
  1423. text-align: center;
  1424. }
  1425. }
  1426. .conversation-content {
  1427. flex: 1;
  1428. .content-top {
  1429. display: flex;
  1430. align-items: center;
  1431. justify-content: space-between;
  1432. margin-bottom: 12rpx;
  1433. .user-name {
  1434. font-size: 32rpx;
  1435. font-weight: 500;
  1436. color: #333333;
  1437. }
  1438. .last-time {
  1439. font-size: 24rpx;
  1440. color: #999999;
  1441. }
  1442. }
  1443. .content-bottom {
  1444. display: flex;
  1445. align-items: center;
  1446. gap: 10rpx;
  1447. .last-message {
  1448. flex: 1;
  1449. font-size: 28rpx;
  1450. color: #999999;
  1451. overflow: hidden;
  1452. text-overflow: ellipsis;
  1453. white-space: nowrap;
  1454. &.unread {
  1455. color: #666666;
  1456. font-weight: 500;
  1457. }
  1458. }
  1459. .message-type-icon {
  1460. font-size: 28rpx;
  1461. }
  1462. }
  1463. }
  1464. /* 右滑操作按钮 */
  1465. .conversation-actions {
  1466. position: absolute;
  1467. right: 0;
  1468. top: 0;
  1469. height: 100%;
  1470. display: flex;
  1471. z-index: 1;
  1472. .action-btn {
  1473. width: 150rpx;
  1474. height: 100%;
  1475. display: flex;
  1476. align-items: center;
  1477. justify-content: center;
  1478. color: #FFFFFF;
  1479. font-size: 28rpx;
  1480. }
  1481. .pin-btn {
  1482. background-color: #576B95;
  1483. }
  1484. .delete-btn {
  1485. background-color: #FA5151;
  1486. }
  1487. }
  1488. }
  1489. .load-more {
  1490. padding: 30rpx;
  1491. text-align: center;
  1492. .load-more-text {
  1493. font-size: 26rpx;
  1494. color: #999999;
  1495. }
  1496. }
  1497. /* 底部导航栏 */
  1498. .tabbar {
  1499. position: fixed;
  1500. bottom: 0;
  1501. left: 0;
  1502. right: 0;
  1503. display: flex;
  1504. background-color: #FFFFFF;
  1505. border-top: 1rpx solid #F0F0F0;
  1506. padding-bottom: constant(safe-area-inset-bottom);
  1507. padding-bottom: env(safe-area-inset-bottom);
  1508. z-index: 999;
  1509. .tabbar-item {
  1510. flex: 1;
  1511. display: flex;
  1512. flex-direction: column;
  1513. align-items: center;
  1514. justify-content: center;
  1515. padding: 15rpx 0;
  1516. position: relative;
  1517. .tabbar-icon {
  1518. font-size: 44rpx;
  1519. margin-bottom: 5rpx;
  1520. }
  1521. .tabbar-text {
  1522. font-size: 22rpx;
  1523. color: #666666;
  1524. }
  1525. .tab-badge {
  1526. position: absolute;
  1527. top: 8rpx;
  1528. right: 50%;
  1529. margin-right: -40rpx;
  1530. min-width: 32rpx;
  1531. height: 32rpx;
  1532. line-height: 32rpx;
  1533. padding: 0 6rpx;
  1534. background-color: #FA5151;
  1535. border-radius: 16rpx;
  1536. font-size: 20rpx;
  1537. color: #FFFFFF;
  1538. text-align: center;
  1539. }
  1540. &.active {
  1541. .tabbar-text {
  1542. color: #E91E63;
  1543. font-weight: bold;
  1544. }
  1545. }
  1546. }
  1547. }
  1548. /* 操作菜单 */
  1549. .action-menu {
  1550. background-color: #FFFFFF;
  1551. border-radius: 20rpx 20rpx 0 0;
  1552. .menu-item {
  1553. padding: 30rpx;
  1554. text-align: center;
  1555. font-size: 32rpx;
  1556. color: #333333;
  1557. border-bottom: 1rpx solid #F0F0F0;
  1558. &:active {
  1559. background-color: #F8F8F8;
  1560. }
  1561. &.cancel {
  1562. color: #999999;
  1563. border: none;
  1564. margin-top: 20rpx;
  1565. }
  1566. }
  1567. }
  1568. </style>