index.vue 52 KB

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