chat.vue 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  1. <template>
  2. <view class="chat-page">
  3. <!-- 顶部导航 -->
  4. <view class="chat-header">
  5. <view class="header-left" @click="goBack">
  6. <text class="icon-back">←</text>
  7. </view>
  8. <view class="header-center">
  9. <text class="chat-title">{{ targetUserName }}</text>
  10. <text class="online-status" :class="{ online: isTargetOnline }">
  11. {{ isTargetOnline ? '在线' : '离线' }}
  12. </text>
  13. </view>
  14. <view class="header-right">
  15. <text class="icon-more">⋯</text>
  16. </view>
  17. </view>
  18. <!-- 消息列表 -->
  19. <scroll-view
  20. class="message-list"
  21. scroll-y
  22. :scroll-into-view="scrollToView"
  23. @scrolltoupper="loadMoreMessages">
  24. <!-- 加载更多提示 -->
  25. <view v-if="loading" class="loading-tip">加载中...</view>
  26. <view v-else-if="noMore" class="loading-tip">没有更多消息了</view>
  27. <!-- 时间分组和消息项 -->
  28. <view v-for="(msg, index) in messages" :key="msg.messageId">
  29. <!-- 时间分隔线 (每5分钟显示一次) -->
  30. <view v-if="shouldShowTime(msg, index)" class="time-divider">
  31. <text class="time-text">{{ formatMessageTime(msg.sendTime) }}</text>
  32. </view>
  33. <!-- 消息项 -->
  34. <view
  35. :id="'msg-' + index"
  36. class="message-item"
  37. :class="{ 'message-self': msg.fromUserId === userId }"
  38. @longpress="showMessageMenu(msg, index)">
  39. <!-- 头像 -->
  40. <image
  41. class="avatar"
  42. :src="msg.fromUserId === userId ? userAvatar : targetUserAvatar"
  43. mode="aspectFill" />
  44. <!-- 消息内容 -->
  45. <view class="message-content-wrapper">
  46. <!-- 用户名(对方消息时显示) -->
  47. <text v-if="msg.fromUserId !== userId" class="message-name">
  48. {{ msg.fromUserName }}
  49. </text>
  50. <!-- 消息气泡 -->
  51. <view
  52. class="message-bubble"
  53. :class="{ 'bubble-self': msg.fromUserId === userId, 'bubble-failed': msg.sendStatus === 4 }"
  54. @click="handleMessageClick(msg)">
  55. <!-- 文本消息 -->
  56. <text v-if="msg.messageType === 1" class="message-text">
  57. {{ msg.content }}
  58. </text>
  59. <!-- 图片消息 -->
  60. <image
  61. v-else-if="msg.messageType === 2"
  62. class="message-image"
  63. :src="msg.mediaUrl"
  64. mode="widthFix"
  65. lazy-load
  66. @click.stop="previewImage(msg.mediaUrl)" />
  67. <!-- 语音消息 -->
  68. <view v-else-if="msg.messageType === 3" class="message-voice" @click.stop="playVoice(msg)">
  69. <text>🔊</text>
  70. <text>{{ msg.duration }}"</text>
  71. </view>
  72. <!-- 视频消息 -->
  73. <video
  74. v-else-if="msg.messageType === 4"
  75. class="message-video"
  76. :src="msg.mediaUrl"
  77. controls />
  78. <!-- 撤回消息 -->
  79. <text v-if="msg.isRecalled" class="message-recalled">
  80. 消息已撤回
  81. </text>
  82. </view>
  83. <!-- 消息状态(自己的消息) -->
  84. <view v-if="msg.fromUserId === userId" class="message-status">
  85. <text v-if="msg.sendStatus === 1" class="sending">发送中...</text>
  86. <text v-else-if="msg.sendStatus === 2">已送达</text>
  87. <text v-else-if="msg.sendStatus === 3" class="read">已读</text>
  88. <view v-else-if="msg.sendStatus === 4" class="failed-group">
  89. <text class="failed">发送失败</text>
  90. <text class="retry-btn" @click.stop="retryMessage(msg)">重试</text>
  91. </view>
  92. </view>
  93. </view>
  94. </view>
  95. </view>
  96. </scroll-view>
  97. <!-- 输入框 -->
  98. <view class="input-bar">
  99. <!-- 语音按钮 -->
  100. <view class="input-icon" @click="switchInputType">
  101. <text>{{ inputType === 'text' ? '🎤' : '⌨️' }}</text>
  102. </view>
  103. <!-- 文本输入 -->
  104. <input
  105. v-if="inputType === 'text'"
  106. class="input-field"
  107. v-model="inputText"
  108. placeholder="说点什么..."
  109. confirm-type="send"
  110. @confirm="sendTextMessage"
  111. @input="onInputChange" />
  112. <!-- 语音按钮 -->
  113. <button
  114. v-else
  115. class="voice-button"
  116. @touchstart="startVoiceRecord"
  117. @touchend="stopVoiceRecord">
  118. 按住说话
  119. </button>
  120. <!-- 表情按钮 -->
  121. <view class="input-icon" @click="showEmojiPanel = !showEmojiPanel">
  122. <text>😊</text>
  123. </view>
  124. <!-- 更多按钮 -->
  125. <view class="input-icon" @click="showMorePanel = !showMorePanel">
  126. <text>➕</text>
  127. </view>
  128. </view>
  129. <!-- 表情面板 -->
  130. <view v-if="showEmojiPanel" class="emoji-panel">
  131. <text
  132. v-for="emoji in emojis"
  133. :key="emoji"
  134. class="emoji-item"
  135. @click="insertEmoji(emoji)">
  136. {{ emoji }}
  137. </text>
  138. </view>
  139. <!-- 更多功能面板 -->
  140. <view v-if="showMorePanel" class="more-panel">
  141. <view class="more-item" @click="chooseImage">
  142. <view class="more-icon">🖼️</view>
  143. <text class="more-text">图片</text>
  144. </view>
  145. <view class="more-item" @click="chooseVideo">
  146. <view class="more-icon">📹</view>
  147. <text class="more-text">视频</text>
  148. </view>
  149. <view class="more-item" @click="chooseFile">
  150. <view class="more-icon">📁</view>
  151. <text class="more-text">文件</text>
  152. </view>
  153. </view>
  154. <!-- 消息操作菜单 -->
  155. <view v-if="showMessageAction" class="message-action-mask" @click="hideMessageMenu">
  156. <view class="message-action-menu" @click.stop>
  157. <view class="menu-item" @click="copyMessage" v-if="selectedMessage && selectedMessage.messageType === 1">
  158. <text class="menu-icon">📋</text>
  159. <text>复制</text>
  160. </view>
  161. <view class="menu-item" @click="recallMessage" v-if="selectedMessage && selectedMessage.fromUserId === userId && canRecall(selectedMessage)">
  162. <text class="menu-icon">↩️</text>
  163. <text>撤回</text>
  164. </view>
  165. <view class="menu-item" @click="deleteMessage">
  166. <text class="menu-icon">🗑️</text>
  167. <text>删除</text>
  168. </view>
  169. <view class="menu-item cancel" @click="hideMessageMenu">
  170. <text>取消</text>
  171. </view>
  172. </view>
  173. </view>
  174. </view>
  175. </template>
  176. <script>
  177. import timManager from '@/utils/tim-manager.js';
  178. import TIM from 'tim-wx-sdk';
  179. export default {
  180. data() {
  181. return {
  182. userId: null,
  183. userAvatar: '',
  184. targetUserId: null,
  185. targetUserName: '',
  186. targetUserAvatar: '',
  187. messages: [],
  188. inputText: '',
  189. inputType: 'text',
  190. conversationID: '',
  191. scrollToView: '',
  192. showEmojiPanel: false,
  193. showMorePanel: false,
  194. isLogin: false,
  195. // 消息操作菜单
  196. showMessageAction: false,
  197. selectedMessage: null,
  198. selectedMessageIndex: -1,
  199. menuTop: 0,
  200. // 加载更多
  201. loading: false,
  202. noMore: false,
  203. nextReqMessageID: '',
  204. isTargetOnline: false,
  205. emojis: ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩', '🥳']
  206. };
  207. },
  208. async onLoad(options) {
  209. console.log('=== 聊天页面加载 ===');
  210. // 严格验证登录状态
  211. const token = uni.getStorageSync('token');
  212. const userInfo = uni.getStorageSync('userInfo');
  213. const storedUserId = uni.getStorageSync('userId');
  214. console.log('登录状态检查:');
  215. console.log('- token:', token ? '存在' : '不存在');
  216. console.log('- userInfo:', userInfo);
  217. console.log('- storedUserId:', storedUserId);
  218. if (!token || !userInfo) {
  219. console.error('❌ 未登录或登录信息不完整');
  220. uni.showModal({
  221. title: '需要登录',
  222. content: '请先登录后再进行聊天',
  223. showCancel: false,
  224. success: () => {
  225. uni.reLaunch({
  226. url: '/pages/page3/page3'
  227. });
  228. }
  229. });
  230. return;
  231. }
  232. // 优先使用 storage 中的 userId,确保一致性
  233. let rawUserId = storedUserId || userInfo.userId || userInfo.id || userInfo.user_id;
  234. // 转换为数字类型(确保与消息列表页面一致)
  235. if (typeof rawUserId === 'string') {
  236. rawUserId = parseInt(rawUserId);
  237. }
  238. if (!rawUserId || isNaN(rawUserId)) {
  239. console.error('❌ 无法获取有效的用户ID');
  240. uni.showModal({
  241. title: '用户信息错误',
  242. content: '无法获取用户ID,请重新登录',
  243. showCancel: false,
  244. success: () => {
  245. uni.removeStorageSync('token');
  246. uni.removeStorageSync('userInfo');
  247. uni.removeStorageSync('userId');
  248. uni.reLaunch({
  249. url: '/pages/page3/page3'
  250. });
  251. }
  252. });
  253. return;
  254. }
  255. // 保存用户ID(TIM需要字符串格式)
  256. this.userId = String(rawUserId);
  257. this.userAvatar = userInfo.avatar || userInfo.avatarUrl || '/static/default-avatar.svg';
  258. // 获取对方用户信息(确保是字符串格式)
  259. this.targetUserId = String(options.targetUserId);
  260. this.targetUserName = decodeURIComponent(options.targetUserName || '用户');
  261. this.targetUserAvatar = decodeURIComponent(options.targetUserAvatar || '/static/default-avatar.svg');
  262. // 生成会话 ID
  263. this.conversationID = `C2C${this.targetUserId}`;
  264. console.log('✅ 聊天页面初始化成功:');
  265. console.log(' - 当前用户ID:', rawUserId, '(TIM格式:', this.userId, ')');
  266. console.log(' - 对方用户ID:', this.targetUserId);
  267. console.log(' - 会话ID:', this.conversationID);
  268. // 初始化 TIM
  269. await this.initTIM();
  270. // 等待 SDK Ready 后再加载消息
  271. await this.waitForSDKReady();
  272. // 加载历史消息
  273. await this.loadMessages();
  274. // 监听新消息
  275. this.listenMessages();
  276. },
  277. onUnload() {
  278. // 页面卸载时移除监听
  279. timManager.offMessage(this.handleNewMessage);
  280. },
  281. methods: {
  282. /**
  283. * 初始化 TIM
  284. */
  285. async initTIM() {
  286. try {
  287. // 如果未初始化,先初始化
  288. if (!timManager.tim) {
  289. timManager.init(1600109674); // ✅ 已更新为正确的 SDKAppID
  290. }
  291. // 如果未登录,获取 userSig 并登录
  292. if (!timManager.isLogin) {
  293. // 先导入当前用户和目标用户到腾讯云IM
  294. await this.importUsers();
  295. // 从后端获取 userSig
  296. const userSig = await this.getUserSig();
  297. await timManager.login(this.userId, userSig);
  298. }
  299. this.isLogin = true;
  300. console.log('✅ TIM 初始化完成');
  301. } catch (error) {
  302. console.error('❌ TIM 初始化失败:', error);
  303. uni.showToast({
  304. title: '连接失败,请重试',
  305. icon: 'none'
  306. });
  307. }
  308. },
  309. /**
  310. * 导入用户到腾讯云IM
  311. */
  312. async importUsers() {
  313. try {
  314. console.log('📥 开始导入用户到腾讯云IM...');
  315. console.log(' - 当前用户ID:', this.userId, '(类型:', typeof this.userId, ')');
  316. console.log(' - 目标用户ID:', this.targetUserId, '(类型:', typeof this.targetUserId, ')');
  317. // 验证用户ID
  318. if (!this.userId || this.userId === 'undefined' || this.userId === 'null') {
  319. throw new Error('当前用户ID无效: ' + this.userId);
  320. }
  321. if (!this.targetUserId || this.targetUserId === 'undefined' || this.targetUserId === 'null') {
  322. throw new Error('目标用户ID无效: ' + this.targetUserId);
  323. }
  324. // 导入当前用户(确保userId是字符串)
  325. const currentUserRes = await uni.request({
  326. url: 'http://localhost:1004/api/im/importUser',
  327. method: 'POST',
  328. data: {
  329. userId: String(this.userId),
  330. nickname: '用户' + this.userId
  331. },
  332. header: {
  333. 'Content-Type': 'application/json'
  334. }
  335. });
  336. console.log(' - 当前用户导入结果:', currentUserRes[1].data);
  337. // 导入目标用户(确保userId是字符串)
  338. const targetUserRes = await uni.request({
  339. url: 'http://localhost:1004/api/im/importUser',
  340. method: 'POST',
  341. data: {
  342. userId: String(this.targetUserId),
  343. nickname: this.targetUserName || '用户' + this.targetUserId
  344. },
  345. header: {
  346. 'Content-Type': 'application/json'
  347. }
  348. });
  349. console.log(' - 目标用户导入结果:', targetUserRes[1].data);
  350. console.log('✅ 用户导入成功');
  351. } catch (error) {
  352. console.log('⚠️ 用户导入失败(可能已存在):', error);
  353. // 导入失败不影响登录,因为用户可能已经存在
  354. }
  355. },
  356. /**
  357. * 获取 UserSig
  358. */
  359. async getUserSig() {
  360. try {
  361. const [err, res] = await uni.request({
  362. url: 'http://localhost:1004/api/im/getUserSig',
  363. method: 'GET',
  364. data: {
  365. userId: this.userId
  366. }
  367. });
  368. if (err) {
  369. throw new Error('请求失败');
  370. }
  371. if (res.data && res.data.code === 200) {
  372. return res.data.data.userSig;
  373. } else {
  374. throw new Error('获取 UserSig 失败');
  375. }
  376. } catch (error) {
  377. console.error('❌ 获取 UserSig 失败:', error);
  378. throw error;
  379. }
  380. },
  381. /**
  382. * 等待 SDK Ready
  383. */
  384. async waitForSDKReady() {
  385. return new Promise((resolve) => {
  386. // 如果已经 ready,立即返回
  387. if (timManager.isLogin) {
  388. console.log('✅ SDK 已就绪');
  389. resolve();
  390. return;
  391. }
  392. // 否则等待 SDK ready 事件
  393. console.log('⏳ 等待 SDK 就绪...');
  394. const checkReady = setInterval(() => {
  395. if (timManager.isLogin) {
  396. console.log('✅ SDK 已就绪');
  397. clearInterval(checkReady);
  398. resolve();
  399. }
  400. }, 100); // 每 100ms 检查一次
  401. // 超时保护(10秒后强制继续)
  402. setTimeout(() => {
  403. console.log('⚠️ 等待 SDK 就绪超时,继续执行');
  404. clearInterval(checkReady);
  405. resolve();
  406. }, 10000);
  407. });
  408. },
  409. /**
  410. * 加载历史消息
  411. */
  412. async loadMessages() {
  413. try {
  414. const res = await timManager.tim.getMessageList({
  415. conversationID: this.conversationID,
  416. count: 20
  417. });
  418. const messageList = res.data.messageList;
  419. this.nextReqMessageID = res.data.nextReqMessageID;
  420. this.noMore = !res.data.isCompleted;
  421. // 转换为我们的消息格式
  422. this.messages = messageList.map(msg => this.convertMessage(msg));
  423. // 滚动到底部
  424. this.$nextTick(() => {
  425. this.scrollToBottom();
  426. });
  427. // 标记已读
  428. await timManager.setMessageRead(this.conversationID);
  429. } catch (error) {
  430. console.error('❌ 加载消息失败:', error);
  431. }
  432. },
  433. /**
  434. * 加载更多消息(上拉)
  435. */
  436. async loadMoreMessages() {
  437. if (this.loading || !this.nextReqMessageID) {
  438. return;
  439. }
  440. this.loading = true;
  441. try {
  442. const res = await timManager.tim.getMessageList({
  443. conversationID: this.conversationID,
  444. nextReqMessageID: this.nextReqMessageID,
  445. count: 20
  446. });
  447. const messageList = res.data.messageList;
  448. this.nextReqMessageID = res.data.nextReqMessageID;
  449. this.noMore = !res.data.isCompleted;
  450. // 转换并添加到消息列表前面
  451. const newMessages = messageList.map(msg => this.convertMessage(msg));
  452. this.messages = [...newMessages, ...this.messages];
  453. } catch (error) {
  454. console.error('❌ 加载更多消息失败:', error);
  455. } finally {
  456. this.loading = false;
  457. }
  458. },
  459. /**
  460. * 监听新消息
  461. */
  462. listenMessages() {
  463. const handleNewMessage = (messageList) => {
  464. messageList.forEach(msg => {
  465. // 只处理当前会话的消息
  466. if (msg.conversationID === this.conversationID) {
  467. this.messages.push(this.convertMessage(msg));
  468. this.$nextTick(() => {
  469. this.scrollToBottom();
  470. });
  471. // 标记已读
  472. timManager.setMessageRead(this.conversationID);
  473. }
  474. });
  475. };
  476. this.handleNewMessage = handleNewMessage;
  477. timManager.onMessage(handleNewMessage);
  478. },
  479. /**
  480. * 转换消息格式
  481. */
  482. convertMessage(timMsg) {
  483. return {
  484. messageId: timMsg.ID,
  485. fromUserId: timMsg.from,
  486. toUserId: timMsg.to,
  487. messageType: timMsg.type === TIM.TYPES.MSG_TEXT ? 1 : 2,
  488. content: timMsg.type === TIM.TYPES.MSG_TEXT ? timMsg.payload.text : '[图片]',
  489. mediaUrl: timMsg.type === TIM.TYPES.MSG_IMAGE ? timMsg.payload.imageInfoArray[0].url : '',
  490. sendStatus: timMsg.status === 'success' ? 2 : 1,
  491. sendTime: new Date(timMsg.time * 1000),
  492. isRecalled: timMsg.isRevoked,
  493. fromUserName: timMsg.from === this.userId ? '我' : this.targetUserName
  494. };
  495. },
  496. /**
  497. * 发送文本消息
  498. */
  499. async sendTextMessage() {
  500. if (!this.inputText.trim()) {
  501. return;
  502. }
  503. const content = this.inputText;
  504. this.inputText = '';
  505. try {
  506. const message = await timManager.sendTextMessage(this.targetUserId, content);
  507. // 添加到消息列表
  508. this.messages.push(this.convertMessage(message));
  509. this.scrollToBottom();
  510. console.log('✅ 消息发送成功');
  511. // 同步消息到MySQL数据库(双重保障)
  512. this.syncMessageToMySQL(message);
  513. } catch (error) {
  514. console.error('❌ 消息发送失败:', error);
  515. uni.showToast({
  516. title: '发送失败',
  517. icon: 'none'
  518. });
  519. // 失败时恢复输入框内容
  520. this.inputText = content;
  521. }
  522. },
  523. /**
  524. * 选择图片
  525. */
  526. chooseImage() {
  527. uni.chooseImage({
  528. count: 1,
  529. sizeType: ['compressed'],
  530. sourceType: ['album', 'camera'],
  531. success: async (res) => {
  532. const tempFilePath = res.tempFilePaths[0];
  533. try {
  534. uni.showLoading({ title: '发送中...' });
  535. const message = await timManager.sendImageMessage(this.targetUserId, tempFilePath);
  536. this.messages.push(this.convertMessage(message));
  537. this.scrollToBottom();
  538. uni.hideLoading();
  539. console.log('✅ 图片发送成功');
  540. } catch (error) {
  541. uni.hideLoading();
  542. console.error('❌ 图片发送失败:', error);
  543. uni.showToast({
  544. title: '发送失败',
  545. icon: 'none'
  546. });
  547. }
  548. }
  549. });
  550. this.showMorePanel = false;
  551. },
  552. /**
  553. * 输入框内容变化
  554. */
  555. onInputChange() {
  556. // 腾讯云 IM 可以实现正在输入状态,这里暂时省略
  557. console.log('输入中...');
  558. },
  559. /**
  560. * 同步消息到MySQL数据库(双重存储保障)
  561. */
  562. async syncMessageToMySQL(timMessage) {
  563. try {
  564. console.log('🔄 同步消息到MySQL...', timMessage.ID);
  565. // 构建同步参数
  566. const syncData = {
  567. messageId: timMessage.ID,
  568. fromUserId: timMessage.from,
  569. toUserId: timMessage.to,
  570. messageType: this.getMessageType(timMessage),
  571. content: this.getMessageContent(timMessage),
  572. sendTime: timMessage.time // TIM返回的是秒级时间戳
  573. };
  574. // 如果是图片消息,添加媒体信息
  575. if (timMessage.type === 'TIMImageElem' && timMessage.payload.imageInfoArray) {
  576. const imageInfo = timMessage.payload.imageInfoArray[0];
  577. syncData.mediaUrl = imageInfo.imageUrl;
  578. syncData.thumbnailUrl = imageInfo.imageUrl;
  579. }
  580. // 调用后端同步接口
  581. const res = await uni.request({
  582. url: 'http://localhost:1004/api/chat/syncTIMMessage',
  583. method: 'POST',
  584. data: syncData,
  585. header: {
  586. 'Content-Type': 'application/json'
  587. }
  588. });
  589. if (res[1].data.code === 200) {
  590. console.log('✅ 消息已同步到MySQL:', timMessage.ID);
  591. } else {
  592. console.warn('⚠️ 消息同步失败:', res[1].data.message);
  593. }
  594. } catch (error) {
  595. console.error('❌ 同步消息到MySQL失败:', error);
  596. // 同步失败不影响聊天功能,只记录日志
  597. }
  598. },
  599. /**
  600. * 获取消息类型
  601. */
  602. getMessageType(timMessage) {
  603. const typeMap = {
  604. 'TIMTextElem': 1, // 文本
  605. 'TIMImageElem': 2, // 图片
  606. 'TIMSoundElem': 3, // 语音
  607. 'TIMVideoFileElem': 4, // 视频
  608. 'TIMFileElem': 5 // 文件
  609. };
  610. return typeMap[timMessage.type] || 1;
  611. },
  612. /**
  613. * 获取消息内容
  614. */
  615. getMessageContent(timMessage) {
  616. switch (timMessage.type) {
  617. case 'TIMTextElem':
  618. return timMessage.payload.text || '';
  619. case 'TIMImageElem':
  620. return '[图片]';
  621. case 'TIMSoundElem':
  622. return '[语音]';
  623. case 'TIMVideoFileElem':
  624. return '[视频]';
  625. case 'TIMFileElem':
  626. return '[文件]';
  627. default:
  628. return '[未知消息]';
  629. }
  630. },
  631. /**
  632. * 滚动到底部
  633. */
  634. scrollToBottom() {
  635. this.$nextTick(() => {
  636. const lastIndex = this.messages.length - 1;
  637. this.scrollToView = 'msg-' + lastIndex;
  638. });
  639. },
  640. /**
  641. * 判断是否显示时间分隔线
  642. */
  643. shouldShowTime(msg, index) {
  644. if (index === 0) return true;
  645. const prevMsg = this.messages[index - 1];
  646. const timeDiff = new Date(msg.sendTime) - new Date(prevMsg.sendTime);
  647. // 超过5分钟显示时间
  648. return timeDiff > 5 * 60 * 1000;
  649. },
  650. /**
  651. * 格式化消息时间(用于时间分隔线)
  652. */
  653. formatMessageTime(time) {
  654. const date = new Date(time);
  655. const now = new Date();
  656. const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  657. const yesterday = new Date(today - 86400000);
  658. // 今天
  659. if (date >= today) {
  660. return date.toLocaleTimeString('zh-CN', {
  661. hour: '2-digit',
  662. minute: '2-digit'
  663. });
  664. }
  665. // 昨天
  666. if (date >= yesterday) {
  667. return '昨天 ' + date.toLocaleTimeString('zh-CN', {
  668. hour: '2-digit',
  669. minute: '2-digit'
  670. });
  671. }
  672. // 本周
  673. if (date > new Date(now - 7 * 86400000)) {
  674. const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  675. return days[date.getDay()] + ' ' + date.toLocaleTimeString('zh-CN', {
  676. hour: '2-digit',
  677. minute: '2-digit'
  678. });
  679. }
  680. // 更早
  681. return date.toLocaleString('zh-CN', {
  682. month: '2-digit',
  683. day: '2-digit',
  684. hour: '2-digit',
  685. minute: '2-digit'
  686. });
  687. },
  688. /**
  689. * 格式化时间(消息状态用)
  690. */
  691. formatTime(time) {
  692. const date = new Date(time);
  693. const now = new Date();
  694. const diff = now - date;
  695. if (diff < 60000) {
  696. return '刚刚';
  697. } else if (diff < 3600000) {
  698. return Math.floor(diff / 60000) + '分钟前';
  699. } else if (diff < 86400000) {
  700. return Math.floor(diff / 3600000) + '小时前';
  701. } else {
  702. return date.toLocaleString('zh-CN', {
  703. month: '2-digit',
  704. day: '2-digit',
  705. hour: '2-digit',
  706. minute: '2-digit'
  707. });
  708. }
  709. },
  710. /**
  711. * 预览图片
  712. */
  713. previewImage(url) {
  714. uni.previewImage({
  715. urls: [url],
  716. current: url
  717. });
  718. },
  719. /**
  720. * 返回
  721. */
  722. goBack() {
  723. uni.navigateBack({
  724. success: () => {
  725. // 通知消息列表页面刷新
  726. uni.$emit('refreshConversations');
  727. }
  728. });
  729. },
  730. /**
  731. * 显示消息操作菜单
  732. */
  733. showMessageMenu(msg, index) {
  734. this.selectedMessage = msg;
  735. this.selectedMessageIndex = index;
  736. this.showMessageAction = true;
  737. // 计算菜单位置
  738. uni.createSelectorQuery().select('.message-item').boundingClientRect(rect => {
  739. if (rect) {
  740. this.menuTop = rect.top + rect.height;
  741. }
  742. }).exec();
  743. },
  744. /**
  745. * 隐藏消息操作菜单
  746. */
  747. hideMessageMenu() {
  748. this.showMessageAction = false;
  749. this.selectedMessage = null;
  750. this.selectedMessageIndex = -1;
  751. },
  752. /**
  753. * 复制消息
  754. */
  755. copyMessage() {
  756. if (!this.selectedMessage || this.selectedMessage.messageType !== 1) {
  757. return;
  758. }
  759. uni.setClipboardData({
  760. data: this.selectedMessage.content,
  761. success: () => {
  762. uni.showToast({
  763. title: '已复制',
  764. icon: 'success'
  765. });
  766. }
  767. });
  768. this.hideMessageMenu();
  769. },
  770. /**
  771. * 判断是否可以撤回
  772. */
  773. canRecall(msg) {
  774. const diff = Date.now() - new Date(msg.sendTime).getTime();
  775. return diff < 2 * 60 * 1000; // 2分钟内可撤回
  776. },
  777. /**
  778. * 撤回消息
  779. */
  780. async recallMessage() {
  781. if (!this.selectedMessage) {
  782. return;
  783. }
  784. try {
  785. // 查找TIM消息对象
  786. const timMessage = await timManager.tim.findMessage(this.selectedMessage.messageId);
  787. if (timMessage) {
  788. await timManager.revokeMessage(timMessage);
  789. // 更新本地消息状态
  790. this.selectedMessage.isRecalled = true;
  791. this.selectedMessage.content = '你撤回了一条消息';
  792. uni.showToast({
  793. title: '已撤回',
  794. icon: 'success'
  795. });
  796. }
  797. } catch (error) {
  798. console.error('撤回失败:', error);
  799. uni.showToast({
  800. title: '撤回失败',
  801. icon: 'none'
  802. });
  803. }
  804. this.hideMessageMenu();
  805. },
  806. /**
  807. * 删除消息
  808. */
  809. deleteMessage() {
  810. if (!this.selectedMessage) {
  811. return;
  812. }
  813. uni.showModal({
  814. title: '确认删除',
  815. content: '确定要删除这条消息吗?',
  816. success: (res) => {
  817. if (res.confirm) {
  818. // 从列表中删除
  819. this.messages.splice(this.selectedMessageIndex, 1);
  820. uni.showToast({
  821. title: '已删除',
  822. icon: 'success'
  823. });
  824. }
  825. }
  826. });
  827. this.hideMessageMenu();
  828. },
  829. /**
  830. * 处理消息点击
  831. */
  832. handleMessageClick(msg) {
  833. // 如果是发送失败的消息,提示重试
  834. if (msg.sendStatus === 4) {
  835. uni.showModal({
  836. title: '发送失败',
  837. content: '消息发送失败,是否重试?',
  838. success: (res) => {
  839. if (res.confirm) {
  840. this.retryMessage(msg);
  841. }
  842. }
  843. });
  844. }
  845. },
  846. /**
  847. * 重试发送消息
  848. */
  849. async retryMessage(msg) {
  850. if (msg.messageType !== 1) {
  851. uni.showToast({
  852. title: '暂不支持重发该类型消息',
  853. icon: 'none'
  854. });
  855. return;
  856. }
  857. try {
  858. // 更新状态为发送中
  859. msg.sendStatus = 1;
  860. // 重新发送
  861. const message = await timManager.sendTextMessage(this.targetUserId, msg.content);
  862. // 更新消息
  863. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  864. if (index > -1) {
  865. this.messages[index] = this.convertMessage(message);
  866. }
  867. console.log('✅ 消息重发成功');
  868. } catch (error) {
  869. console.error('❌ 消息重发失败:', error);
  870. msg.sendStatus = 4;
  871. uni.showToast({
  872. title: '发送失败',
  873. icon: 'none'
  874. });
  875. }
  876. },
  877. // 其他功能方法
  878. switchInputType() {
  879. this.inputType = this.inputType === 'text' ? 'voice' : 'text';
  880. },
  881. startVoiceRecord() {
  882. uni.showToast({
  883. title: '按住说话',
  884. icon: 'none'
  885. });
  886. },
  887. stopVoiceRecord() {
  888. uni.showToast({
  889. title: '语音功能开发中',
  890. icon: 'none'
  891. });
  892. },
  893. insertEmoji(emoji) {
  894. this.inputText += emoji;
  895. this.showEmojiPanel = false;
  896. },
  897. chooseVideo() {
  898. uni.showToast({
  899. title: '视频功能开发中',
  900. icon: 'none'
  901. });
  902. this.showMorePanel = false;
  903. },
  904. chooseFile() {
  905. uni.showToast({
  906. title: '文件功能开发中',
  907. icon: 'none'
  908. });
  909. this.showMorePanel = false;
  910. },
  911. playVoice() {
  912. uni.showToast({
  913. title: '语音播放功能开发中',
  914. icon: 'none'
  915. });
  916. }
  917. }
  918. };
  919. </script>
  920. <style scoped>
  921. .chat-page {
  922. display: flex;
  923. flex-direction: column;
  924. height: 100vh;
  925. background-color: #f5f5f5;
  926. }
  927. /* 顶部导航 */
  928. .chat-header {
  929. display: flex;
  930. align-items: center;
  931. justify-content: space-between;
  932. padding: 20rpx 30rpx;
  933. background-color: #fff;
  934. border-bottom: 1px solid #e5e5e5;
  935. }
  936. .header-left, .header-right {
  937. width: 80rpx;
  938. }
  939. .icon-back, .icon-more {
  940. font-size: 40rpx;
  941. }
  942. .header-center {
  943. flex: 1;
  944. text-align: center;
  945. }
  946. .chat-title {
  947. display: block;
  948. font-size: 36rpx;
  949. font-weight: bold;
  950. }
  951. .online-status {
  952. display: block;
  953. font-size: 24rpx;
  954. color: #999;
  955. margin-top: 5rpx;
  956. }
  957. .online-status.online {
  958. color: #07c160;
  959. }
  960. /* 消息列表 */
  961. .message-list {
  962. flex: 1;
  963. padding: 20rpx;
  964. overflow-y: scroll;
  965. }
  966. .loading-tip {
  967. text-align: center;
  968. padding: 20rpx;
  969. color: #999;
  970. font-size: 28rpx;
  971. }
  972. .message-item {
  973. display: flex;
  974. margin-bottom: 30rpx;
  975. }
  976. .message-item.message-self {
  977. flex-direction: row-reverse;
  978. }
  979. .avatar {
  980. width: 80rpx;
  981. height: 80rpx;
  982. border-radius: 8rpx;
  983. margin: 0 20rpx;
  984. }
  985. .message-content-wrapper {
  986. max-width: 70%;
  987. }
  988. .message-name {
  989. display: block;
  990. font-size: 24rpx;
  991. color: #999;
  992. margin-bottom: 10rpx;
  993. }
  994. .message-bubble {
  995. padding: 20rpx;
  996. border-radius: 8rpx;
  997. background-color: #fff;
  998. word-wrap: break-word;
  999. }
  1000. .message-self .message-bubble {
  1001. background-color: #95ec69;
  1002. }
  1003. .message-bubble.bubble-self {
  1004. background-color: #95ec69;
  1005. }
  1006. .message-text {
  1007. font-size: 30rpx;
  1008. line-height: 1.5;
  1009. }
  1010. .message-image {
  1011. max-width: 400rpx;
  1012. border-radius: 8rpx;
  1013. }
  1014. .message-voice {
  1015. display: flex;
  1016. align-items: center;
  1017. gap: 10rpx;
  1018. }
  1019. .message-video {
  1020. width: 400rpx;
  1021. height: 300rpx;
  1022. }
  1023. .message-recalled {
  1024. color: #999;
  1025. font-size: 28rpx;
  1026. }
  1027. .message-status {
  1028. text-align: right;
  1029. font-size: 24rpx;
  1030. color: #999;
  1031. margin-top: 5rpx;
  1032. }
  1033. .message-status .read {
  1034. color: #07c160;
  1035. }
  1036. .message-status .failed {
  1037. color: #fa5151;
  1038. }
  1039. .message-time {
  1040. display: block;
  1041. text-align: right;
  1042. font-size: 22rpx;
  1043. color: #ccc;
  1044. margin-top: 5rpx;
  1045. }
  1046. /* 输入框 */
  1047. .input-bar {
  1048. display: flex;
  1049. align-items: center;
  1050. padding: 20rpx;
  1051. background-color: #fff;
  1052. border-top: 1px solid #e5e5e5;
  1053. }
  1054. .input-icon {
  1055. width: 80rpx;
  1056. height: 80rpx;
  1057. display: flex;
  1058. align-items: center;
  1059. justify-content: center;
  1060. font-size: 50rpx;
  1061. }
  1062. .input-field {
  1063. flex: 1;
  1064. height: 70rpx;
  1065. padding: 0 20rpx;
  1066. background-color: #f5f5f5;
  1067. border-radius: 8rpx;
  1068. font-size: 30rpx;
  1069. }
  1070. .voice-button {
  1071. flex: 1;
  1072. height: 70rpx;
  1073. line-height: 70rpx;
  1074. background-color: #f5f5f5;
  1075. border-radius: 8rpx;
  1076. text-align: center;
  1077. font-size: 30rpx;
  1078. border: none;
  1079. }
  1080. /* 表情面板 */
  1081. .emoji-panel {
  1082. display: flex;
  1083. flex-wrap: wrap;
  1084. padding: 20rpx;
  1085. background-color: #fff;
  1086. border-top: 1px solid #e5e5e5;
  1087. }
  1088. .emoji-item {
  1089. width: 80rpx;
  1090. height: 80rpx;
  1091. display: flex;
  1092. align-items: center;
  1093. justify-content: center;
  1094. font-size: 60rpx;
  1095. }
  1096. /* 更多功能面板 */
  1097. .more-panel {
  1098. display: flex;
  1099. padding: 40rpx;
  1100. background-color: #fff;
  1101. border-top: 1px solid #e5e5e5;
  1102. }
  1103. .more-item {
  1104. display: flex;
  1105. flex-direction: column;
  1106. align-items: center;
  1107. margin: 0 40rpx;
  1108. }
  1109. .more-icon {
  1110. width: 100rpx;
  1111. height: 100rpx;
  1112. display: flex;
  1113. align-items: center;
  1114. justify-content: center;
  1115. font-size: 60rpx;
  1116. background-color: #f5f5f5;
  1117. border-radius: 16rpx;
  1118. margin-bottom: 10rpx;
  1119. }
  1120. .more-text {
  1121. font-size: 24rpx;
  1122. color: #666;
  1123. }
  1124. /* 时间分隔线 */
  1125. .time-divider {
  1126. text-align: center;
  1127. padding: 20rpx 0;
  1128. }
  1129. .time-text {
  1130. display: inline-block;
  1131. padding: 8rpx 20rpx;
  1132. background-color: rgba(0, 0, 0, 0.1);
  1133. border-radius: 8rpx;
  1134. font-size: 22rpx;
  1135. color: #999;
  1136. }
  1137. /* 消息气泡失败状态 */
  1138. .bubble-failed {
  1139. opacity: 0.6;
  1140. border: 2rpx solid #fa5151;
  1141. }
  1142. /* 消息状态优化 */
  1143. .message-status .sending {
  1144. color: #576b95;
  1145. }
  1146. .message-status .failed-group {
  1147. display: flex;
  1148. align-items: center;
  1149. gap: 10rpx;
  1150. }
  1151. .message-status .retry-btn {
  1152. color: #576b95;
  1153. text-decoration: underline;
  1154. cursor: pointer;
  1155. }
  1156. /* 消息操作菜单遮罩 */
  1157. .message-action-mask {
  1158. position: fixed;
  1159. top: 0;
  1160. left: 0;
  1161. right: 0;
  1162. bottom: 0;
  1163. background-color: rgba(0, 0, 0, 0.4);
  1164. z-index: 9999;
  1165. display: flex;
  1166. align-items: center;
  1167. justify-content: center;
  1168. }
  1169. /* 消息操作菜单 */
  1170. .message-action-menu {
  1171. width: 600rpx;
  1172. background-color: #fff;
  1173. border-radius: 20rpx;
  1174. overflow: hidden;
  1175. }
  1176. .message-action-menu .menu-item {
  1177. display: flex;
  1178. align-items: center;
  1179. justify-content: center;
  1180. gap: 15rpx;
  1181. padding: 30rpx;
  1182. font-size: 32rpx;
  1183. color: #333;
  1184. border-bottom: 1rpx solid #f0f0f0;
  1185. transition: background-color 0.2s;
  1186. }
  1187. .message-action-menu .menu-item:active {
  1188. background-color: #f5f5f5;
  1189. }
  1190. .message-action-menu .menu-item.cancel {
  1191. color: #999;
  1192. border-bottom: none;
  1193. margin-top: 20rpx;
  1194. border-top: 10rpx solid #f5f5f5;
  1195. }
  1196. .message-action-menu .menu-icon {
  1197. font-size: 36rpx;
  1198. }
  1199. </style>