index.vue 51 KB

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