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. const timPresenceManager = require('@/utils/tim-presence-manager.js').default;
  351. const userIdList = [];
  352. this.conversations.forEach(conv => {
  353. if (conv.onlineStatusCallback) {
  354. timPresenceManager.offStatusChange(conv.targetUserId, conv.onlineStatusCallback);
  355. userIdList.push(conv.targetUserId);
  356. }
  357. });
  358. // 取消订阅用户状态
  359. if (userIdList.length > 0) {
  360. timPresenceManager.unsubscribeUserStatus(userIdList).catch(err => {
  361. console.error('❌ 取消订阅失败:', err);
  362. });
  363. }
  364. },
  365. methods: {
  366. /**
  367. * 处理拉黑列表更新事件
  368. */
  369. async handleBlacklistUpdate() {
  370. console.log('🔄 检测到拉黑列表更新,开始刷新会话列表');
  371. // 重置拉黑列表加载状态
  372. this.blacklistLoaded = false;
  373. // 重新加载拉黑列表
  374. await this.loadBlacklist();
  375. // 重新加载系统消息未读
  376. await this.loadSystemUnread();
  377. // 重新加载会话列表(会自动过滤拉黑用户)
  378. this.loadConversations();
  379. // 显示提示
  380. uni.showToast({
  381. title: '已更新会话列表',
  382. icon: 'success',
  383. duration: 1500
  384. });
  385. },
  386. /**
  387. * 初始化腾讯云IM
  388. */
  389. async initTIM() {
  390. try {
  391. console.log('📱 初始化腾讯云IM...');
  392. console.log('📱 当前用户ID:', this.userId);
  393. // 如果未初始化,先初始化
  394. if (!timManager.tim) {
  395. timManager.init(1600109674); // SDKAppID
  396. console.log('✅ TIM SDK 实例已创建');
  397. }
  398. // 检查是否已登录,以及登录的用户是否匹配
  399. if (timManager.isLogin && timManager.userId) {
  400. // 如果已登录但用户ID不匹配,先登出
  401. if (String(timManager.userId) !== String(this.userId)) {
  402. console.warn('⚠️ 检测到用户切换,从', timManager.userId, '到', this.userId);
  403. console.log('⚠️ 执行登出操作...');
  404. await timManager.logout();
  405. } else {
  406. console.log('✅ TIM 已登录,用户ID匹配:', this.userId);
  407. this.timInitialized = true;
  408. // 直接加载会话列表
  409. this.loadConversations();
  410. return;
  411. }
  412. }
  413. // 执行登录流程
  414. console.log('🔐 开始登录流程,用户ID:', this.userId);
  415. // 先导入用户到腾讯云IM
  416. await this.importUser();
  417. // 获取 UserSig 并登录
  418. const userSig = await this.getUserSig();
  419. console.log('🔑 获取到 UserSig');
  420. // 登录到 TIM
  421. await timManager.login(this.userId, userSig);
  422. console.log('✅ TIM 登录成功,用户ID:', this.userId);
  423. // 监听会话列表更新
  424. timManager.tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, (event) => {
  425. console.log('📋 会话列表更新事件触发');
  426. console.log('📋 当前登录用户:', this.userId);
  427. this.loadConversations();
  428. });
  429. this.timInitialized = true;
  430. console.log('✅ TIM 初始化完成');
  431. // 加载会话列表
  432. this.loadConversations();
  433. } catch (error) {
  434. console.error('❌ TIM 初始化失败:', error);
  435. console.error('❌ 错误详情:', error.message || error);
  436. uni.showToast({
  437. title: '初始化失败: ' + (error.message || '请重试'),
  438. icon: 'none',
  439. duration: 3000
  440. });
  441. }
  442. },
  443. /**
  444. * 导入用户到腾讯云IM
  445. */
  446. async importUser() {
  447. try {
  448. await uni.request({
  449. url: 'http://localhost:8083/api/im/importUser',
  450. method: 'POST',
  451. data: {
  452. userId: String(this.userId)
  453. }
  454. });
  455. console.log('✅ 用户导入成功');
  456. } catch (error) {
  457. console.log('⚠️ 用户导入失败(可能已存在):', error);
  458. // 导入失败不影响登录
  459. }
  460. },
  461. /**
  462. * 获取 UserSig
  463. */
  464. async getUserSig() {
  465. try {
  466. const res = await uni.request({
  467. url: `http://localhost:8083/api/im/getUserSig?userId=${this.userId}`,
  468. method: 'GET'
  469. });
  470. if (res[1].data.code === 200) {
  471. return res[1].data.data.userSig;
  472. } else {
  473. throw new Error(res[1].data.message);
  474. }
  475. } catch (error) {
  476. console.error('❌ 获取 UserSig 失败:', error);
  477. throw error;
  478. }
  479. },
  480. /**
  481. * 加载会话列表(从腾讯云IM)
  482. */
  483. async loadConversations() {
  484. if (this.loading || !this.timInitialized) {
  485. console.log('⏸️ 跳过加载会话列表:', this.loading ? '正在加载中' : 'TIM未初始化');
  486. return;
  487. }
  488. // 确保先加载拉黑列表
  489. if (!this.blacklistLoaded) {
  490. await this.loadBlacklist();
  491. }
  492. // 验证登录状态
  493. if (!timManager.isLogin || !timManager.userId) {
  494. console.error('❌ TIM 未登录或用户ID为空');
  495. return;
  496. }
  497. // 验证用户ID是否匹配
  498. if (String(timManager.userId) !== String(this.userId)) {
  499. console.error('❌ 用户ID不匹配!TIM:', timManager.userId, '页面:', this.userId);
  500. console.log('🔄 自动切换用户,重新登录TIM...');
  501. // 自动重新初始化TIM(会自动登出旧用户并登录新用户)
  502. this.timInitialized = false;
  503. try {
  504. await this.initTIM();
  505. // 初始化完成后会自动调用loadConversations
  506. } catch (error) {
  507. console.error('❌ 重新初始化TIM失败:', error);
  508. uni.showModal({
  509. title: '切换用户失败',
  510. content: '请重新登录',
  511. showCancel: false,
  512. success: () => {
  513. uni.reLaunch({
  514. url: '/pages/page3/page3'
  515. });
  516. }
  517. });
  518. }
  519. return;
  520. }
  521. this.loading = true;
  522. console.log('🔄 开始加载会话列表,用户ID:', this.userId);
  523. try {
  524. // 从腾讯云IM获取会话列表(仅当前登录用户的会话)
  525. const conversationList = await timManager.getConversationList();
  526. console.log('📋 从TIM获取到会话数:', conversationList.length);
  527. // 转换为UI需要的格式
  528. let formattedConversations = conversationList.map(conv => {
  529. const formatted = this.formatConversation(conv);
  530. // 验证会话是否属于当前用户
  531. if (formatted.userId !== this.userId) {
  532. console.warn('⚠️ 发现不属于当前用户的会话:', formatted);
  533. }
  534. return formatted;
  535. });
  536. // 过滤掉不属于当前用户的会话(双重保险)
  537. formattedConversations = formattedConversations.filter(conv => conv.userId === this.userId);
  538. // 先计算所有会话的未读数(包括拉黑用户)
  539. const allUnreadCount = formattedConversations.reduce((total, conv) => total + conv.unreadCount, 0);
  540. // 过滤掉拉黑用户的会话 🌟
  541. formattedConversations = formattedConversations.filter(conv => {
  542. return !this.blacklistUsers.includes(conv.targetUserId.toString());
  543. });
  544. this.conversations = formattedConversations;
  545. // 批量获取用户头像信息
  546. await this.loadUserAvatars();
  547. // 计算总未读数(包括所有会话的未读 + 系统消息未读)
  548. this.totalUnread = allUnreadCount + this.systemUnread;
  549. // 同步到Vuex
  550. this.$store.dispatch('updateTotalUnread', this.totalUnread);
  551. console.log('✅ 会话列表加载成功');
  552. console.log(' - 当前用户ID:', this.userId);
  553. console.log(' - 会话数量:', this.conversations.length);
  554. console.log(' - 拉黑用户数:', this.blacklistUsers.length);
  555. console.log(' - 会话未读数:', allUnreadCount);
  556. console.log(' - 系统消息未读数:', this.systemUnread);
  557. console.log(' - 总未读数:', this.totalUnread);
  558. // 输出前3个会话的详细信息(调试用)
  559. if (this.conversations.length > 0) {
  560. console.log('📋 会话预览(前3个):');
  561. this.conversations.slice(0, 3).forEach((conv, idx) => {
  562. console.log(` ${idx + 1}. ${conv.targetUserName} (ID:${conv.targetUserId}) 头像: ${conv.targetUserAvatar}, 未读: ${conv.unreadCount}`);
  563. });
  564. }
  565. if (this.blacklistUsers.length > 0) {
  566. console.log('🚫 已过滤拉黑用户:', this.blacklistUsers);
  567. }
  568. } catch (e) {
  569. console.error('❌ 加载会话列表失败:', e);
  570. console.error('❌ 错误详情:', e.message || e);
  571. uni.showToast({
  572. title: '加载失败: ' + (e.message || '请重试'),
  573. icon: 'none',
  574. duration: 2000
  575. });
  576. } finally {
  577. this.loading = false;
  578. this.refreshing = false;
  579. }
  580. },
  581. /**
  582. * 获取拉黑用户列表
  583. */
  584. async loadBlacklist() {
  585. try {
  586. console.log('🔄 加载拉黑用户列表,用户ID:', this.userId);
  587. const res = await uni.request({
  588. url: 'http://localhost:8083/api/chatfriend/getBlacklist', // 替换为你的后端接口
  589. method: 'GET',
  590. data: {
  591. userId: this.userId
  592. }
  593. });
  594. if (res[1].statusCode === 200 && res[1].data.code === 200) {
  595. // 假设返回格式: {data: [{targetUserId: 'xxx'}, ...]}
  596. const blacklistData = res[1].data.data || [];
  597. this.blacklistUsers = blacklistData.map(item => {
  598. // 确保用户ID为字符串格式,避免类型不一致问题
  599. return String(item.targetUserId || item.userId || item.id);
  600. });
  601. console.log('✅ 拉黑列表加载成功,共', this.blacklistUsers.length, '个拉黑用户:', this.blacklistUsers);
  602. } else {
  603. console.warn('⚠️ 拉黑列表接口返回异常:', res[1].data);
  604. }
  605. } catch (error) {
  606. console.error('❌ 加载拉黑列表失败:', error);
  607. // 加载失败不影响会话列表显示,只记录错误
  608. } finally {
  609. this.blacklistLoaded = true; // 标记为已加载,避免重复请求
  610. }
  611. },
  612. /**
  613. * 批量获取用户头像信息
  614. */
  615. async loadUserAvatars() {
  616. try {
  617. if (this.conversations.length === 0) {
  618. return;
  619. }
  620. // 收集所有需要获取头像的用户ID
  621. const userIds = this.conversations
  622. .map(conv => conv.targetUserId)
  623. .filter(id => id) // 过滤掉空值
  624. .join(',');
  625. if (!userIds) {
  626. console.log('⚠️ 没有需要获取头像的用户');
  627. return;
  628. }
  629. console.log('🔄 开始批量获取用户头像,用户ID列表:', userIds);
  630. // 调用批量获取用户信息接口
  631. const res = await uni.request({
  632. url: 'http://localhost:8083/api/user/batch',
  633. method: 'GET',
  634. data: {
  635. userIds: userIds
  636. }
  637. });
  638. if (res[1].statusCode === 200 && res[1].data.code === 200) {
  639. const userList = res[1].data.data || [];
  640. console.log('✅ 批量获取用户信息成功,数量:', userList.length);
  641. // 创建用户ID到用户信息的映射
  642. const userMap = {};
  643. userList.forEach(user => {
  644. userMap[user.userId] = user;
  645. });
  646. // 收集数据库中不存在的用户ID
  647. const deletedUserIds = [];
  648. // 更新会话列表中的头像和昵称
  649. for (const conv of this.conversations) {
  650. const userInfo = userMap[conv.targetUserId];
  651. if (userInfo) {
  652. // 更新头像(如果数据库中有头像)
  653. if (userInfo.avatarUrl) {
  654. conv.targetUserAvatar = userInfo.avatarUrl;
  655. }
  656. // 更新昵称(如果数据库中的昵称更准确)
  657. if (userInfo.nickname && userInfo.nickname !== `用户${conv.targetUserId}`) {
  658. conv.targetUserName = userInfo.nickname;
  659. }
  660. console.log(`🖼️ 更新用户 ${conv.targetUserId} 的信息:`, {
  661. 昵称: conv.targetUserName,
  662. 头像: conv.targetUserAvatar
  663. });
  664. } else {
  665. // 数据库中不存在该用户,标记为需要删除
  666. console.warn(`⚠️ 用户 ${conv.targetUserId} 在数据库中不存在`);
  667. deletedUserIds.push(conv.targetUserId);
  668. }
  669. }
  670. // 如果有不存在的用户,删除TIM中的会话和好友
  671. if (deletedUserIds.length > 0) {
  672. console.log(`🗑️ 发现 ${deletedUserIds.length} 个不存在的用户,开始清理TIM数据...`);
  673. await this.cleanupDeletedUsers(deletedUserIds);
  674. }
  675. } else {
  676. console.error('❌ 批量获取用户信息失败:', res[1].data);
  677. }
  678. } catch (error) {
  679. console.error('❌ 批量获取用户头像失败:', error);
  680. // 头像获取失败不影响会话列表显示,只记录错误
  681. }
  682. },
  683. /**
  684. * 格式化会话数据
  685. * 将TIM的会话格式转换为UI需要的格式
  686. */
  687. formatConversation(timConv) {
  688. // conversationID 格式: C2C{userId}
  689. const targetUserId = timConv.conversationID.replace('C2C', '');
  690. // 检查是否在本地置顶列表中
  691. const isPinned = this.pinnedConversations.includes(timConv.conversationID) ? 1 : 0;
  692. return {
  693. id: timConv.conversationID,
  694. userId: this.userId,
  695. targetUserId: targetUserId,
  696. targetUserName: timConv.userProfile?.nick || `用户${targetUserId}`,
  697. targetUserAvatar: timConv.userProfile?.avatar || '',
  698. lastMessage: this.getLastMessageText(timConv.lastMessage),
  699. lastMessageType: this.getMessageType(timConv.lastMessage),
  700. lastMessageTime: timConv.lastMessage?.lastTime ? timConv.lastMessage.lastTime * 1000 : Date.now(),
  701. unreadCount: timConv.unreadCount || 0,
  702. isOnline: false,
  703. isPinned: isPinned
  704. };
  705. },
  706. /**
  707. * 获取最后一条消息的文本
  708. */
  709. getLastMessageText(message) {
  710. if (!message) return '暂无消息';
  711. switch (message.type) {
  712. case 'TIMTextElem':
  713. return message.payload?.text || '';
  714. case 'TIMImageElem':
  715. return '[图片]';
  716. case 'TIMSoundElem':
  717. return '[语音]';
  718. case 'TIMVideoFileElem':
  719. return '[视频]';
  720. case 'TIMFileElem':
  721. return '[文件]';
  722. case 'TIMCustomElem':
  723. // 处理自定义消息(我们的语音消息)
  724. try {
  725. const customData = JSON.parse(message.payload.data);
  726. if (customData.type === 'voice') {
  727. return '[语音]';
  728. }
  729. } catch (e) {
  730. console.error('解析自定义消息失败:', e);
  731. }
  732. return '[自定义消息]';
  733. default:
  734. return '[未知消息]';
  735. }
  736. },
  737. /**
  738. * 获取消息类型
  739. */
  740. getMessageType(message) {
  741. if (!message) return 1;
  742. const typeMap = {
  743. 'TIMTextElem': 1, // 文本
  744. 'TIMImageElem': 2, // 图片
  745. 'TIMSoundElem': 3, // 语音
  746. 'TIMVideoFileElem': 4 // 视频
  747. };
  748. return typeMap[message.type] || 1;
  749. },
  750. /**
  751. * 下拉刷新
  752. */
  753. onRefresh() {
  754. this.refreshing = true;
  755. this.loadConversations();
  756. },
  757. /**
  758. * 加载更多(TIM一次性返回所有会话,不需要分页)
  759. */
  760. loadMore() {
  761. // TIM SDK 一次性返回所有会话,不需要分页加载
  762. },
  763. /**
  764. * 加载系统消息未读
  765. */
  766. async loadSystemUnread() {
  767. try {
  768. const userId = this.userId;
  769. const res = await this.$api?.message?.getSystemUnreadCount ? this.$api.message.getSystemUnreadCount(userId) : null;
  770. if (res && (res.code === 200 || res.code === 0)) {
  771. this.systemUnread = res.data || 0;
  772. } else {
  773. // 直接调用工具方法
  774. const api = require('@/utils/api.js').default;
  775. const r = await api.message.getSystemUnreadCount(userId);
  776. this.systemUnread = r.data || 0;
  777. }
  778. // 预览最新一条
  779. const api2 = require('@/utils/api.js').default;
  780. const listRes = await api2.message.getSystemList(userId, 1, 1);
  781. const list = listRes.data?.list || listRes.data || [];
  782. if (list.length > 0) {
  783. this.systemLatestTime = list[0].createdAt || list[0].created_at;
  784. this.systemLatestPreview = list[0].title || '系统通知';
  785. }
  786. // 更新总未读数
  787. const allUnreadCount = this.conversations.reduce((total, conv) => total + conv.unreadCount, 0);
  788. this.totalUnread = allUnreadCount + this.systemUnread;
  789. // 同步到Vuex
  790. this.$store.dispatch('updateTotalUnread', this.totalUnread);
  791. } catch (e) {
  792. console.log('加载系统未读失败', e);
  793. }
  794. },
  795. openSystemMessages() {
  796. uni.navigateTo({ url: '/pages/message/system' });
  797. },
  798. /**
  799. * 刷新会话列表
  800. */
  801. refreshConversations() {
  802. if (this.timInitialized) {
  803. // 先刷新系统消息未读
  804. this.loadSystemUnread();
  805. // 再刷新会话列表
  806. this.loadConversations();
  807. }
  808. },
  809. /**
  810. * 打开聊天页面
  811. */
  812. openChat(conversation) {
  813. uni.navigateTo({
  814. url: `/pages/message/chat?targetUserId=${conversation.targetUserId}&targetUserName=${conversation.targetUserName}&targetUserAvatar=${conversation.targetUserAvatar || ''}`
  815. });
  816. },
  817. /**
  818. * 显示操作菜单
  819. */
  820. showActionMenu(conversation) {
  821. this.selectedConversation = conversation;
  822. this.$refs.actionMenu.open();
  823. },
  824. /**
  825. * 关闭操作菜单
  826. */
  827. closeActionMenu() {
  828. this.$refs.actionMenu.close();
  829. this.selectedConversation = null;
  830. },
  831. /**
  832. * 标记为已读
  833. */
  834. async markAsRead() {
  835. if (!this.selectedConversation) {
  836. return;
  837. }
  838. try {
  839. // 调用 TIM SDK 标记已读
  840. await timManager.setMessageRead(this.selectedConversation.id);
  841. // 更新本地显示
  842. this.selectedConversation.unreadCount = 0;
  843. // 重新计算总未读数(包含所有会话+系统消息)
  844. const allUnreadCount = this.conversations.reduce((total, conv) => total + conv.unreadCount, 0);
  845. this.totalUnread = allUnreadCount + this.systemUnread;
  846. // 同步到Vuex
  847. this.$store.dispatch('updateTotalUnread', this.totalUnread);
  848. uni.showToast({
  849. title: '已标记为已读',
  850. icon: 'success'
  851. });
  852. } catch (e) {
  853. console.error('标记已读失败', e);
  854. }
  855. this.closeActionMenu();
  856. },
  857. /**
  858. * 删除会话
  859. */
  860. async deleteCurrentConversation() {
  861. if (!this.selectedConversation) {
  862. return;
  863. }
  864. uni.showModal({
  865. title: '确认删除',
  866. content: '确定要删除该会话吗?',
  867. success: async (res) => {
  868. if (res.confirm) {
  869. try {
  870. // 调用 TIM SDK 删除会话
  871. await timManager.tim.deleteConversation(this.selectedConversation.id);
  872. // 从列表中移除
  873. const index = this.conversations.findIndex(c => c.id === this.selectedConversation.id);
  874. if (index > -1) {
  875. this.conversations.splice(index, 1);
  876. }
  877. // 重新计算总未读数(包含所有会话+系统消息)
  878. const allUnreadCount = this.conversations.reduce((total, conv) => total + conv.unreadCount, 0);
  879. this.totalUnread = allUnreadCount + this.systemUnread;
  880. // 同步到Vuex
  881. this.$store.dispatch('updateTotalUnread', this.totalUnread);
  882. uni.showToast({
  883. title: '删除成功',
  884. icon: 'success'
  885. });
  886. } catch (e) {
  887. console.error('删除会话失败', e);
  888. uni.showToast({
  889. title: '删除失败',
  890. icon: 'none'
  891. });
  892. }
  893. }
  894. }
  895. });
  896. this.closeActionMenu();
  897. },
  898. /**
  899. * 搜索(实时过滤在computed中实现)
  900. */
  901. onSearch() {
  902. console.log('搜索:', this.searchKeyword);
  903. // filteredConversations computed属性会自动过滤
  904. },
  905. /**
  906. * 取消搜索
  907. */
  908. cancelSearch() {
  909. this.showSearchPanel = false;
  910. this.searchKeyword = '';
  911. },
  912. /**
  913. * 处理滑动
  914. */
  915. handleSwipe(e, conv) {
  916. if (e.detail.x < -50) {
  917. this.swipingConvId = conv.id;
  918. } else if (e.detail.x > -10) {
  919. this.swipingConvId = null;
  920. }
  921. },
  922. /**
  923. * 滑动结束
  924. */
  925. handleSwipeEnd(conv) {
  926. // 如果滑动距离不够,自动回弹
  927. setTimeout(() => {
  928. if (this.swipingConvId === conv.id) {
  929. // 保持显示操作按钮
  930. }
  931. }, 100);
  932. },
  933. /**
  934. * 切换置顶状态
  935. */
  936. togglePin(conv) {
  937. conv.isPinned = conv.isPinned ? 0 : 1;
  938. // 保存到本地存储
  939. this.savePinnedConversations();
  940. // 重置滑动状态
  941. this.swipingConvId = null;
  942. uni.showToast({
  943. title: conv.isPinned ? '已置顶' : '已取消置顶',
  944. icon: 'success'
  945. });
  946. },
  947. /**
  948. * 加载置顶会话列表
  949. */
  950. loadPinnedConversations() {
  951. try {
  952. const pinned = uni.getStorageSync('pinnedConversations_' + this.userId);
  953. if (pinned) {
  954. this.pinnedConversations = JSON.parse(pinned);
  955. }
  956. } catch (e) {
  957. console.error('加载置顶列表失败:', e);
  958. }
  959. },
  960. /**
  961. * 保存置顶会话列表
  962. */
  963. savePinnedConversations() {
  964. try {
  965. const pinnedIds = this.conversations
  966. .filter(conv => conv.isPinned)
  967. .map(conv => conv.id);
  968. uni.setStorageSync('pinnedConversations_' + this.userId, JSON.stringify(pinnedIds));
  969. } catch (e) {
  970. console.error('保存置顶列表失败:', e);
  971. }
  972. },
  973. /**
  974. * 确认删除会话
  975. */
  976. confirmDeleteConversation(conv) {
  977. uni.showModal({
  978. title: '确认删除',
  979. content: '确定要删除该会话吗?',
  980. success: (res) => {
  981. if (res.confirm) {
  982. this.deleteConversationItem(conv);
  983. }
  984. }
  985. });
  986. // 重置滑动状态
  987. this.swipingConvId = null;
  988. },
  989. /**
  990. * 删除会话
  991. */
  992. async deleteConversationItem(conv) {
  993. try {
  994. // 调用 TIM SDK 删除会话
  995. await timManager.tim.deleteConversation(conv.id);
  996. // 从列表中移除
  997. const index = this.conversations.findIndex(c => c.id === conv.id);
  998. if (index > -1) {
  999. this.conversations.splice(index, 1);
  1000. }
  1001. // 重新计算总未读数(包含所有会话+系统消息)
  1002. const allUnreadCount = this.conversations.reduce((total, c) => total + c.unreadCount, 0);
  1003. this.totalUnread = allUnreadCount + this.systemUnread;
  1004. // 同步到Vuex
  1005. this.$store.dispatch('updateTotalUnread', this.totalUnread);
  1006. uni.showToast({
  1007. title: '删除成功',
  1008. icon: 'success'
  1009. });
  1010. } catch (e) {
  1011. console.error('删除会话失败', e);
  1012. uni.showToast({
  1013. title: '删除失败',
  1014. icon: 'none'
  1015. });
  1016. }
  1017. },
  1018. /**
  1019. * 格式化最后一条消息
  1020. */
  1021. formatLastMessage(conv) {
  1022. if (!conv.lastMessage) {
  1023. return '暂无消息';
  1024. }
  1025. // 限制长度
  1026. const maxLen = 30;
  1027. if (conv.lastMessage.length > maxLen) {
  1028. return conv.lastMessage.substring(0, maxLen) + '...';
  1029. }
  1030. return conv.lastMessage;
  1031. },
  1032. /**
  1033. * 格式化时间
  1034. */
  1035. formatTime(time) {
  1036. if (!time) return '';
  1037. const date = new Date(time);
  1038. const now = new Date();
  1039. const diff = now - date;
  1040. // 今天
  1041. if (date.toDateString() === now.toDateString()) {
  1042. return date.toLocaleTimeString('zh-CN', {
  1043. hour: '2-digit',
  1044. minute: '2-digit'
  1045. });
  1046. }
  1047. // 昨天
  1048. const yesterday = new Date(now);
  1049. yesterday.setDate(yesterday.getDate() - 1);
  1050. if (date.toDateString() === yesterday.toDateString()) {
  1051. return '昨天';
  1052. }
  1053. // 本周
  1054. if (diff < 7 * 24 * 60 * 60 * 1000) {
  1055. const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  1056. return days[date.getDay()];
  1057. }
  1058. // 更早
  1059. return date.toLocaleDateString('zh-CN', {
  1060. month: '2-digit',
  1061. day: '2-digit'
  1062. });
  1063. },
  1064. /**
  1065. * 初始化在线状态监听
  1066. */
  1067. async initOnlineStatusListener() {
  1068. console.log('👂 初始化在线状态监听');
  1069. const timPresenceManager = require('@/utils/tim-presence-manager.js').default;
  1070. // 收集所有需要订阅的用户ID
  1071. const userIdList = this.conversations.map(conv => conv.targetUserId).filter(id => id);
  1072. if (userIdList.length === 0) {
  1073. console.log('⚠️ 没有需要订阅的用户');
  1074. return;
  1075. }
  1076. // 使用 TIM 原生能力订阅用户状态
  1077. try {
  1078. await timPresenceManager.subscribeUserStatus(userIdList);
  1079. console.log('✅ 已订阅用户状态:', userIdList);
  1080. } catch (error) {
  1081. console.error('❌ 订阅用户状态失败:', error);
  1082. }
  1083. // 监听所有用户的在线状态变化
  1084. this.conversations.forEach(conv => {
  1085. // 创建回调并保存引用
  1086. const callback = (status) => {
  1087. console.log(`👤 用户 ${conv.targetUserId} 状态变更: ${status}`);
  1088. // 更新会话列表中的在线状态
  1089. const conversation = this.conversations.find(c => c.targetUserId === conv.targetUserId);
  1090. if (conversation) {
  1091. this.$set(conversation, 'isOnline', status === 'online');
  1092. }
  1093. };
  1094. // 保存回调引用以便后续清理
  1095. conv.onlineStatusCallback = callback;
  1096. // 注册监听
  1097. timPresenceManager.onStatusChange(conv.targetUserId, callback);
  1098. // 获取缓存的状态并初始化
  1099. const cachedStatus = timPresenceManager.getCachedStatus(conv.targetUserId);
  1100. if (cachedStatus !== null) {
  1101. this.$set(conv, 'isOnline', cachedStatus);
  1102. }
  1103. });
  1104. },
  1105. /**
  1106. * 刷新在线状态
  1107. */
  1108. async refreshOnlineStatus() {
  1109. console.log('🔄 刷新在线状态');
  1110. const timPresenceManager = require('@/utils/tim-presence-manager.js').default;
  1111. // 从缓存中获取在线状态
  1112. this.conversations.forEach(conv => {
  1113. const cachedStatus = timPresenceManager.getCachedStatus(conv.targetUserId);
  1114. if (cachedStatus !== null) {
  1115. this.$set(conv, 'isOnline', cachedStatus);
  1116. }
  1117. });
  1118. console.log('✅ 在线状态刷新完成');
  1119. },
  1120. /**
  1121. * 清理已删除用户的TIM数据
  1122. * @param {Array} deletedUserIds 已删除的用户ID列表
  1123. */
  1124. async cleanupDeletedUsers(deletedUserIds) {
  1125. try {
  1126. console.log('🗑️ 开始清理已删除用户的TIM数据:', deletedUserIds);
  1127. let successCount = 0;
  1128. let failCount = 0;
  1129. for (const userId of deletedUserIds) {
  1130. try {
  1131. // 1. 删除TIM会话
  1132. const conversationID = `C2C${userId}`;
  1133. await timManager.tim.deleteConversation(conversationID);
  1134. console.log(`✅ 已删除会话: ${conversationID}`);
  1135. // 2. 删除TIM好友关系
  1136. await timManager.tim.deleteFriend({
  1137. userIDList: [String(userId)],
  1138. type: timManager.tim.TYPES.SNS_DELETE_TYPE_BOTH // 双向删除
  1139. });
  1140. console.log(`✅ 已删除好友: ${userId}`);
  1141. // 3. 从本地会话列表中移除
  1142. const index = this.conversations.findIndex(conv => conv.targetUserId === userId);
  1143. if (index > -1) {
  1144. this.conversations.splice(index, 1);
  1145. console.log(`✅ 已从本地列表移除: ${userId}`);
  1146. }
  1147. successCount++;
  1148. } catch (error) {
  1149. console.error(`❌ 清理用户 ${userId} 失败:`, error);
  1150. failCount++;
  1151. }
  1152. }
  1153. // 重新计算总未读数
  1154. const allUnreadCount = this.conversations.reduce((total, conv) => total + conv.unreadCount, 0);
  1155. this.totalUnread = allUnreadCount + this.systemUnread;
  1156. this.$store.dispatch('updateTotalUnread', this.totalUnread);
  1157. console.log(`✅ TIM数据清理完成: 成功${successCount}个, 失败${failCount}个`);
  1158. // 显示提示
  1159. if (successCount > 0) {
  1160. uni.showToast({
  1161. title: `已清理${successCount}个无效会话`,
  1162. icon: 'success',
  1163. duration: 2000
  1164. });
  1165. }
  1166. } catch (error) {
  1167. console.error('❌ 清理TIM数据失败:', error);
  1168. }
  1169. },
  1170. /**
  1171. * 切换标签页
  1172. */
  1173. switchTab(tab) {
  1174. if (tab === 'message') return;
  1175. const tabPages = {
  1176. index: '/pages/index/index',
  1177. plaza: '/pages/plaza/index',
  1178. recommend: '/pages/recommend/index',
  1179. mine: '/pages/mine/index'
  1180. };
  1181. if (tabPages[tab]) {
  1182. uni.redirectTo({
  1183. url: tabPages[tab]
  1184. });
  1185. }
  1186. }
  1187. }
  1188. };
  1189. </script>
  1190. <style lang="scss" scoped>
  1191. .message-page {
  1192. min-height: 100vh;
  1193. background-color: #F5F5F5;
  1194. padding-bottom: 120rpx;
  1195. }
  1196. /* 顶部标题栏 */
  1197. .header {
  1198. display: flex;
  1199. align-items: center;
  1200. justify-content: space-between;
  1201. padding: 30rpx;
  1202. background-color: #FFFFFF;
  1203. border-bottom: 1rpx solid #F0F0F0;
  1204. .header-title {
  1205. font-size: 40rpx;
  1206. font-weight: bold;
  1207. color: #E91E63;
  1208. }
  1209. .header-actions {
  1210. display: flex;
  1211. gap: 30rpx;
  1212. .action-icon {
  1213. font-size: 40rpx;
  1214. cursor: pointer;
  1215. }
  1216. }
  1217. }
  1218. /* 搜索面板 */
  1219. .search-panel {
  1220. background-color: #FFFFFF;
  1221. padding: 20rpx 30rpx;
  1222. border-bottom: 1rpx solid #F0F0F0;
  1223. .search-bar {
  1224. display: flex;
  1225. align-items: center;
  1226. gap: 20rpx;
  1227. .search-input {
  1228. flex: 1;
  1229. height: 70rpx;
  1230. padding: 0 20rpx;
  1231. background-color: #F5F5F5;
  1232. border-radius: 35rpx;
  1233. font-size: 28rpx;
  1234. }
  1235. .search-cancel {
  1236. font-size: 28rpx;
  1237. color: #E91E63;
  1238. }
  1239. }
  1240. }
  1241. /* 会话列表 */
  1242. .conversation-list {
  1243. height: calc(100vh - 200rpx);
  1244. background-color: #FFFFFF;
  1245. }
  1246. /* 骨架屏 */
  1247. .skeleton-container {
  1248. padding: 20rpx 0;
  1249. }
  1250. .skeleton-item {
  1251. display: flex;
  1252. align-items: center;
  1253. padding: 25rpx 30rpx;
  1254. background-color: #FFFFFF;
  1255. border-bottom: 1rpx solid #F5F5F5;
  1256. .skeleton-avatar {
  1257. width: 100rpx;
  1258. height: 100rpx;
  1259. border-radius: 12rpx;
  1260. background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  1261. background-size: 200% 100%;
  1262. animation: skeleton-loading 1.5s ease-in-out infinite;
  1263. margin-right: 25rpx;
  1264. }
  1265. .skeleton-content {
  1266. flex: 1;
  1267. .skeleton-line {
  1268. height: 30rpx;
  1269. border-radius: 6rpx;
  1270. background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  1271. background-size: 200% 100%;
  1272. animation: skeleton-loading 1.5s ease-in-out infinite;
  1273. &.skeleton-line-title {
  1274. width: 40%;
  1275. margin-bottom: 20rpx;
  1276. }
  1277. &.skeleton-line-text {
  1278. width: 60%;
  1279. }
  1280. }
  1281. }
  1282. }
  1283. @keyframes skeleton-loading {
  1284. 0% {
  1285. background-position: 200% 0;
  1286. }
  1287. 100% {
  1288. background-position: -200% 0;
  1289. }
  1290. }
  1291. /* 空状态 */
  1292. .empty-container {
  1293. display: flex;
  1294. flex-direction: column;
  1295. align-items: center;
  1296. justify-content: center;
  1297. padding: 150rpx 60rpx;
  1298. .empty-icon-wrapper {
  1299. width: 200rpx;
  1300. height: 200rpx;
  1301. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  1302. border-radius: 50%;
  1303. display: flex;
  1304. align-items: center;
  1305. justify-content: center;
  1306. margin-bottom: 40rpx;
  1307. box-shadow: 0 20rpx 60rpx rgba(102, 126, 234, 0.3);
  1308. animation: float 3s ease-in-out infinite;
  1309. }
  1310. .empty-icon {
  1311. font-size: 100rpx;
  1312. filter: brightness(1.2);
  1313. }
  1314. .empty-text {
  1315. font-size: 36rpx;
  1316. font-weight: 600;
  1317. color: #333333;
  1318. margin-bottom: 15rpx;
  1319. }
  1320. .empty-hint {
  1321. font-size: 28rpx;
  1322. color: #999999;
  1323. margin-bottom: 40rpx;
  1324. }
  1325. .empty-action {
  1326. margin-top: 20rpx;
  1327. .empty-btn {
  1328. padding: 20rpx 60rpx;
  1329. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  1330. color: #FFFFFF;
  1331. border-radius: 50rpx;
  1332. font-size: 28rpx;
  1333. border: none;
  1334. box-shadow: 0 10rpx 30rpx rgba(102, 126, 234, 0.3);
  1335. &::after {
  1336. border: none;
  1337. }
  1338. }
  1339. }
  1340. }
  1341. @keyframes float {
  1342. 0%, 100% {
  1343. transform: translateY(0);
  1344. }
  1345. 50% {
  1346. transform: translateY(-20rpx);
  1347. }
  1348. }
  1349. /* 会话列表项包装器 */
  1350. .conversation-item-wrapper {
  1351. position: relative;
  1352. background-color: #FFFFFF;
  1353. border-bottom: 1rpx solid #F5F5F5;
  1354. overflow: hidden;
  1355. }
  1356. /* 系统消息高亮样式 */
  1357. .system-highlight { background: #fff7f7; }
  1358. .system-icon { font-size: 44rpx; color: #E91E63; }
  1359. .system-title { color: #E91E63; font-weight: 600; }
  1360. .system-preview { color: #d25d6b; }
  1361. .system-tag { font-size: 22rpx; color: #fff; background-color: #E91E63; padding: 4rpx 10rpx; border-radius: 8rpx; }
  1362. /* 滑动区域 */
  1363. .movable-area {
  1364. width: 100%;
  1365. height: 160rpx;
  1366. position: relative;
  1367. }
  1368. .movable-view {
  1369. width: 100%;
  1370. height: 100%;
  1371. background-color: #FFFFFF;
  1372. }
  1373. /* 会话列表项 */
  1374. .conversation-item {
  1375. display: flex;
  1376. align-items: center;
  1377. padding: 25rpx 30rpx;
  1378. background-color: #FFFFFF;
  1379. position: relative;
  1380. width: 94%;
  1381. height: 100%;
  1382. &:active {
  1383. background-color: #F8F8F8;
  1384. }
  1385. /* 置顶标记 */
  1386. .pinned-badge {
  1387. position: absolute;
  1388. top: 10rpx;
  1389. left: 10rpx;
  1390. font-size: 28rpx;
  1391. opacity: 0.7;
  1392. }
  1393. .avatar-wrapper {
  1394. position: relative;
  1395. margin-right: 25rpx;
  1396. .avatar {
  1397. width: 100rpx;
  1398. height: 100rpx;
  1399. border-radius: 12rpx;
  1400. }
  1401. .online-badge {
  1402. position: absolute;
  1403. bottom: 0;
  1404. right: 0;
  1405. width: 24rpx;
  1406. height: 24rpx;
  1407. background-color: #07C160;
  1408. border: 3rpx solid #FFFFFF;
  1409. border-radius: 50%;
  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>