| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529 |
- <template>
- <view class="message-page">
- <!-- 顶部标题栏 -->
- <view class="header">
- <text class="header-title">💬 消息</text>
- <view class="header-actions">
- <text class="action-icon" @click="showSearchPanel = true">🔍</text>
- </view>
- </view>
- <!-- 搜索面板 -->
- <view v-if="showSearchPanel" class="search-panel">
- <view class="search-bar">
- <input
- class="search-input"
- v-model="searchKeyword"
- placeholder="搜索好友或消息内容"
- @input="onSearch" />
- <text class="search-cancel" @click="cancelSearch">取消</text>
- </view>
- </view>
- <!-- 会话列表 -->
- <scroll-view
- class="conversation-list"
- scroll-y
- refresher-enabled
- :refresher-triggered="refreshing"
- @refresherrefresh="onRefresh"
- @scrolltolower="loadMore">
-
- <!-- 骨架屏加载状态 -->
- <view v-if="loading && conversations.length === 0" class="skeleton-container">
- <view v-for="i in 6" :key="i" class="skeleton-item">
- <view class="skeleton-avatar"></view>
- <view class="skeleton-content">
- <view class="skeleton-line skeleton-line-title"></view>
- <view class="skeleton-line skeleton-line-text"></view>
- </view>
- </view>
- </view>
- <!-- 空状态(初次/无搜索) -->
- <view v-if="conversations.length === 0 && !loading && !searchKeyword" class="empty-container">
- <view class="empty-icon-wrapper">
- <text class="empty-icon">💬</text>
- </view>
- <text class="empty-text">暂无消息</text>
- <text class="empty-hint">开始和心仪的TA聊天吧~</text>
- <view class="empty-action">
- <button class="empty-btn" @click="switchTab('recommend')">去推荐页面</button>
- </view>
- </view>
- <!-- 系统消息作为第一条会话项展示(整合到同列表,突出样式) -->
- <view v-else-if="!searchKeyword" class="conversation-item-wrapper system-highlight" @click="openSystemMessages">
- <view class="conversation-item">
- <view class="avatar-wrapper">
- <text class="system-icon">📢</text>
- <view v-if="systemUnread > 0" class="unread-badge">{{ systemUnread > 99 ? '99+' : systemUnread }}</view>
- </view>
- <view class="conversation-content">
- <view class="content-top">
- <text class="user-name system-title">系统通知</text>
- <text class="last-time">{{ systemLatestTime ? formatTime(systemLatestTime) : '' }}</text>
- </view>
- <view class="content-bottom">
- <text class="last-message system-preview">{{ systemLatestPreview || '平台公告及处理通知' }}</text>
- <text class="system-tag"></text>
- </view>
- </view>
- </view>
- </view>
-
- <!-- 搜索无结果 -->
- <view v-else-if="searchKeyword && filteredConversations.length === 0" class="empty-container">
- <view class="empty-icon-wrapper">
- <text class="empty-icon">🔍</text>
- </view>
- <text class="empty-text">没有找到相关内容</text>
- <text class="empty-hint">试试搜索其他关键词</text>
- </view>
- <!-- 会话列表项(带滑动) -->
- <view
- v-for="conv in filteredConversations"
- :key="conv.id"
- class="conversation-item-wrapper">
-
- <movable-area class="movable-area">
- <movable-view
- class="movable-view"
- direction="horizontal"
- :x="conv.id === swipingConvId ? -150 : 0"
- @change="handleSwipe($event, conv)"
- @touchend="handleSwipeEnd(conv)">
-
- <view class="conversation-item" @click="openChat(conv)" @longpress="showActionMenu(conv)">
- <!-- 置顶标记 -->
- <view v-if="conv.isPinned" class="pinned-badge">📌</view>
-
- <!-- 头像 -->
- <view class="avatar-wrapper">
- <image
- class="avatar"
- :src="conv.targetUserAvatar || '/static/default-avatar.svg'"
- mode="aspectFill"
- lazy-load />
- <view v-if="conv.isOnline" class="online-badge"></view>
- <view v-if="conv.unreadCount > 0" class="unread-badge">
- {{ conv.unreadCount > 99 ? '99+' : conv.unreadCount }}
- </view>
- </view>
- <!-- 会话内容 -->
- <view class="conversation-content">
- <view class="content-top">
- <text class="user-name">{{ conv.targetUserName }}</text>
- <text class="last-time">{{formatTime(conv.lastMessageTime) }}</text>
- </view>
- <view class="content-bottom">
- <text class="last-message" :class="{ unread: conv.unreadCount > 0 }">
- {{ formatLastMessage(conv) }}
- </text>
- <text v-if="conv.lastMessageType === 1" class="message-type-icon">📝</text>
- <text v-else-if="conv.lastMessageType === 2" class="message-type-icon">🖼️</text>
- <text v-else-if="conv.lastMessageType === 3" class="message-type-icon">🎤</text>
- <text v-else-if="conv.lastMessageType === 4" class="message-type-icon">📹</text>
- </view>
- </view>
- </view>
- </movable-view>
-
- <!-- 右滑操作按钮 -->
- <view class="conversation-actions">
- <view class="action-btn pin-btn" @click.stop="togglePin(conv)">
- {{ conv.isPinned ? '取消' : '置顶' }}
- </view>
- <view class="action-btn delete-btn" @click.stop="confirmDeleteConversation(conv)">
- 删除
- </view>
- </view>
- </movable-area>
- </view>
- <!-- 加载更多 -->
- <view v-if="hasMore && conversations.length > 0" class="load-more">
- <text class="load-more-text">{{ loading ? '加载中...' : '上拉加载更多' }}</text>
- </view>
- <view v-else-if="!hasMore && conversations.length > 0" class="load-more">
- <text class="load-more-text">没有更多了</text>
- </view>
- </scroll-view>
- <!-- 底部导航栏 -->
- <view class="tabbar">
- <view class="tabbar-item" @click="switchTab('index')">
- <text class="tabbar-icon">🏠</text>
- <text class="tabbar-text">首页</text>
- </view>
- <view class="tabbar-item" @click="switchTab('plaza')">
- <text class="tabbar-icon">💕</text>
- <text class="tabbar-text">广场</text>
- </view>
- <view class="tabbar-item" @click="switchTab('recommend')">
- <text class="tabbar-icon">👍</text>
- <text class="tabbar-text">推荐</text>
- </view>
- <view class="tabbar-item active">
- <text class="tabbar-icon">💬</text>
- <text class="tabbar-text">消息</text>
- <view v-if="totalUnread > 0" class="tab-badge">
- {{ totalUnread > 99 ? '99+' : totalUnread }}
- </view>
- </view>
- <view class="tabbar-item" @click="switchTab('mine')">
- <text class="tabbar-icon">👤</text>
- <text class="tabbar-text">我的</text>
- </view>
- </view>
- <!-- 操作菜单 -->
- <uni-popup ref="actionMenu" type="bottom">
- <view class="action-menu">
- <view class="menu-item" @click="markAsRead">标为已读</view>
- <view class="menu-item" @click="deleteCurrentConversation">删除会话</view>
- <view class="menu-item cancel" @click="closeActionMenu">取消</view>
- </view>
- </uni-popup>
- </view>
- </template>
- <script>
- import { getConversations, getUnreadCount, deleteConversation, checkOnlineStatus } from '@/utils/chat-api.js';
- import wsManager from '@/utils/websocket.js';
- import timManager from '@/utils/tim-manager.js';
- import TIM from 'tim-wx-sdk';
- export default {
- data() {
- return {
- userId: null,
- conversations: [],
- loading: false,
- refreshing: false,
- hasMore: false, // TIM 一次性返回所有会话,不分页
- currentPage: 1,
- pageSize: 20,
-
- totalUnread: 0,
- showSearchPanel: false,
- searchKeyword: '',
-
- selectedConversation: null,
- onlineCheckTimer: null,
- timInitialized: false,
-
- // 滑动相关
- swipingConvId: null,
-
- // 置顶会话列表(本地存储)
- pinnedConversations: []
- , systemUnread: 0
- , systemLatestTime: null
- , systemLatestPreview: ''
- };
- },
-
- computed: {
- // 过滤和排序会话列表
- filteredConversations() {
- let list = [...this.conversations];
-
- // 搜索过滤
- if (this.searchKeyword) {
- list = list.filter(conv => {
- return conv.targetUserName.includes(this.searchKeyword) ||
- conv.lastMessage.includes(this.searchKeyword);
- });
- }
-
- // 按置顶和时间排序
- list.sort((a, b) => {
- // 置顶优先
- if (a.isPinned && !b.isPinned) return -1;
- if (!a.isPinned && b.isPinned) return 1;
-
- // 时间倒序
- return new Date(b.lastMessageTime) - new Date(a.lastMessageTime);
- });
-
- return list;
- }
- },
-
- onLoad() {
- // 获取登录凭证
- const token = uni.getStorageSync('token');
- const userInfo = uni.getStorageSync('userInfo');
- const storedUserId = uni.getStorageSync('userId');
-
- console.log('=== 消息页面登录状态检查 ===');
- console.log('token:', token ? '存在' : '不存在');
- console.log('userInfo:', userInfo);
- console.log('storedUserId:', storedUserId);
-
- // 严格验证登录状态
- if (!token || !userInfo) {
- console.error('❌ 未登录或登录信息不完整');
- uni.showModal({
- title: '需要登录',
- content: '请先登录后再查看消息',
- showCancel: false,
- success: () => {
- uni.reLaunch({
- url: '/pages/page3/page3'
- });
- }
- });
- return;
- }
-
- // 优先使用 storage 中的 userId,确保一致性
- this.userId = storedUserId || userInfo.userId || userInfo.id || userInfo.user_id;
-
- // 转换为数字类型(如果是字符串)
- if (typeof this.userId === 'string') {
- this.userId = parseInt(this.userId);
- }
-
- // 最终验证 userId
- if (!this.userId || isNaN(this.userId)) {
- console.error('❌ 无法获取有效的用户ID');
- console.error('userInfo:', JSON.stringify(userInfo));
- console.error('storedUserId:', storedUserId);
- uni.showModal({
- title: '用户信息错误',
- content: '无法获取用户ID,请重新登录',
- showCancel: false,
- success: () => {
- // 清除错误的登录信息
- uni.removeStorageSync('token');
- uni.removeStorageSync('userInfo');
- uni.removeStorageSync('userId');
- uni.reLaunch({
- url: '/pages/page3/page3'
- });
- }
- });
- return;
- }
-
- console.log('✅ 当前登录用户ID:', this.userId, '(类型:', typeof this.userId, ')');
-
- // 确保 userId 同步到 storage(以防不一致)
- if (storedUserId !== this.userId) {
- console.log('⚠️ 同步 userId 到 storage');
- uni.setStorageSync('userId', this.userId);
- }
-
- // 加载置顶会话列表(基于当前用户ID)
- this.loadPinnedConversations();
-
- // 初始化腾讯云IM(确保使用正确的用户ID登录)
- this.initTIM();
- // 拉取系统消息未读
- this.loadSystemUnread();
-
- // 监听刷新事件(从聊天页面返回时触发)
- uni.$on('refreshConversations', this.refreshConversations);
- },
-
- onShow() {
- console.log('=== 消息页面显示 ===');
-
- // 重新验证登录状态
- const token = uni.getStorageSync('token');
- const storedUserId = uni.getStorageSync('userId');
-
- console.log('onShow - 检查登录状态:');
- console.log(' - token:', token ? '存在' : '不存在');
- console.log(' - storedUserId:', storedUserId);
- console.log(' - this.userId:', this.userId);
-
- // 如果未登录,跳转登录页
- if (!token || !storedUserId) {
- console.warn('⚠️ 未登录,跳转登录页');
- uni.reLaunch({
- url: '/pages/page3/page3'
- });
- return;
- }
-
- // 如果用户ID改变,更新页面userId并重新初始化TIM
- if (storedUserId !== this.userId) {
- console.warn('⚠️ 用户ID改变,从', this.userId, '到', storedUserId);
- console.log('🔄 更新页面userId并重新初始化TIM...');
-
- this.userId = storedUserId;
- this.timInitialized = false;
-
- // 重新初始化TIM
- this.initTIM().catch(error => {
- console.error('❌ 重新初始化TIM失败:', error);
- uni.showToast({
- title: '初始化失败',
- icon: 'none'
- });
- });
- return;
- }
-
- console.log('✅ 登录状态正常,用户ID:', this.userId);
-
- // 页面显示时刷新会话列表
- this.refreshConversations();
- this.loadSystemUnread();
- },
-
- onUnload() {
- // 清除定时器
- if (this.onlineCheckTimer) {
- clearInterval(this.onlineCheckTimer);
- }
-
- // 移除事件监听
- uni.$off('refreshConversations', this.refreshConversations);
- },
-
- methods: {
- /**
- * 初始化腾讯云IM
- */
- async initTIM() {
- try {
- console.log('📱 初始化腾讯云IM...');
- console.log('📱 当前用户ID:', this.userId);
-
- // 如果未初始化,先初始化
- if (!timManager.tim) {
- timManager.init(1600109674); // SDKAppID
- console.log('✅ TIM SDK 实例已创建');
- }
-
- // 检查是否已登录,以及登录的用户是否匹配
- if (timManager.isLogin && timManager.userId) {
- // 如果已登录但用户ID不匹配,先登出
- if (String(timManager.userId) !== String(this.userId)) {
- console.warn('⚠️ 检测到用户切换,从', timManager.userId, '到', this.userId);
- console.log('⚠️ 执行登出操作...');
- await timManager.logout();
- } else {
- console.log('✅ TIM 已登录,用户ID匹配:', this.userId);
- this.timInitialized = true;
- // 直接加载会话列表
- this.loadConversations();
- return;
- }
- }
-
- // 执行登录流程
- console.log('🔐 开始登录流程,用户ID:', this.userId);
-
- // 先导入用户到腾讯云IM
- await this.importUser();
-
- // 获取 UserSig 并登录
- const userSig = await this.getUserSig();
- console.log('🔑 获取到 UserSig');
-
- // 登录到 TIM
- await timManager.login(this.userId, userSig);
- console.log('✅ TIM 登录成功,用户ID:', this.userId);
-
- // 监听会话列表更新
- timManager.tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, (event) => {
- console.log('📋 会话列表更新事件触发');
- console.log('📋 当前登录用户:', this.userId);
- this.loadConversations();
- });
-
- this.timInitialized = true;
- console.log('✅ TIM 初始化完成');
-
- // 加载会话列表
- this.loadConversations();
-
- } catch (error) {
- console.error('❌ TIM 初始化失败:', error);
- console.error('❌ 错误详情:', error.message || error);
- uni.showToast({
- title: '初始化失败: ' + (error.message || '请重试'),
- icon: 'none',
- duration: 3000
- });
- }
- },
-
- /**
- * 导入用户到腾讯云IM
- */
- async importUser() {
- try {
- await uni.request({
- url: 'http://localhost:1004/api/im/importUser',
- method: 'POST',
- data: {
- userId: String(this.userId)
- }
- });
- console.log('✅ 用户导入成功');
- } catch (error) {
- console.log('⚠️ 用户导入失败(可能已存在):', error);
- // 导入失败不影响登录
- }
- },
-
- /**
- * 获取 UserSig
- */
- async getUserSig() {
- try {
- const res = await uni.request({
- url: `http://localhost:1004/api/im/getUserSig?userId=${this.userId}`,
- method: 'GET'
- });
-
- if (res[1].data.code === 200) {
- return res[1].data.data.userSig;
- } else {
- throw new Error(res[1].data.message);
- }
- } catch (error) {
- console.error('❌ 获取 UserSig 失败:', error);
- throw error;
- }
- },
-
- /**
- * 加载会话列表(从腾讯云IM)
- */
- async loadConversations() {
- if (this.loading || !this.timInitialized) {
- console.log('⏸️ 跳过加载会话列表:', this.loading ? '正在加载中' : 'TIM未初始化');
- return;
- }
-
- // 验证登录状态
- if (!timManager.isLogin || !timManager.userId) {
- console.error('❌ TIM 未登录或用户ID为空');
- return;
- }
-
- // 验证用户ID是否匹配
- if (String(timManager.userId) !== String(this.userId)) {
- console.error('❌ 用户ID不匹配!TIM:', timManager.userId, '页面:', this.userId);
- console.log('🔄 自动切换用户,重新登录TIM...');
-
- // 自动重新初始化TIM(会自动登出旧用户并登录新用户)
- this.timInitialized = false;
- try {
- await this.initTIM();
- // 初始化完成后会自动调用loadConversations
- } catch (error) {
- console.error('❌ 重新初始化TIM失败:', error);
- uni.showModal({
- title: '切换用户失败',
- content: '请重新登录',
- showCancel: false,
- success: () => {
- uni.reLaunch({
- url: '/pages/page3/page3'
- });
- }
- });
- }
- return;
- }
-
- this.loading = true;
- console.log('🔄 开始加载会话列表,用户ID:', this.userId);
-
- try {
- // 从腾讯云IM获取会话列表(仅当前登录用户的会话)
- const conversationList = await timManager.getConversationList();
- console.log('📋 从TIM获取到会话数:', conversationList.length);
-
- // 转换为UI需要的格式
- this.conversations = conversationList.map(conv => {
- const formatted = this.formatConversation(conv);
- // 验证会话是否属于当前用户
- if (formatted.userId !== this.userId) {
- console.warn('⚠️ 发现不属于当前用户的会话:', formatted);
- }
- return formatted;
- });
-
- // 过滤掉不属于当前用户的会话(双重保险)
- this.conversations = this.conversations.filter(conv => conv.userId === this.userId);
-
- // 批量获取用户头像信息
- await this.loadUserAvatars();
-
- // 计算总未读数
- this.totalUnread = this.conversations.reduce((total, conv) => total + conv.unreadCount, 0);
-
- console.log('✅ 会话列表加载成功');
- console.log(' - 当前用户ID:', this.userId);
- console.log(' - 会话数量:', this.conversations.length);
- console.log(' - 总未读数:', this.totalUnread);
-
- // 输出前3个会话的详细信息(调试用)
- if (this.conversations.length > 0) {
- console.log('📋 会话预览(前3个):');
- this.conversations.slice(0, 3).forEach((conv, idx) => {
- console.log(` ${idx + 1}. ${conv.targetUserName} (ID:${conv.targetUserId}) 头像: ${conv.targetUserAvatar}`);
- });
- }
-
- } catch (e) {
- console.error('❌ 加载会话列表失败:', e);
- console.error('❌ 错误详情:', e.message || e);
- uni.showToast({
- title: '加载失败: ' + (e.message || '请重试'),
- icon: 'none',
- duration: 2000
- });
- } finally {
- this.loading = false;
- this.refreshing = false;
- }
- },
-
- /**
- * 批量获取用户头像信息
- */
- async loadUserAvatars() {
- try {
- if (this.conversations.length === 0) {
- return;
- }
-
- // 收集所有需要获取头像的用户ID
- const userIds = this.conversations
- .map(conv => conv.targetUserId)
- .filter(id => id) // 过滤掉空值
- .join(',');
-
- if (!userIds) {
- console.log('⚠️ 没有需要获取头像的用户');
- return;
- }
-
- console.log('🔄 开始批量获取用户头像,用户ID列表:', userIds);
-
- // 调用批量获取用户信息接口
- const res = await uni.request({
- url: 'http://localhost:8083/api/user/batch',
- method: 'GET',
- data: {
- userIds: userIds
- }
- });
-
- if (res[1].statusCode === 200 && res[1].data.code === 200) {
- const userList = res[1].data.data || [];
- console.log('✅ 批量获取用户信息成功,数量:', userList.length);
-
- // 创建用户ID到用户信息的映射
- const userMap = {};
- userList.forEach(user => {
- userMap[user.userId] = user;
- });
-
- // 更新会话列表中的头像和昵称
- this.conversations.forEach(conv => {
- const userInfo = userMap[conv.targetUserId];
- if (userInfo) {
- // 更新头像(如果数据库中有头像)
- if (userInfo.avatarUrl) {
- conv.targetUserAvatar = userInfo.avatarUrl;
- }
- // 更新昵称(如果数据库中的昵称更准确)
- if (userInfo.nickname && userInfo.nickname !== `用户${conv.targetUserId}`) {
- conv.targetUserName = userInfo.nickname;
- }
-
- console.log(`🖼️ 更新用户 ${conv.targetUserId} 的信息:`, {
- 昵称: conv.targetUserName,
- 头像: conv.targetUserAvatar
- });
- }
- });
- } else {
- console.error('❌ 批量获取用户信息失败:', res[1].data);
- }
- } catch (error) {
- console.error('❌ 批量获取用户头像失败:', error);
- // 头像获取失败不影响会话列表显示,只记录错误
- }
- },
-
- /**
- * 格式化会话数据
- * 将TIM的会话格式转换为UI需要的格式
- */
- formatConversation(timConv) {
- // conversationID 格式: C2C{userId}
- const targetUserId = timConv.conversationID.replace('C2C', '');
-
- // 检查是否在本地置顶列表中
- const isPinned = this.pinnedConversations.includes(timConv.conversationID) ? 1 : 0;
-
- return {
- id: timConv.conversationID,
- userId: this.userId,
- targetUserId: targetUserId,
- targetUserName: timConv.userProfile?.nick || `用户${targetUserId}`,
- targetUserAvatar: timConv.userProfile?.avatar || '',
- lastMessage: this.getLastMessageText(timConv.lastMessage),
- lastMessageType: this.getMessageType(timConv.lastMessage),
- lastMessageTime: timConv.lastMessage?.lastTime ? timConv.lastMessage.lastTime * 1000 : Date.now(),
- unreadCount: timConv.unreadCount || 0,
- isOnline: false,
- isPinned: isPinned
- };
- },
-
- /**
- * 获取最后一条消息的文本
- */
- getLastMessageText(message) {
- if (!message) return '暂无消息';
-
- switch (message.type) {
- case 'TIMTextElem':
- return message.payload?.text || '';
- case 'TIMImageElem':
- return '[图片]';
- case 'TIMSoundElem':
- return '[语音]';
- case 'TIMVideoFileElem':
- return '[视频]';
- case 'TIMFileElem':
- return '[文件]';
- case 'TIMCustomElem':
- return '[自定义消息]';
- default:
- return '[未知消息]';
- }
- },
-
- /**
- * 获取消息类型
- */
- getMessageType(message) {
- if (!message) return 1;
-
- const typeMap = {
- 'TIMTextElem': 1, // 文本
- 'TIMImageElem': 2, // 图片
- 'TIMSoundElem': 3, // 语音
- 'TIMVideoFileElem': 4 // 视频
- };
-
- return typeMap[message.type] || 1;
- },
-
- /**
- * 下拉刷新
- */
- onRefresh() {
- this.refreshing = true;
- this.loadConversations();
- },
-
- /**
- * 加载更多(TIM一次性返回所有会话,不需要分页)
- */
- loadMore() {
- // TIM SDK 一次性返回所有会话,不需要分页加载
- },
- async loadSystemUnread() {
- try {
- const userId = this.userId;
- const res = await this.$api?.message?.getSystemUnreadCount ? this.$api.message.getSystemUnreadCount(userId) : null;
- if (res && (res.code === 200 || res.code === 0)) {
- this.systemUnread = res.data || 0;
- } else {
- // 直接调用工具方法
- const api = require('@/utils/api.js').default;
- const r = await api.message.getSystemUnreadCount(userId);
- this.systemUnread = r.data || 0;
- }
- // 预览最新一条
- const api2 = require('@/utils/api.js').default;
- const listRes = await api2.message.getSystemList(userId, 1, 1);
- const list = listRes.data?.list || listRes.data || [];
- if (list.length > 0) {
- this.systemLatestTime = list[0].createdAt || list[0].created_at;
- this.systemLatestPreview = list[0].title || '系统通知';
- }
- } catch (e) { console.log('加载系统未读失败', e); }
- },
- openSystemMessages() {
- uni.navigateTo({ url: '/pages/message/system' });
- },
-
- /**
- * 刷新会话列表
- */
- refreshConversations() {
- if (this.timInitialized) {
- this.loadConversations();
- }
- },
-
- /**
- * 打开聊天页面
- */
- openChat(conversation) {
- uni.navigateTo({
- url: `/pages/message/chat?targetUserId=${conversation.targetUserId}&targetUserName=${conversation.targetUserName}&targetUserAvatar=${conversation.targetUserAvatar || ''}`
- });
- },
-
- /**
- * 显示操作菜单
- */
- showActionMenu(conversation) {
- this.selectedConversation = conversation;
- this.$refs.actionMenu.open();
- },
-
- /**
- * 关闭操作菜单
- */
- closeActionMenu() {
- this.$refs.actionMenu.close();
- this.selectedConversation = null;
- },
-
- /**
- * 标记为已读
- */
- async markAsRead() {
- if (!this.selectedConversation) {
- return;
- }
-
- try {
- // 调用 TIM SDK 标记已读
- await timManager.setMessageRead(this.selectedConversation.id);
-
- // 更新本地显示
- this.selectedConversation.unreadCount = 0;
-
- // 重新计算总未读数
- this.totalUnread = this.conversations.reduce((total, conv) => total + conv.unreadCount, 0);
-
- uni.showToast({
- title: '已标记为已读',
- icon: 'success'
- });
- } catch (e) {
- console.error('标记已读失败', e);
- }
-
- this.closeActionMenu();
- },
-
- /**
- * 删除会话
- */
- async deleteCurrentConversation() {
- if (!this.selectedConversation) {
- return;
- }
-
- uni.showModal({
- title: '确认删除',
- content: '确定要删除该会话吗?',
- success: async (res) => {
- if (res.confirm) {
- try {
- // 调用 TIM SDK 删除会话
- await timManager.tim.deleteConversation(this.selectedConversation.id);
-
- // 从列表中移除
- const index = this.conversations.findIndex(c => c.id === this.selectedConversation.id);
- if (index > -1) {
- this.conversations.splice(index, 1);
- }
-
- // 重新计算总未读数
- this.totalUnread = this.conversations.reduce((total, conv) => total + conv.unreadCount, 0);
-
- uni.showToast({
- title: '删除成功',
- icon: 'success'
- });
- } catch (e) {
- console.error('删除会话失败', e);
- uni.showToast({
- title: '删除失败',
- icon: 'none'
- });
- }
- }
- }
- });
-
- this.closeActionMenu();
- },
-
- /**
- * 搜索(实时过滤在computed中实现)
- */
- onSearch() {
- console.log('搜索:', this.searchKeyword);
- // filteredConversations computed属性会自动过滤
- },
-
- /**
- * 取消搜索
- */
- cancelSearch() {
- this.showSearchPanel = false;
- this.searchKeyword = '';
- },
-
- /**
- * 处理滑动
- */
- handleSwipe(e, conv) {
- if (e.detail.x < -50) {
- this.swipingConvId = conv.id;
- } else if (e.detail.x > -10) {
- this.swipingConvId = null;
- }
- },
-
- /**
- * 滑动结束
- */
- handleSwipeEnd(conv) {
- // 如果滑动距离不够,自动回弹
- setTimeout(() => {
- if (this.swipingConvId === conv.id) {
- // 保持显示操作按钮
- }
- }, 100);
- },
-
- /**
- * 切换置顶状态
- */
- togglePin(conv) {
- conv.isPinned = conv.isPinned ? 0 : 1;
-
- // 保存到本地存储
- this.savePinnedConversations();
-
- // 重置滑动状态
- this.swipingConvId = null;
-
- uni.showToast({
- title: conv.isPinned ? '已置顶' : '已取消置顶',
- icon: 'success'
- });
- },
-
- /**
- * 加载置顶会话列表
- */
- loadPinnedConversations() {
- try {
- const pinned = uni.getStorageSync('pinnedConversations_' + this.userId);
- if (pinned) {
- this.pinnedConversations = JSON.parse(pinned);
- }
- } catch (e) {
- console.error('加载置顶列表失败:', e);
- }
- },
-
- /**
- * 保存置顶会话列表
- */
- savePinnedConversations() {
- try {
- const pinnedIds = this.conversations
- .filter(conv => conv.isPinned)
- .map(conv => conv.id);
- uni.setStorageSync('pinnedConversations_' + this.userId, JSON.stringify(pinnedIds));
- } catch (e) {
- console.error('保存置顶列表失败:', e);
- }
- },
-
- /**
- * 确认删除会话
- */
- confirmDeleteConversation(conv) {
- uni.showModal({
- title: '确认删除',
- content: '确定要删除该会话吗?',
- success: (res) => {
- if (res.confirm) {
- this.deleteConversationItem(conv);
- }
- }
- });
-
- // 重置滑动状态
- this.swipingConvId = null;
- },
-
- /**
- * 删除会话
- */
- async deleteConversationItem(conv) {
- try {
- // 调用 TIM SDK 删除会话
- await timManager.tim.deleteConversation(conv.id);
-
- // 从列表中移除
- const index = this.conversations.findIndex(c => c.id === conv.id);
- if (index > -1) {
- this.conversations.splice(index, 1);
- }
-
- // 重新计算总未读数
- this.totalUnread = this.conversations.reduce((total, c) => total + c.unreadCount, 0);
-
- uni.showToast({
- title: '删除成功',
- icon: 'success'
- });
- } catch (e) {
- console.error('删除会话失败', e);
- uni.showToast({
- title: '删除失败',
- icon: 'none'
- });
- }
- },
-
-
- /**
- * 格式化最后一条消息
- */
- formatLastMessage(conv) {
- if (!conv.lastMessage) {
- return '暂无消息';
- }
-
- // 限制长度
- const maxLen = 30;
- if (conv.lastMessage.length > maxLen) {
- return conv.lastMessage.substring(0, maxLen) + '...';
- }
-
- return conv.lastMessage;
- },
-
- /**
- * 格式化时间
- */
- formatTime(time) {
- if (!time) return '';
-
- const date = new Date(time);
- const now = new Date();
- const diff = now - date;
-
- // 今天
- if (date.toDateString() === now.toDateString()) {
- return date.toLocaleTimeString('zh-CN', {
- hour: '2-digit',
- minute: '2-digit'
- });
- }
-
- // 昨天
- const yesterday = new Date(now);
- yesterday.setDate(yesterday.getDate() - 1);
- if (date.toDateString() === yesterday.toDateString()) {
- return '昨天';
- }
-
- // 本周
- if (diff < 7 * 24 * 60 * 60 * 1000) {
- const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
- return days[date.getDay()];
- }
-
- // 更早
- return date.toLocaleDateString('zh-CN', {
- month: '2-digit',
- day: '2-digit'
- });
- },
-
- /**
- * 切换标签页
- */
- switchTab(tab) {
- if (tab === 'message') return;
-
- const tabPages = {
- index: '/pages/index/index',
- plaza: '/pages/plaza/index',
- recommend: '/pages/recommend/index',
- mine: '/pages/mine/index'
- };
-
- if (tabPages[tab]) {
- uni.redirectTo({
- url: tabPages[tab]
- });
- }
- }
- }
- };
- </script>
- <style lang="scss" scoped>
- .message-page {
- min-height: 100vh;
- background-color: #F5F5F5;
- padding-bottom: 120rpx;
- }
- /* 顶部标题栏 */
- .header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 30rpx;
- background-color: #FFFFFF;
- border-bottom: 1rpx solid #F0F0F0;
-
- .header-title {
- font-size: 40rpx;
- font-weight: bold;
- color: #E91E63;
- }
-
- .header-actions {
- display: flex;
- gap: 30rpx;
-
- .action-icon {
- font-size: 40rpx;
- cursor: pointer;
- }
- }
- }
- /* 搜索面板 */
- .search-panel {
- background-color: #FFFFFF;
- padding: 20rpx 30rpx;
- border-bottom: 1rpx solid #F0F0F0;
-
- .search-bar {
- display: flex;
- align-items: center;
- gap: 20rpx;
-
- .search-input {
- flex: 1;
- height: 70rpx;
- padding: 0 20rpx;
- background-color: #F5F5F5;
- border-radius: 35rpx;
- font-size: 28rpx;
- }
-
- .search-cancel {
- font-size: 28rpx;
- color: #E91E63;
- }
- }
- }
- /* 会话列表 */
- .conversation-list {
- height: calc(100vh - 200rpx);
- background-color: #FFFFFF;
- }
- /* 骨架屏 */
- .skeleton-container {
- padding: 20rpx 0;
- }
- .skeleton-item {
- display: flex;
- align-items: center;
- padding: 25rpx 30rpx;
- background-color: #FFFFFF;
- border-bottom: 1rpx solid #F5F5F5;
-
- .skeleton-avatar {
- width: 100rpx;
- height: 100rpx;
- border-radius: 12rpx;
- background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
- background-size: 200% 100%;
- animation: skeleton-loading 1.5s ease-in-out infinite;
- margin-right: 25rpx;
- }
-
- .skeleton-content {
- flex: 1;
-
- .skeleton-line {
- height: 30rpx;
- border-radius: 6rpx;
- background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
- background-size: 200% 100%;
- animation: skeleton-loading 1.5s ease-in-out infinite;
-
- &.skeleton-line-title {
- width: 40%;
- margin-bottom: 20rpx;
- }
-
- &.skeleton-line-text {
- width: 60%;
- }
- }
- }
- }
- @keyframes skeleton-loading {
- 0% {
- background-position: 200% 0;
- }
- 100% {
- background-position: -200% 0;
- }
- }
- /* 空状态 */
- .empty-container {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: 150rpx 60rpx;
-
- .empty-icon-wrapper {
- width: 200rpx;
- height: 200rpx;
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
- border-radius: 50%;
- display: flex;
- align-items: center;
- justify-content: center;
- margin-bottom: 40rpx;
- box-shadow: 0 20rpx 60rpx rgba(102, 126, 234, 0.3);
- animation: float 3s ease-in-out infinite;
- }
-
- .empty-icon {
- font-size: 100rpx;
- filter: brightness(1.2);
- }
-
- .empty-text {
- font-size: 36rpx;
- font-weight: 600;
- color: #333333;
- margin-bottom: 15rpx;
- }
-
- .empty-hint {
- font-size: 28rpx;
- color: #999999;
- margin-bottom: 40rpx;
- }
-
- .empty-action {
- margin-top: 20rpx;
-
- .empty-btn {
- padding: 20rpx 60rpx;
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
- color: #FFFFFF;
- border-radius: 50rpx;
- font-size: 28rpx;
- border: none;
- box-shadow: 0 10rpx 30rpx rgba(102, 126, 234, 0.3);
-
- &::after {
- border: none;
- }
- }
- }
- }
- @keyframes float {
- 0%, 100% {
- transform: translateY(0);
- }
- 50% {
- transform: translateY(-20rpx);
- }
- }
- /* 会话列表项包装器 */
- .conversation-item-wrapper {
- position: relative;
- background-color: #FFFFFF;
- border-bottom: 1rpx solid #F5F5F5;
- overflow: hidden;
- }
- /* 系统消息高亮样式 */
- .system-highlight { background: #fff7f7; }
- .system-icon { font-size: 44rpx; color: #E91E63; }
- .system-title { color: #E91E63; font-weight: 600; }
- .system-preview { color: #d25d6b; }
- .system-tag { font-size: 22rpx; color: #fff; background-color: #E91E63; padding: 4rpx 10rpx; border-radius: 8rpx; }
- /* 滑动区域 */
- .movable-area {
- width: 100%;
- height: 160rpx;
- position: relative;
- }
- .movable-view {
- width: 100%;
- height: 100%;
- background-color: #FFFFFF;
- }
- /* 会话列表项 */
- .conversation-item {
- display: flex;
- align-items: center;
- padding: 25rpx 30rpx;
- background-color: #FFFFFF;
- position: relative;
- width: 100%;
- height: 100%;
-
- &:active {
- background-color: #F8F8F8;
- }
-
- /* 置顶标记 */
- .pinned-badge {
- position: absolute;
- top: 10rpx;
- left: 10rpx;
- font-size: 28rpx;
- opacity: 0.7;
- }
-
- .avatar-wrapper {
- position: relative;
- margin-right: 25rpx;
-
- .avatar {
- width: 100rpx;
- height: 100rpx;
- border-radius: 12rpx;
- }
-
- .online-badge {
- position: absolute;
- bottom: 0;
- right: 0;
- width: 24rpx;
- height: 24rpx;
- background-color: #07C160;
- border: 3rpx solid #FFFFFF;
- border-radius: 50%;
- }
-
- .unread-badge {
- position: absolute;
- top: -10rpx;
- right: -10rpx;
- min-width: 36rpx;
- height: 36rpx;
- line-height: 36rpx;
- padding: 0 8rpx;
- background-color: #FA5151;
- border-radius: 18rpx;
- font-size: 20rpx;
- color: #FFFFFF;
- text-align: center;
- }
- }
-
- .conversation-content {
- flex: 1;
-
- .content-top {
- display: flex;
- align-items: center;
- justify-content: space-between;
- margin-bottom: 12rpx;
-
- .user-name {
- font-size: 32rpx;
- font-weight: 500;
- color: #333333;
- }
-
- .last-time {
- font-size: 24rpx;
- color: #999999;
- }
- }
-
- .content-bottom {
- display: flex;
- align-items: center;
- gap: 10rpx;
-
- .last-message {
- flex: 1;
- font-size: 28rpx;
- color: #999999;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-
- &.unread {
- color: #666666;
- font-weight: 500;
- }
- }
-
- .message-type-icon {
- font-size: 28rpx;
- }
- }
- }
-
- /* 右滑操作按钮 */
- .conversation-actions {
- position: absolute;
- right: 0;
- top: 0;
- height: 100%;
- display: flex;
- z-index: 1;
-
- .action-btn {
- width: 150rpx;
- height: 100%;
- display: flex;
- align-items: center;
- justify-content: center;
- color: #FFFFFF;
- font-size: 28rpx;
- }
-
- .pin-btn {
- background-color: #576B95;
- }
-
- .delete-btn {
- background-color: #FA5151;
- }
- }
- }
- .load-more {
- padding: 30rpx;
- text-align: center;
-
- .load-more-text {
- font-size: 26rpx;
- color: #999999;
- }
- }
- /* 底部导航栏 */
- .tabbar {
- position: fixed;
- bottom: 0;
- left: 0;
- right: 0;
- display: flex;
- background-color: #FFFFFF;
- border-top: 1rpx solid #F0F0F0;
- padding-bottom: constant(safe-area-inset-bottom);
- padding-bottom: env(safe-area-inset-bottom);
- z-index: 999;
-
- .tabbar-item {
- flex: 1;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: 15rpx 0;
- position: relative;
-
- .tabbar-icon {
- font-size: 44rpx;
- margin-bottom: 5rpx;
- }
-
- .tabbar-text {
- font-size: 22rpx;
- color: #666666;
- }
-
- .tab-badge {
- position: absolute;
- top: 8rpx;
- right: 50%;
- margin-right: -40rpx;
- min-width: 32rpx;
- height: 32rpx;
- line-height: 32rpx;
- padding: 0 6rpx;
- background-color: #FA5151;
- border-radius: 16rpx;
- font-size: 20rpx;
- color: #FFFFFF;
- text-align: center;
- }
-
- &.active {
- .tabbar-text {
- color: #E91E63;
- font-weight: bold;
- }
- }
- }
- }
- /* 操作菜单 */
- .action-menu {
- background-color: #FFFFFF;
- border-radius: 20rpx 20rpx 0 0;
-
- .menu-item {
- padding: 30rpx;
- text-align: center;
- font-size: 32rpx;
- color: #333333;
- border-bottom: 1rpx solid #F0F0F0;
-
- &:active {
- background-color: #F8F8F8;
- }
-
- &.cancel {
- color: #999999;
- border: none;
- margin-top: 20rpx;
- }
- }
- }
- </style>
|