| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384 |
- <template>
- <view class="chat-page">
- <!-- 顶部导航 -->
- <view class="chat-header">
- <view class="header-left" @click="goBack">
- <text class="icon-back">←</text>
- </view>
- <view class="header-center">
- <text class="chat-title">{{ targetUserName }}</text>
- <text class="online-status" :class="{ online: isTargetOnline }">
- {{ isTargetOnline ? '在线' : '离线' }}
- </text>
- </view>
- <view class="header-right">
- <text class="icon-more">⋯</text>
- </view>
- </view>
- <!-- 消息列表 -->
- <scroll-view
- class="message-list"
- scroll-y
- :scroll-into-view="scrollToView"
- @scrolltoupper="loadMoreMessages">
-
- <!-- 加载更多提示 -->
- <view v-if="loading" class="loading-tip">加载中...</view>
- <view v-else-if="noMore" class="loading-tip">没有更多消息了</view>
- <!-- 时间分组和消息项 -->
- <view v-for="(msg, index) in messages" :key="msg.messageId">
- <!-- 时间分隔线 (每5分钟显示一次) -->
- <view v-if="shouldShowTime(msg, index)" class="time-divider">
- <text class="time-text">{{ formatMessageTime(msg.sendTime) }}</text>
- </view>
-
- <!-- 消息项 -->
- <view
- :id="'msg-' + index"
- class="message-item"
- :class="{ 'message-self': msg.fromUserId === userId }"
- @longpress="showMessageMenu(msg, index)">
-
- <!-- 头像 -->
- <image
- class="avatar"
- :src="msg.fromUserId === userId ? userAvatar : targetUserAvatar"
- mode="aspectFill" />
-
- <!-- 消息内容 -->
- <view class="message-content-wrapper">
- <!-- 用户名(对方消息时显示) -->
- <text v-if="msg.fromUserId !== userId" class="message-name">
- {{ msg.fromUserName }}
- </text>
-
- <!-- 消息气泡 -->
- <view
- class="message-bubble"
- :class="{ 'bubble-self': msg.fromUserId === userId, 'bubble-failed': msg.sendStatus === 4 }"
- @click="handleMessageClick(msg)">
- <!-- 文本消息 -->
- <text v-if="msg.messageType === 1" class="message-text">
- {{ msg.content }}
- </text>
-
- <!-- 图片消息 -->
- <image
- v-else-if="msg.messageType === 2"
- class="message-image"
- :src="msg.mediaUrl"
- mode="widthFix"
- lazy-load
- @click.stop="previewImage(msg.mediaUrl)" />
-
- <!-- 语音消息 -->
- <view v-else-if="msg.messageType === 3" class="message-voice" @click.stop="playVoice(msg)">
- <text>🔊</text>
- <text>{{ msg.duration }}"</text>
- </view>
-
- <!-- 视频消息 -->
- <video
- v-else-if="msg.messageType === 4"
- class="message-video"
- :src="msg.mediaUrl"
- controls />
-
- <!-- 撤回消息 -->
- <text v-if="msg.isRecalled" class="message-recalled">
- 消息已撤回
- </text>
- </view>
-
- <!-- 消息状态(自己的消息) -->
- <view v-if="msg.fromUserId === userId" class="message-status">
- <text v-if="msg.sendStatus === 1" class="sending">发送中...</text>
- <text v-else-if="msg.sendStatus === 2">已送达</text>
- <text v-else-if="msg.sendStatus === 3" class="read">已读</text>
- <view v-else-if="msg.sendStatus === 4" class="failed-group">
- <text class="failed">发送失败</text>
- <text class="retry-btn" @click.stop="retryMessage(msg)">重试</text>
- </view>
- </view>
- </view>
- </view>
- </view>
- </scroll-view>
- <!-- 输入框 -->
- <view class="input-bar">
- <!-- 语音按钮 -->
- <view class="input-icon" @click="switchInputType">
- <text>{{ inputType === 'text' ? '🎤' : '⌨️' }}</text>
- </view>
-
- <!-- 文本输入 -->
- <input
- v-if="inputType === 'text'"
- class="input-field"
- v-model="inputText"
- placeholder="说点什么..."
- confirm-type="send"
- @confirm="sendTextMessage"
- @input="onInputChange" />
-
- <!-- 语音按钮 -->
- <button
- v-else
- class="voice-button"
- @touchstart="startVoiceRecord"
- @touchend="stopVoiceRecord">
- 按住说话
- </button>
-
- <!-- 表情按钮 -->
- <view class="input-icon" @click="showEmojiPanel = !showEmojiPanel">
- <text>😊</text>
- </view>
-
- <!-- 更多按钮 -->
- <view class="input-icon" @click="showMorePanel = !showMorePanel">
- <text>➕</text>
- </view>
- </view>
- <!-- 表情面板 -->
- <view v-if="showEmojiPanel" class="emoji-panel">
- <text
- v-for="emoji in emojis"
- :key="emoji"
- class="emoji-item"
- @click="insertEmoji(emoji)">
- {{ emoji }}
- </text>
- </view>
- <!-- 更多功能面板 -->
- <view v-if="showMorePanel" class="more-panel">
- <view class="more-item" @click="chooseImage">
- <view class="more-icon">🖼️</view>
- <text class="more-text">图片</text>
- </view>
- <view class="more-item" @click="chooseVideo">
- <view class="more-icon">📹</view>
- <text class="more-text">视频</text>
- </view>
- <view class="more-item" @click="chooseFile">
- <view class="more-icon">📁</view>
- <text class="more-text">文件</text>
- </view>
- </view>
-
- <!-- 消息操作菜单 -->
- <view v-if="showMessageAction" class="message-action-mask" @click="hideMessageMenu">
- <view class="message-action-menu" @click.stop>
- <view class="menu-item" @click="copyMessage" v-if="selectedMessage && selectedMessage.messageType === 1">
- <text class="menu-icon">📋</text>
- <text>复制</text>
- </view>
- <view class="menu-item" @click="recallMessage" v-if="selectedMessage && selectedMessage.fromUserId === userId && canRecall(selectedMessage)">
- <text class="menu-icon">↩️</text>
- <text>撤回</text>
- </view>
- <view class="menu-item" @click="deleteMessage">
- <text class="menu-icon">🗑️</text>
- <text>删除</text>
- </view>
- <view class="menu-item cancel" @click="hideMessageMenu">
- <text>取消</text>
- </view>
- </view>
- </view>
- </view>
- </template>
- <script>
- import timManager from '@/utils/tim-manager.js';
- import TIM from 'tim-wx-sdk';
- export default {
- data() {
- return {
- userId: null,
- userAvatar: '',
- targetUserId: null,
- targetUserName: '',
- targetUserAvatar: '',
-
- messages: [],
- inputText: '',
- inputType: 'text',
- conversationID: '',
-
- scrollToView: '',
- showEmojiPanel: false,
- showMorePanel: false,
-
- isLogin: false,
-
- // 消息操作菜单
- showMessageAction: false,
- selectedMessage: null,
- selectedMessageIndex: -1,
- menuTop: 0,
-
- // 加载更多
- loading: false,
- noMore: false,
- nextReqMessageID: '',
- isTargetOnline: false,
-
- emojis: ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩', '🥳']
- };
- },
-
- async onLoad(options) {
- console.log('=== 聊天页面加载 ===');
-
- // 严格验证登录状态
- 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,确保一致性
- let rawUserId = storedUserId || userInfo.userId || userInfo.id || userInfo.user_id;
-
- // 转换为数字类型(确保与消息列表页面一致)
- if (typeof rawUserId === 'string') {
- rawUserId = parseInt(rawUserId);
- }
-
- if (!rawUserId || isNaN(rawUserId)) {
- console.error('❌ 无法获取有效的用户ID');
- uni.showModal({
- title: '用户信息错误',
- content: '无法获取用户ID,请重新登录',
- showCancel: false,
- success: () => {
- uni.removeStorageSync('token');
- uni.removeStorageSync('userInfo');
- uni.removeStorageSync('userId');
- uni.reLaunch({
- url: '/pages/page3/page3'
- });
- }
- });
- return;
- }
-
- // 保存用户ID(TIM需要字符串格式)
- this.userId = String(rawUserId);
- this.userAvatar = userInfo.avatar || userInfo.avatarUrl || '/static/default-avatar.svg';
-
- // 获取对方用户信息(确保是字符串格式)
- this.targetUserId = String(options.targetUserId);
- this.targetUserName = decodeURIComponent(options.targetUserName || '用户');
- this.targetUserAvatar = decodeURIComponent(options.targetUserAvatar || '/static/default-avatar.svg');
-
- // 生成会话 ID
- this.conversationID = `C2C${this.targetUserId}`;
-
- console.log('✅ 聊天页面初始化成功:');
- console.log(' - 当前用户ID:', rawUserId, '(TIM格式:', this.userId, ')');
- console.log(' - 对方用户ID:', this.targetUserId);
- console.log(' - 会话ID:', this.conversationID);
-
- // 初始化 TIM
- await this.initTIM();
-
- // 等待 SDK Ready 后再加载消息
- await this.waitForSDKReady();
-
- // 加载历史消息
- await this.loadMessages();
-
- // 监听新消息
- this.listenMessages();
- },
-
- onUnload() {
- // 页面卸载时移除监听
- timManager.offMessage(this.handleNewMessage);
- },
-
- methods: {
- /**
- * 初始化 TIM
- */
- async initTIM() {
- try {
- // 如果未初始化,先初始化
- if (!timManager.tim) {
- timManager.init(1600109674); // ✅ 已更新为正确的 SDKAppID
- }
-
- // 如果未登录,获取 userSig 并登录
- if (!timManager.isLogin) {
- // 先导入当前用户和目标用户到腾讯云IM
- await this.importUsers();
-
- // 从后端获取 userSig
- const userSig = await this.getUserSig();
- await timManager.login(this.userId, userSig);
- }
-
- this.isLogin = true;
- console.log('✅ TIM 初始化完成');
- } catch (error) {
- console.error('❌ TIM 初始化失败:', error);
- uni.showToast({
- title: '连接失败,请重试',
- icon: 'none'
- });
- }
- },
-
- /**
- * 导入用户到腾讯云IM
- */
- async importUsers() {
- try {
- console.log('📥 开始导入用户到腾讯云IM...');
- console.log(' - 当前用户ID:', this.userId, '(类型:', typeof this.userId, ')');
- console.log(' - 目标用户ID:', this.targetUserId, '(类型:', typeof this.targetUserId, ')');
-
- // 验证用户ID
- if (!this.userId || this.userId === 'undefined' || this.userId === 'null') {
- throw new Error('当前用户ID无效: ' + this.userId);
- }
- if (!this.targetUserId || this.targetUserId === 'undefined' || this.targetUserId === 'null') {
- throw new Error('目标用户ID无效: ' + this.targetUserId);
- }
-
- // 导入当前用户(确保userId是字符串)
- const currentUserRes = await uni.request({
- url: 'http://localhost:1004/api/im/importUser',
- method: 'POST',
- data: {
- userId: String(this.userId),
- nickname: '用户' + this.userId
- },
- header: {
- 'Content-Type': 'application/json'
- }
- });
-
- console.log(' - 当前用户导入结果:', currentUserRes[1].data);
-
- // 导入目标用户(确保userId是字符串)
- const targetUserRes = await uni.request({
- url: 'http://localhost:1004/api/im/importUser',
- method: 'POST',
- data: {
- userId: String(this.targetUserId),
- nickname: this.targetUserName || '用户' + this.targetUserId
- },
- header: {
- 'Content-Type': 'application/json'
- }
- });
-
- console.log(' - 目标用户导入结果:', targetUserRes[1].data);
- console.log('✅ 用户导入成功');
- } catch (error) {
- console.log('⚠️ 用户导入失败(可能已存在):', error);
- // 导入失败不影响登录,因为用户可能已经存在
- }
- },
-
- /**
- * 获取 UserSig
- */
- async getUserSig() {
- try {
- const [err, res] = await uni.request({
- url: 'http://localhost:1004/api/im/getUserSig',
- method: 'GET',
- data: {
- userId: this.userId
- }
- });
-
- if (err) {
- throw new Error('请求失败');
- }
-
- if (res.data && res.data.code === 200) {
- return res.data.data.userSig;
- } else {
- throw new Error('获取 UserSig 失败');
- }
- } catch (error) {
- console.error('❌ 获取 UserSig 失败:', error);
- throw error;
- }
- },
-
- /**
- * 等待 SDK Ready
- */
- async waitForSDKReady() {
- return new Promise((resolve) => {
- // 如果已经 ready,立即返回
- if (timManager.isLogin) {
- console.log('✅ SDK 已就绪');
- resolve();
- return;
- }
-
- // 否则等待 SDK ready 事件
- console.log('⏳ 等待 SDK 就绪...');
- const checkReady = setInterval(() => {
- if (timManager.isLogin) {
- console.log('✅ SDK 已就绪');
- clearInterval(checkReady);
- resolve();
- }
- }, 100); // 每 100ms 检查一次
-
- // 超时保护(10秒后强制继续)
- setTimeout(() => {
- console.log('⚠️ 等待 SDK 就绪超时,继续执行');
- clearInterval(checkReady);
- resolve();
- }, 10000);
- });
- },
-
- /**
- * 加载历史消息
- */
- async loadMessages() {
- try {
- const res = await timManager.tim.getMessageList({
- conversationID: this.conversationID,
- count: 20
- });
-
- const messageList = res.data.messageList;
- this.nextReqMessageID = res.data.nextReqMessageID;
- this.noMore = !res.data.isCompleted;
-
- // 转换为我们的消息格式
- this.messages = messageList.map(msg => this.convertMessage(msg));
-
- // 滚动到底部
- this.$nextTick(() => {
- this.scrollToBottom();
- });
-
- // 标记已读
- await timManager.setMessageRead(this.conversationID);
- } catch (error) {
- console.error('❌ 加载消息失败:', error);
- }
- },
-
- /**
- * 加载更多消息(上拉)
- */
- async loadMoreMessages() {
- if (this.loading || !this.nextReqMessageID) {
- return;
- }
-
- this.loading = true;
-
- try {
- const res = await timManager.tim.getMessageList({
- conversationID: this.conversationID,
- nextReqMessageID: this.nextReqMessageID,
- count: 20
- });
-
- const messageList = res.data.messageList;
- this.nextReqMessageID = res.data.nextReqMessageID;
- this.noMore = !res.data.isCompleted;
-
- // 转换并添加到消息列表前面
- const newMessages = messageList.map(msg => this.convertMessage(msg));
- this.messages = [...newMessages, ...this.messages];
-
- } catch (error) {
- console.error('❌ 加载更多消息失败:', error);
- } finally {
- this.loading = false;
- }
- },
-
- /**
- * 监听新消息
- */
- listenMessages() {
- const handleNewMessage = (messageList) => {
- messageList.forEach(msg => {
- // 只处理当前会话的消息
- if (msg.conversationID === this.conversationID) {
- this.messages.push(this.convertMessage(msg));
- this.$nextTick(() => {
- this.scrollToBottom();
- });
-
- // 标记已读
- timManager.setMessageRead(this.conversationID);
- }
- });
- };
-
- this.handleNewMessage = handleNewMessage;
- timManager.onMessage(handleNewMessage);
- },
-
- /**
- * 转换消息格式
- */
- convertMessage(timMsg) {
- return {
- messageId: timMsg.ID,
- fromUserId: timMsg.from,
- toUserId: timMsg.to,
- messageType: timMsg.type === TIM.TYPES.MSG_TEXT ? 1 : 2,
- content: timMsg.type === TIM.TYPES.MSG_TEXT ? timMsg.payload.text : '[图片]',
- mediaUrl: timMsg.type === TIM.TYPES.MSG_IMAGE ? timMsg.payload.imageInfoArray[0].url : '',
- sendStatus: timMsg.status === 'success' ? 2 : 1,
- sendTime: new Date(timMsg.time * 1000),
- isRecalled: timMsg.isRevoked,
- fromUserName: timMsg.from === this.userId ? '我' : this.targetUserName
- };
- },
-
- /**
- * 发送文本消息
- */
- async sendTextMessage() {
- if (!this.inputText.trim()) {
- return;
- }
-
- const content = this.inputText;
- this.inputText = '';
-
- try {
- const message = await timManager.sendTextMessage(this.targetUserId, content);
-
- // 添加到消息列表
- this.messages.push(this.convertMessage(message));
- this.scrollToBottom();
-
- console.log('✅ 消息发送成功');
-
- // 同步消息到MySQL数据库(双重保障)
- this.syncMessageToMySQL(message);
- } catch (error) {
- console.error('❌ 消息发送失败:', error);
- uni.showToast({
- title: '发送失败',
- icon: 'none'
- });
- // 失败时恢复输入框内容
- this.inputText = content;
- }
- },
-
- /**
- * 选择图片
- */
- chooseImage() {
- uni.chooseImage({
- count: 1,
- sizeType: ['compressed'],
- sourceType: ['album', 'camera'],
- success: async (res) => {
- const tempFilePath = res.tempFilePaths[0];
-
- try {
- uni.showLoading({ title: '发送中...' });
-
- const message = await timManager.sendImageMessage(this.targetUserId, tempFilePath);
-
- this.messages.push(this.convertMessage(message));
- this.scrollToBottom();
-
- uni.hideLoading();
- console.log('✅ 图片发送成功');
- } catch (error) {
- uni.hideLoading();
- console.error('❌ 图片发送失败:', error);
- uni.showToast({
- title: '发送失败',
- icon: 'none'
- });
- }
- }
- });
-
- this.showMorePanel = false;
- },
-
- /**
- * 输入框内容变化
- */
- onInputChange() {
- // 腾讯云 IM 可以实现正在输入状态,这里暂时省略
- console.log('输入中...');
- },
-
- /**
- * 同步消息到MySQL数据库(双重存储保障)
- */
- async syncMessageToMySQL(timMessage) {
- try {
- console.log('🔄 同步消息到MySQL...', timMessage.ID);
-
- // 构建同步参数
- const syncData = {
- messageId: timMessage.ID,
- fromUserId: timMessage.from,
- toUserId: timMessage.to,
- messageType: this.getMessageType(timMessage),
- content: this.getMessageContent(timMessage),
- sendTime: timMessage.time // TIM返回的是秒级时间戳
- };
-
- // 如果是图片消息,添加媒体信息
- if (timMessage.type === 'TIMImageElem' && timMessage.payload.imageInfoArray) {
- const imageInfo = timMessage.payload.imageInfoArray[0];
- syncData.mediaUrl = imageInfo.imageUrl;
- syncData.thumbnailUrl = imageInfo.imageUrl;
- }
-
- // 调用后端同步接口
- const res = await uni.request({
- url: 'http://localhost:1004/api/chat/syncTIMMessage',
- method: 'POST',
- data: syncData,
- header: {
- 'Content-Type': 'application/json'
- }
- });
-
- if (res[1].data.code === 200) {
- console.log('✅ 消息已同步到MySQL:', timMessage.ID);
- } else {
- console.warn('⚠️ 消息同步失败:', res[1].data.message);
- }
- } catch (error) {
- console.error('❌ 同步消息到MySQL失败:', error);
- // 同步失败不影响聊天功能,只记录日志
- }
- },
-
- /**
- * 获取消息类型
- */
- getMessageType(timMessage) {
- const typeMap = {
- 'TIMTextElem': 1, // 文本
- 'TIMImageElem': 2, // 图片
- 'TIMSoundElem': 3, // 语音
- 'TIMVideoFileElem': 4, // 视频
- 'TIMFileElem': 5 // 文件
- };
- return typeMap[timMessage.type] || 1;
- },
-
- /**
- * 获取消息内容
- */
- getMessageContent(timMessage) {
- switch (timMessage.type) {
- case 'TIMTextElem':
- return timMessage.payload.text || '';
- case 'TIMImageElem':
- return '[图片]';
- case 'TIMSoundElem':
- return '[语音]';
- case 'TIMVideoFileElem':
- return '[视频]';
- case 'TIMFileElem':
- return '[文件]';
- default:
- return '[未知消息]';
- }
- },
-
-
- /**
- * 滚动到底部
- */
- scrollToBottom() {
- this.$nextTick(() => {
- const lastIndex = this.messages.length - 1;
- this.scrollToView = 'msg-' + lastIndex;
- });
- },
-
- /**
- * 判断是否显示时间分隔线
- */
- shouldShowTime(msg, index) {
- if (index === 0) return true;
-
- const prevMsg = this.messages[index - 1];
- const timeDiff = new Date(msg.sendTime) - new Date(prevMsg.sendTime);
-
- // 超过5分钟显示时间
- return timeDiff > 5 * 60 * 1000;
- },
-
- /**
- * 格式化消息时间(用于时间分隔线)
- */
- formatMessageTime(time) {
- const date = new Date(time);
- const now = new Date();
- const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
- const yesterday = new Date(today - 86400000);
-
- // 今天
- if (date >= today) {
- return date.toLocaleTimeString('zh-CN', {
- hour: '2-digit',
- minute: '2-digit'
- });
- }
-
- // 昨天
- if (date >= yesterday) {
- return '昨天 ' + date.toLocaleTimeString('zh-CN', {
- hour: '2-digit',
- minute: '2-digit'
- });
- }
-
- // 本周
- if (date > new Date(now - 7 * 86400000)) {
- const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
- return days[date.getDay()] + ' ' + date.toLocaleTimeString('zh-CN', {
- hour: '2-digit',
- minute: '2-digit'
- });
- }
-
- // 更早
- return date.toLocaleString('zh-CN', {
- month: '2-digit',
- day: '2-digit',
- hour: '2-digit',
- minute: '2-digit'
- });
- },
-
- /**
- * 格式化时间(消息状态用)
- */
- formatTime(time) {
- const date = new Date(time);
- const now = new Date();
- const diff = now - date;
-
- if (diff < 60000) {
- return '刚刚';
- } else if (diff < 3600000) {
- return Math.floor(diff / 60000) + '分钟前';
- } else if (diff < 86400000) {
- return Math.floor(diff / 3600000) + '小时前';
- } else {
- return date.toLocaleString('zh-CN', {
- month: '2-digit',
- day: '2-digit',
- hour: '2-digit',
- minute: '2-digit'
- });
- }
- },
-
- /**
- * 预览图片
- */
- previewImage(url) {
- uni.previewImage({
- urls: [url],
- current: url
- });
- },
-
- /**
- * 返回
- */
- goBack() {
- uni.navigateBack({
- success: () => {
- // 通知消息列表页面刷新
- uni.$emit('refreshConversations');
- }
- });
- },
-
- /**
- * 显示消息操作菜单
- */
- showMessageMenu(msg, index) {
- this.selectedMessage = msg;
- this.selectedMessageIndex = index;
- this.showMessageAction = true;
-
- // 计算菜单位置
- uni.createSelectorQuery().select('.message-item').boundingClientRect(rect => {
- if (rect) {
- this.menuTop = rect.top + rect.height;
- }
- }).exec();
- },
-
- /**
- * 隐藏消息操作菜单
- */
- hideMessageMenu() {
- this.showMessageAction = false;
- this.selectedMessage = null;
- this.selectedMessageIndex = -1;
- },
-
- /**
- * 复制消息
- */
- copyMessage() {
- if (!this.selectedMessage || this.selectedMessage.messageType !== 1) {
- return;
- }
-
- uni.setClipboardData({
- data: this.selectedMessage.content,
- success: () => {
- uni.showToast({
- title: '已复制',
- icon: 'success'
- });
- }
- });
-
- this.hideMessageMenu();
- },
-
- /**
- * 判断是否可以撤回
- */
- canRecall(msg) {
- const diff = Date.now() - new Date(msg.sendTime).getTime();
- return diff < 2 * 60 * 1000; // 2分钟内可撤回
- },
-
- /**
- * 撤回消息
- */
- async recallMessage() {
- if (!this.selectedMessage) {
- return;
- }
-
- try {
- // 查找TIM消息对象
- const timMessage = await timManager.tim.findMessage(this.selectedMessage.messageId);
-
- if (timMessage) {
- await timManager.revokeMessage(timMessage);
-
- // 更新本地消息状态
- this.selectedMessage.isRecalled = true;
- this.selectedMessage.content = '你撤回了一条消息';
-
- uni.showToast({
- title: '已撤回',
- icon: 'success'
- });
- }
- } catch (error) {
- console.error('撤回失败:', error);
- uni.showToast({
- title: '撤回失败',
- icon: 'none'
- });
- }
-
- this.hideMessageMenu();
- },
-
- /**
- * 删除消息
- */
- deleteMessage() {
- if (!this.selectedMessage) {
- return;
- }
-
- uni.showModal({
- title: '确认删除',
- content: '确定要删除这条消息吗?',
- success: (res) => {
- if (res.confirm) {
- // 从列表中删除
- this.messages.splice(this.selectedMessageIndex, 1);
- uni.showToast({
- title: '已删除',
- icon: 'success'
- });
- }
- }
- });
-
- this.hideMessageMenu();
- },
-
- /**
- * 处理消息点击
- */
- handleMessageClick(msg) {
- // 如果是发送失败的消息,提示重试
- if (msg.sendStatus === 4) {
- uni.showModal({
- title: '发送失败',
- content: '消息发送失败,是否重试?',
- success: (res) => {
- if (res.confirm) {
- this.retryMessage(msg);
- }
- }
- });
- }
- },
-
- /**
- * 重试发送消息
- */
- async retryMessage(msg) {
- if (msg.messageType !== 1) {
- uni.showToast({
- title: '暂不支持重发该类型消息',
- icon: 'none'
- });
- return;
- }
-
- try {
- // 更新状态为发送中
- msg.sendStatus = 1;
-
- // 重新发送
- const message = await timManager.sendTextMessage(this.targetUserId, msg.content);
-
- // 更新消息
- const index = this.messages.findIndex(m => m.messageId === msg.messageId);
- if (index > -1) {
- this.messages[index] = this.convertMessage(message);
- }
-
- console.log('✅ 消息重发成功');
-
- } catch (error) {
- console.error('❌ 消息重发失败:', error);
- msg.sendStatus = 4;
- uni.showToast({
- title: '发送失败',
- icon: 'none'
- });
- }
- },
-
- // 其他功能方法
- switchInputType() {
- this.inputType = this.inputType === 'text' ? 'voice' : 'text';
- },
- startVoiceRecord() {
- uni.showToast({
- title: '按住说话',
- icon: 'none'
- });
- },
- stopVoiceRecord() {
- uni.showToast({
- title: '语音功能开发中',
- icon: 'none'
- });
- },
- insertEmoji(emoji) {
- this.inputText += emoji;
- this.showEmojiPanel = false;
- },
- chooseVideo() {
- uni.showToast({
- title: '视频功能开发中',
- icon: 'none'
- });
- this.showMorePanel = false;
- },
- chooseFile() {
- uni.showToast({
- title: '文件功能开发中',
- icon: 'none'
- });
- this.showMorePanel = false;
- },
- playVoice() {
- uni.showToast({
- title: '语音播放功能开发中',
- icon: 'none'
- });
- }
- }
- };
- </script>
- <style scoped>
- .chat-page {
- display: flex;
- flex-direction: column;
- height: 100vh;
- background-color: #f5f5f5;
- }
- /* 顶部导航 */
- .chat-header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 20rpx 30rpx;
- background-color: #fff;
- border-bottom: 1px solid #e5e5e5;
- }
- .header-left, .header-right {
- width: 80rpx;
- }
- .icon-back, .icon-more {
- font-size: 40rpx;
- }
- .header-center {
- flex: 1;
- text-align: center;
- }
- .chat-title {
- display: block;
- font-size: 36rpx;
- font-weight: bold;
- }
- .online-status {
- display: block;
- font-size: 24rpx;
- color: #999;
- margin-top: 5rpx;
- }
- .online-status.online {
- color: #07c160;
- }
- /* 消息列表 */
- .message-list {
- flex: 1;
- padding: 20rpx;
- overflow-y: scroll;
- }
- .loading-tip {
- text-align: center;
- padding: 20rpx;
- color: #999;
- font-size: 28rpx;
- }
- .message-item {
- display: flex;
- margin-bottom: 30rpx;
- }
- .message-item.message-self {
- flex-direction: row-reverse;
- }
- .avatar {
- width: 80rpx;
- height: 80rpx;
- border-radius: 8rpx;
- margin: 0 20rpx;
- }
- .message-content-wrapper {
- max-width: 70%;
- }
- .message-name {
- display: block;
- font-size: 24rpx;
- color: #999;
- margin-bottom: 10rpx;
- }
- .message-bubble {
- padding: 20rpx;
- border-radius: 8rpx;
- background-color: #fff;
- word-wrap: break-word;
- }
- .message-self .message-bubble {
- background-color: #95ec69;
- }
- .message-bubble.bubble-self {
- background-color: #95ec69;
- }
- .message-text {
- font-size: 30rpx;
- line-height: 1.5;
- }
- .message-image {
- max-width: 400rpx;
- border-radius: 8rpx;
- }
- .message-voice {
- display: flex;
- align-items: center;
- gap: 10rpx;
- }
- .message-video {
- width: 400rpx;
- height: 300rpx;
- }
- .message-recalled {
- color: #999;
- font-size: 28rpx;
- }
- .message-status {
- text-align: right;
- font-size: 24rpx;
- color: #999;
- margin-top: 5rpx;
- }
- .message-status .read {
- color: #07c160;
- }
- .message-status .failed {
- color: #fa5151;
- }
- .message-time {
- display: block;
- text-align: right;
- font-size: 22rpx;
- color: #ccc;
- margin-top: 5rpx;
- }
- /* 输入框 */
- .input-bar {
- display: flex;
- align-items: center;
- padding: 20rpx;
- background-color: #fff;
- border-top: 1px solid #e5e5e5;
- }
- .input-icon {
- width: 80rpx;
- height: 80rpx;
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 50rpx;
- }
- .input-field {
- flex: 1;
- height: 70rpx;
- padding: 0 20rpx;
- background-color: #f5f5f5;
- border-radius: 8rpx;
- font-size: 30rpx;
- }
- .voice-button {
- flex: 1;
- height: 70rpx;
- line-height: 70rpx;
- background-color: #f5f5f5;
- border-radius: 8rpx;
- text-align: center;
- font-size: 30rpx;
- border: none;
- }
- /* 表情面板 */
- .emoji-panel {
- display: flex;
- flex-wrap: wrap;
- padding: 20rpx;
- background-color: #fff;
- border-top: 1px solid #e5e5e5;
- }
- .emoji-item {
- width: 80rpx;
- height: 80rpx;
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 60rpx;
- }
- /* 更多功能面板 */
- .more-panel {
- display: flex;
- padding: 40rpx;
- background-color: #fff;
- border-top: 1px solid #e5e5e5;
- }
- .more-item {
- display: flex;
- flex-direction: column;
- align-items: center;
- margin: 0 40rpx;
- }
- .more-icon {
- width: 100rpx;
- height: 100rpx;
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 60rpx;
- background-color: #f5f5f5;
- border-radius: 16rpx;
- margin-bottom: 10rpx;
- }
- .more-text {
- font-size: 24rpx;
- color: #666;
- }
- /* 时间分隔线 */
- .time-divider {
- text-align: center;
- padding: 20rpx 0;
- }
- .time-text {
- display: inline-block;
- padding: 8rpx 20rpx;
- background-color: rgba(0, 0, 0, 0.1);
- border-radius: 8rpx;
- font-size: 22rpx;
- color: #999;
- }
- /* 消息气泡失败状态 */
- .bubble-failed {
- opacity: 0.6;
- border: 2rpx solid #fa5151;
- }
- /* 消息状态优化 */
- .message-status .sending {
- color: #576b95;
- }
- .message-status .failed-group {
- display: flex;
- align-items: center;
- gap: 10rpx;
- }
- .message-status .retry-btn {
- color: #576b95;
- text-decoration: underline;
- cursor: pointer;
- }
- /* 消息操作菜单遮罩 */
- .message-action-mask {
- position: fixed;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- background-color: rgba(0, 0, 0, 0.4);
- z-index: 9999;
- display: flex;
- align-items: center;
- justify-content: center;
- }
- /* 消息操作菜单 */
- .message-action-menu {
- width: 600rpx;
- background-color: #fff;
- border-radius: 20rpx;
- overflow: hidden;
- }
- .message-action-menu .menu-item {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 15rpx;
- padding: 30rpx;
- font-size: 32rpx;
- color: #333;
- border-bottom: 1rpx solid #f0f0f0;
- transition: background-color 0.2s;
- }
- .message-action-menu .menu-item:active {
- background-color: #f5f5f5;
- }
- .message-action-menu .menu-item.cancel {
- color: #999;
- border-bottom: none;
- margin-top: 20rpx;
- border-top: 10rpx solid #f5f5f5;
- }
- .message-action-menu .menu-icon {
- font-size: 36rpx;
- }
- </style>
|