chat.vue 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834
  1. <template>
  2. <view class="chat-page">
  3. <!-- 更多选项弹窗 -->
  4. <view v-if="showMoreOptionsModal" class="modal-mask" @click="closeMoreOptions">
  5. <view class="modal-content" @click.stop>
  6. <view class="modal-header">
  7. <text class="modal-title">{{ targetUserName }}</text>
  8. <text class="modal-subtitle">好友操作</text>
  9. </view>
  10. <view class="modal-body">
  11. <!-- <view class="modal-item" @click="goToUserProfile">
  12. <text class="item-icon">👤</text>
  13. <text class="item-text">查看资料</text>
  14. </view> -->
  15. <view class="modal-item" @click="blockFriend" :class="{ danger: true }">
  16. <text class="item-icon">🚫</text>
  17. <text class="item-text">拉黑好友</text>
  18. </view>
  19. <!-- <view class="modal-item" @click="reportUser" :class="{ danger: true }">
  20. <text class="item-icon">🚨</text>
  21. <text class="item-text">举报用户</text>
  22. </view> -->
  23. </view>
  24. <view class="modal-footer">
  25. <button class="modal-close-btn" @click="closeMoreOptions">取消</button>
  26. </view>
  27. </view>
  28. </view>
  29. <!-- 拉黑确认弹窗 -->
  30. <view v-if="showBlockConfirmModal" class="modal-mask" @click="closeBlockConfirm">
  31. <view class="confirm-modal" @click.stop>
  32. <view class="confirm-title">确认拉黑</view>
  33. <view class="confirm-content">
  34. <text>拉黑后将无法接收该用户的消息,是否确定?</text>
  35. </view>
  36. <view class="confirm-buttons">
  37. <button class="confirm-btn cancel" @click="closeBlockConfirm">取消</button>
  38. <button class="confirm-btn confirm" @click="confirmBlockFriend">确认</button>
  39. </view>
  40. </view>
  41. </view>
  42. <!-- 顶部导航 -->
  43. <view class="chat-header">
  44. <view class="header-left" @click="goBack">
  45. <text class="icon-back">←</text>
  46. </view>
  47. <view class="header-center">
  48. <text class="chat-title">{{ targetUserName }}</text>
  49. <text class="online-status" :class="{ online: isTargetOnline }">
  50. {{ isTargetOnline ? '在线' : '离线' }}
  51. </text>
  52. </view>
  53. <view class="header-right" @click="showMoreOptions">
  54. <text class="icon-more">⋯</text>
  55. </view>
  56. </view>
  57. <!-- 消息列表 -->
  58. <scroll-view
  59. class="message-list"
  60. scroll-y
  61. :scroll-into-view="scrollToView"
  62. @scrolltoupper="loadMoreMessages">
  63. <!-- 加载更多提示 -->
  64. <view v-if="loading" class="loading-tip">加载中...</view>
  65. <view v-else-if="noMore" class="loading-tip">没有更多消息了</view>
  66. <!-- 时间分组和消息项 -->
  67. <view v-for="(msg, index) in messages" :key="msg.messageId">
  68. <!-- 时间分隔线 (每5分钟显示一次) -->
  69. <view v-if="shouldShowTime(msg, index)" class="time-divider">
  70. <text class="time-text">{{ formatMessageTime(msg.sendTime) }}</text>
  71. </view>
  72. <!-- 消息项 -->
  73. <view
  74. :id="'msg-' + index"
  75. class="message-item"
  76. :class="{ 'message-self': msg.fromUserId === userId }"
  77. @longpress="showMessageMenu(msg, index)">
  78. <!-- 头像 -->
  79. <image
  80. class="avatar"
  81. :src="msg.fromUserId === userId ? userAvatar : targetUserAvatar"
  82. mode="aspectFill" />
  83. <!-- 消息内容 -->
  84. <view class="message-content-wrapper">
  85. <!-- 用户名(对方消息时显示) -->
  86. <text v-if="msg.fromUserId !== userId" class="message-name">
  87. {{ msg.fromUserName }}
  88. </text>
  89. <!-- 消息气泡 -->
  90. <view
  91. class="message-bubble"
  92. :class="{ 'bubble-self': msg.fromUserId === userId, 'bubble-failed': msg.sendStatus === 4 }"
  93. @click="handleMessageClick(msg)">
  94. <!-- 文本消息 -->
  95. <text v-if="msg.messageType === 1" class="message-text">
  96. {{ msg.content }}
  97. </text>
  98. <!-- 图片消息 -->
  99. <image
  100. v-else-if="msg.messageType === 2"
  101. class="message-image"
  102. :src="msg.mediaUrl"
  103. mode="widthFix"
  104. lazy-load
  105. @click.stop="previewImage(msg.mediaUrl)" />
  106. <!-- 语音消息 -->
  107. <view v-else-if="msg.messageType === 3" class="message-voice" @click.stop="playVoice(msg)">
  108. <text>🔊</text>
  109. <text>{{ msg.duration }}"</text>
  110. </view>
  111. <!-- 视频消息 -->
  112. <video
  113. v-else-if="msg.messageType === 4"
  114. class="message-video"
  115. :src="msg.mediaUrl"
  116. controls />
  117. <!-- 撤回消息 -->
  118. <text v-if="msg.isRecalled" class="message-recalled">
  119. 消息已撤回
  120. </text>
  121. </view>
  122. <!-- 消息状态(自己的消息) -->
  123. <view v-if="msg.fromUserId === userId" class="message-status">
  124. <text v-if="msg.sendStatus === 1" class="sending">发送中...</text>
  125. <text v-else-if="msg.sendStatus === 2">已送达</text>
  126. <text v-else-if="msg.sendStatus === 3" class="read">已读</text>
  127. <view v-else-if="msg.sendStatus === 4" class="failed-group">
  128. <text class="failed">发送失败</text>
  129. <text class="retry-btn" @click.stop="retryMessage(msg)">重试</text>
  130. </view>
  131. </view>
  132. </view>
  133. </view>
  134. </view>
  135. </scroll-view>
  136. <!-- 输入框 -->
  137. <view class="input-bar">
  138. <!-- 语音按钮 -->
  139. <view class="input-icon" @click="switchInputType">
  140. <text>{{ inputType === 'text' ? '🎤' : '⌨️' }}</text>
  141. </view>
  142. <!-- 文本输入 -->
  143. <input
  144. v-if="inputType === 'text'"
  145. class="input-field"
  146. v-model="inputText"
  147. placeholder="说点什么..."
  148. confirm-type="send"
  149. @confirm="sendTextMessage"
  150. @input="onInputChange" />
  151. <!-- 语音按钮 -->
  152. <button
  153. v-else
  154. class="voice-button"
  155. @touchstart="startVoiceRecord"
  156. @touchend="stopVoiceRecord">
  157. 按住说话
  158. </button>
  159. <!-- 表情按钮 -->
  160. <view class="input-icon" @click="showEmojiPanel = !showEmojiPanel">
  161. <text>😊</text>
  162. </view>
  163. <!-- 更多按钮 -->
  164. <view class="input-icon" @click="showMorePanel = !showMorePanel">
  165. <text>➕</text>
  166. </view>
  167. </view>
  168. <!-- 表情面板 -->
  169. <view v-if="showEmojiPanel" class="emoji-panel">
  170. <text
  171. v-for="emoji in emojis"
  172. :key="emoji"
  173. class="emoji-item"
  174. @click="insertEmoji(emoji)">
  175. {{ emoji }}
  176. </text>
  177. </view>
  178. <!-- 更多功能面板 -->
  179. <view v-if="showMorePanel" class="more-panel">
  180. <view class="more-item" @click="chooseImage">
  181. <view class="more-icon">🖼️</view>
  182. <text class="more-text">图片</text>
  183. </view>
  184. <view class="more-item" @click="chooseVideo">
  185. <view class="more-icon">📹</view>
  186. <text class="more-text">视频</text>
  187. </view>
  188. <view class="more-item" @click="chooseFile">
  189. <view class="more-icon">📁</view>
  190. <text class="more-text">文件</text>
  191. </view>
  192. </view>
  193. <!-- 消息操作菜单 -->
  194. <view v-if="showMessageAction" class="message-action-mask" @click="hideMessageMenu">
  195. <view class="message-action-menu" @click.stop>
  196. <view class="menu-item" @click="copyMessage" v-if="selectedMessage && selectedMessage.messageType === 1">
  197. <text class="menu-icon">📋</text>
  198. <text>复制</text>
  199. </view>
  200. <view class="menu-item" @click="recallMessage" v-if="selectedMessage && selectedMessage.fromUserId === userId && canRecall(selectedMessage)">
  201. <text class="menu-icon">↩️</text>
  202. <text>撤回</text>
  203. </view>
  204. <view class="menu-item" @click="deleteMessage">
  205. <text class="menu-icon">🗑️</text>
  206. <text>删除</text>
  207. </view>
  208. <view class="menu-item cancel" @click="hideMessageMenu">
  209. <text>取消</text>
  210. </view>
  211. </view>
  212. </view>
  213. </view>
  214. </template>
  215. <script>
  216. import timManager from '@/utils/tim-manager.js';
  217. import TIM from 'tim-wx-sdk';
  218. export default {
  219. data() {
  220. return {
  221. isBlockedByTarget: false,
  222. userId: null,
  223. userAvatar: '',
  224. targetUserId: null,
  225. targetUserName: '',
  226. targetUserAvatar: '',
  227. messages: [],
  228. inputText: '',
  229. inputType: 'text',
  230. conversationID: '',
  231. scrollToView: '',
  232. showEmojiPanel: false,
  233. showMorePanel: false,
  234. isLogin: false,
  235. // 消息操作菜单
  236. showMessageAction: false,
  237. selectedMessage: null,
  238. selectedMessageIndex: -1,
  239. menuTop: 0,
  240. // 加载更多
  241. loading: false,
  242. noMore: false,
  243. nextReqMessageID: '',
  244. isTargetOnline: false,
  245. emojis: ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩', '🥳'],
  246. showMoreOptionsModal: false, // 控制更多选项弹窗显示
  247. showBlockConfirmModal: false // 控制拉黑确认弹窗显示
  248. };
  249. },
  250. async onLoad(options) {
  251. console.log('=== 聊天页面加载 ===');
  252. // 严格验证登录状态
  253. const token = uni.getStorageSync('token');
  254. const userInfo = uni.getStorageSync('userInfo');
  255. const storedUserId = uni.getStorageSync('userId');
  256. console.log('登录状态检查:');
  257. console.log('- token:', token ? '存在' : '不存在');
  258. console.log('- userInfo:', userInfo);
  259. console.log('- storedUserId:', storedUserId);
  260. if (!token || !userInfo) {
  261. console.error('❌ 未登录或登录信息不完整');
  262. uni.showModal({
  263. title: '需要登录',
  264. content: '请先登录后再进行聊天',
  265. showCancel: false,
  266. success: () => {
  267. uni.reLaunch({
  268. url: '/pages/page3/page3'
  269. });
  270. }
  271. });
  272. return;
  273. }
  274. // 优先使用 storage 中的 userId,确保一致性
  275. let rawUserId = storedUserId || userInfo.userId || userInfo.id || userInfo.user_id;
  276. // 转换为数字类型(确保与消息列表页面一致)
  277. if (typeof rawUserId === 'string') {
  278. rawUserId = parseInt(rawUserId);
  279. }
  280. if (!rawUserId || isNaN(rawUserId)) {
  281. console.error('❌ 无法获取有效的用户ID');
  282. uni.showModal({
  283. title: '用户信息错误',
  284. content: '无法获取用户ID,请重新登录',
  285. showCancel: false,
  286. success: () => {
  287. uni.removeStorageSync('token');
  288. uni.removeStorageSync('userInfo');
  289. uni.removeStorageSync('userId');
  290. uni.reLaunch({
  291. url: '/pages/page3/page3'
  292. });
  293. }
  294. });
  295. return;
  296. }
  297. // 保存用户ID(TIM需要字符串格式)
  298. this.userId = String(rawUserId);
  299. this.userAvatar = userInfo.avatar || userInfo.avatarUrl || '/static/default-avatar.svg';
  300. // 获取对方用户信息(确保是字符串格式)
  301. this.targetUserId = String(options.targetUserId);
  302. this.targetUserName = decodeURIComponent(options.targetUserName || '用户');
  303. this.targetUserAvatar = decodeURIComponent(options.targetUserAvatar || '/static/default-avatar.svg');
  304. // 生成会话 ID
  305. this.conversationID = `C2C${this.targetUserId}`;
  306. console.log('✅ 聊天页面初始化成功:');
  307. console.log(' - 当前用户ID:', rawUserId, '(TIM格式:', this.userId, ')');
  308. console.log(' - 对方用户ID:', this.targetUserId);
  309. console.log(' - 会话ID:', this.conversationID);
  310. // 初始化 TIM
  311. await this.initTIM();
  312. // 等待 SDK Ready 后再加载消息
  313. await this.waitForSDKReady();
  314. // 先检查拉黑状态
  315. this.isBlockedByTarget = await this.checkIsBlockedByTarget();
  316. if (this.isBlockedByTarget) {
  317. uni.showToast({
  318. title: '你已被对方拉黑,无法发送消息',
  319. icon: 'none',
  320. duration: 3000
  321. });
  322. }
  323. // 加载历史消息
  324. await this.loadMessages();
  325. // 监听新消息
  326. this.listenMessages();
  327. },
  328. onUnload() {
  329. // 页面卸载时移除监听
  330. timManager.offMessage(this.handleNewMessage);
  331. },
  332. methods: {
  333. /**
  334. * 初始化 TIM
  335. */
  336. async initTIM() {
  337. try {
  338. // 如果未初始化,先初始化
  339. if (!timManager.tim) {
  340. timManager.init(1600109674); // ✅ 已更新为正确的 SDKAppID
  341. }
  342. // 如果未登录,获取 userSig 并登录
  343. if (!timManager.isLogin) {
  344. // 先导入当前用户和目标用户到腾讯云IM
  345. await this.importUsers();
  346. // 从后端获取 userSig
  347. const userSig = await this.getUserSig();
  348. await timManager.login(this.userId, userSig);
  349. }
  350. this.isLogin = true;
  351. console.log('✅ TIM 初始化完成');
  352. } catch (error) {
  353. console.error('❌ TIM 初始化失败:', error);
  354. uni.showToast({
  355. title: '连接失败,请重试',
  356. icon: 'none'
  357. });
  358. }
  359. },
  360. more(userid) {
  361. console.log('点击了更多按钮,开始跳转...', userid);
  362. // 如果目标页面是普通页面,用navigateTo(保留当前页面);如果是tabbar页面,用switchTab
  363. uni.navigateTo({
  364. url: `/pages/message/more?userid=${userid}`,
  365. success: () => {
  366. console.log('跳转成功');
  367. },
  368. fail: (err) => {
  369. console.error('跳转失败:', err);
  370. uni.showToast({
  371. title: '页面不存在或路径错误',
  372. icon: 'none'
  373. });
  374. }
  375. });
  376. },
  377. /**
  378. * 导入用户到腾讯云IM
  379. */
  380. async importUsers() {
  381. try {
  382. console.log('📥 开始导入用户到腾讯云IM...');
  383. console.log(' - 当前用户ID:', this.userId, '(类型:', typeof this.userId, ')');
  384. console.log(' - 目标用户ID:', this.targetUserId, '(类型:', typeof this.targetUserId, ')');
  385. // 验证用户ID
  386. if (!this.userId || this.userId === 'undefined' || this.userId === 'null') {
  387. throw new Error('当前用户ID无效: ' + this.userId);
  388. }
  389. if (!this.targetUserId || this.targetUserId === 'undefined' || this.targetUserId === 'null') {
  390. throw new Error('目标用户ID无效: ' + this.targetUserId);
  391. }
  392. // 导入当前用户(确保userId是字符串)
  393. const currentUserRes = await uni.request({
  394. url: 'http://localhost:1004/api/im/importUser',
  395. method: 'POST',
  396. data: {
  397. userId: String(this.userId),
  398. nickname: '用户' + this.userId
  399. },
  400. header: {
  401. 'Content-Type': 'application/json'
  402. }
  403. });
  404. console.log(' - 当前用户导入结果:', currentUserRes[1].data);
  405. // 导入目标用户(确保userId是字符串)
  406. const targetUserRes = await uni.request({
  407. url: 'http://localhost:1004/api/im/importUser',
  408. method: 'POST',
  409. data: {
  410. userId: String(this.targetUserId),
  411. nickname: this.targetUserName || '用户' + this.targetUserId
  412. },
  413. header: {
  414. 'Content-Type': 'application/json'
  415. }
  416. });
  417. console.log(' - 目标用户导入结果:', targetUserRes[1].data);
  418. console.log('✅ 用户导入成功');
  419. } catch (error) {
  420. console.log('⚠️ 用户导入失败(可能已存在):', error);
  421. // 导入失败不影响登录,因为用户可能已经存在
  422. }
  423. },
  424. /**
  425. * 获取 UserSig
  426. */
  427. async getUserSig() {
  428. try {
  429. const [err, res] = await uni.request({
  430. url: 'http://localhost:1004/api/im/getUserSig',
  431. method: 'GET',
  432. data: {
  433. userId: this.userId
  434. }
  435. });
  436. if (err) {
  437. throw new Error('请求失败');
  438. }
  439. if (res.data && res.data.code === 200) {
  440. return res.data.data.userSig;
  441. } else {
  442. throw new Error('获取 UserSig 失败');
  443. }
  444. } catch (error) {
  445. console.error('❌ 获取 UserSig 失败:', error);
  446. throw error;
  447. }
  448. },
  449. /**
  450. * 等待 SDK Ready
  451. */
  452. async waitForSDKReady() {
  453. return new Promise((resolve) => {
  454. // 如果已经 ready,立即返回
  455. if (timManager.isLogin) {
  456. console.log('✅ SDK 已就绪');
  457. resolve();
  458. return;
  459. }
  460. // 否则等待 SDK ready 事件
  461. console.log('⏳ 等待 SDK 就绪...');
  462. const checkReady = setInterval(() => {
  463. if (timManager.isLogin) {
  464. console.log('✅ SDK 已就绪');
  465. clearInterval(checkReady);
  466. resolve();
  467. }
  468. }, 100); // 每 100ms 检查一次
  469. // 超时保护(10秒后强制继续)
  470. setTimeout(() => {
  471. console.log('⚠️ 等待 SDK 就绪超时,继续执行');
  472. clearInterval(checkReady);
  473. resolve();
  474. }, 10000);
  475. });
  476. },
  477. /**
  478. * 加载历史消息
  479. */
  480. async loadMessages() {
  481. try {
  482. const res = await timManager.tim.getMessageList({
  483. conversationID: this.conversationID,
  484. count: 20
  485. });
  486. const messageList = res.data.messageList;
  487. this.nextReqMessageID = res.data.nextReqMessageID;
  488. this.noMore = !res.data.isCompleted;
  489. // 转换为我们的消息格式
  490. this.messages = messageList.map(msg => this.convertMessage(msg));
  491. // 滚动到底部
  492. this.$nextTick(() => {
  493. this.scrollToBottom();
  494. });
  495. // 标记已读
  496. await timManager.setMessageRead(this.conversationID);
  497. } catch (error) {
  498. console.error('❌ 加载消息失败:', error);
  499. }
  500. },
  501. /**
  502. * 加载更多消息(上拉)
  503. */
  504. async loadMoreMessages() {
  505. if (this.loading || !this.nextReqMessageID) {
  506. return;
  507. }
  508. this.loading = true;
  509. try {
  510. const res = await timManager.tim.getMessageList({
  511. conversationID: this.conversationID,
  512. nextReqMessageID: this.nextReqMessageID,
  513. count: 20
  514. });
  515. const messageList = res.data.messageList;
  516. this.nextReqMessageID = res.data.nextReqMessageID;
  517. this.noMore = !res.data.isCompleted;
  518. // 转换并添加到消息列表前面
  519. const newMessages = messageList.map(msg => this.convertMessage(msg));
  520. this.messages = [...newMessages, ...this.messages];
  521. } catch (error) {
  522. console.error('❌ 加载更多消息失败:', error);
  523. } finally {
  524. this.loading = false;
  525. }
  526. },
  527. /**
  528. * 监听新消息
  529. */
  530. listenMessages() {
  531. const handleNewMessage = (event) => {
  532. // 兼容不同格式的事件数据
  533. const messageList = event.data || event || [];
  534. // 确保是数组格式
  535. const messagesToProcess = Array.isArray(messageList) ? messageList : [messageList];
  536. messagesToProcess.forEach(msg => {
  537. // 只处理当前会话的消息
  538. if (msg.conversationID === this.conversationID) {
  539. // 查找消息在本地列表中的位置
  540. const existingIndex = this.messages.findIndex(m => m.messageId === msg.ID);
  541. if (existingIndex > -1) {
  542. // 更新现有消息状态(使用$set确保视图更新)
  543. this.$set(this.messages, existingIndex, this.convertMessage(msg));
  544. } else {
  545. // 添加新消息
  546. this.messages.push(this.convertMessage(msg));
  547. this.$nextTick(() => {
  548. this.scrollToBottom();
  549. });
  550. }
  551. // 标记已读
  552. timManager.setMessageRead(this.conversationID);
  553. }
  554. });
  555. };
  556. this.handleNewMessage = handleNewMessage;
  557. timManager.onMessage(handleNewMessage);
  558. // 添加消息状态变更监听
  559. if (timManager.tim) {
  560. timManager.tim.on(TIM.EVENT.MESSAGE_STATUS_CHANGED, handleNewMessage);
  561. }
  562. },
  563. /**
  564. * 转换消息格式
  565. */
  566. convertMessage(timMsg) {
  567. let sendStatus = 1; // 默认发送中
  568. // 完善的状态判断逻辑
  569. if (timMsg.status === TIM.TYPES.MSG_STATUS_SEND_SUCC ||
  570. timMsg.status === 'success' ||
  571. timMsg.status === TIM.TYPES.MSG_STATUS_RECEIVED) {
  572. sendStatus = 2; // 已送达
  573. } else if (timMsg.status === TIM.TYPES.MSG_STATUS_SEND_FAIL ||
  574. timMsg.status === 'fail') {
  575. sendStatus = 4; // 发送失败
  576. } else if (timMsg.status === TIM.TYPES.MSG_STATUS_HAS_READ ||
  577. timMsg.status === 'read') {
  578. sendStatus = 3; // 已读
  579. } else if (timMsg.status === TIM.TYPES.MSG_STATUS_SENDING) {
  580. sendStatus = 1; // 发送中
  581. }
  582. return {
  583. messageId: timMsg.ID,
  584. fromUserId: timMsg.from,
  585. toUserId: timMsg.to,
  586. messageType: timMsg.type === TIM.TYPES.MSG_TEXT ? 1 :
  587. timMsg.type === TIM.TYPES.MSG_IMAGE ? 2 :
  588. timMsg.type === TIM.TYPES.MSG_SOUND ? 3 :
  589. timMsg.type === TIM.TYPES.MSG_VIDEO ? 4 : 1,
  590. content: timMsg.type === TIM.TYPES.MSG_TEXT ? timMsg.payload.text : '[图片]',
  591. mediaUrl: timMsg.type === TIM.TYPES.MSG_IMAGE ? timMsg.payload.imageInfoArray?.[0]?.url : '',
  592. sendStatus: sendStatus,
  593. sendTime: new Date(timMsg.time * 1000),
  594. isRecalled: timMsg.isRevoked,
  595. fromUserName: timMsg.from === this.userId ? '我' : this.targetUserName
  596. };
  597. },
  598. /**
  599. * 检查对方是否拉黑自己
  600. */
  601. async checkIsBlockedByTarget() {
  602. try {
  603. const [err, res] = await uni.request({
  604. url: 'http://localhost:8083/api/chatfriend/checkBlock',
  605. method: 'POST',
  606. data: {
  607. userId: this.userId, // 自己的ID
  608. targetUserId: this.targetUserId // 对方的ID
  609. },
  610. header: {
  611. 'Content-Type': 'application/json'
  612. }
  613. });
  614. console.log('拉黑检查接口响应:', res.data); // 方便调试
  615. if (err) {
  616. console.error('网络请求失败:', err);
  617. return false; // 网络错误时默认按“未被拉黑”处理(避免误拦截)
  618. }
  619. // 严格校验接口返回格式
  620. if (!res.data || res.data.code !== 200) {
  621. console.error('接口返回格式错误:', res.data);
  622. return false;
  623. }
  624. // 关键修复:后端返回 data:true 表示“已被拉黑”,直接返回该值
  625. // 你的接口中 data 就是布尔值,无需额外解析
  626. const isBlocked = res.data.data;
  627. console.log('是否被拉黑:', isBlocked); // 确认这里输出为 true(被拉黑时)
  628. return isBlocked;
  629. } catch (error) {
  630. console.error('检查拉黑状态失败:', error);
  631. return false;
  632. }
  633. },
  634. /**
  635. * 发送文本消息
  636. */
  637. async sendTextMessage() {
  638. if (!this.inputText.trim()) {
  639. return;
  640. }
  641. const content = this.inputText;
  642. this.inputText = '';
  643. // 先检查是否被拉黑
  644. const isBlocked = await this.checkIsBlockedByTarget();
  645. if (isBlocked) {
  646. // 被拉黑时的处理保持不变
  647. const failedMessage = {
  648. messageId: 'failed_' + Date.now(),
  649. fromUserId: this.userId,
  650. toUserId: this.targetUserId,
  651. messageType: 1,
  652. content: content,
  653. sendStatus: 4, // 4表示发送失败
  654. sendTime: new Date(),
  655. fromUserName: '我'
  656. };
  657. this.messages.push(failedMessage);
  658. this.scrollToBottom();
  659. uni.showToast({
  660. title: '消息发送失败',
  661. icon: 'none'
  662. });
  663. return;
  664. }
  665. // 创建临时消息显示"发送中"
  666. const tempMessageId = 'temp_' + Date.now();
  667. const tempMessage = {
  668. messageId: tempMessageId,
  669. fromUserId: this.userId,
  670. toUserId: this.targetUserId,
  671. messageType: 1,
  672. content: content,
  673. sendStatus: 1, // 发送中
  674. sendTime: new Date(),
  675. fromUserName: '我'
  676. };
  677. this.messages.push(tempMessage);
  678. this.scrollToBottom();
  679. // 未被拉黑,正常发送
  680. try {
  681. const sendPromise = timManager.sendTextMessage(this.targetUserId, content);
  682. const timeoutPromise = new Promise((_, reject) => {
  683. setTimeout(() => reject(new Error('发送超时')), 15000);
  684. });
  685. const message = await Promise.race([sendPromise, timeoutPromise]);
  686. // 替换临时消息
  687. const tempIndex = this.messages.findIndex(m => m.messageId === tempMessageId);
  688. if (tempIndex > -1) {
  689. const convertedMsg = this.convertMessage(message);
  690. // 强制设置为已送达
  691. convertedMsg.sendStatus = 2;
  692. this.$set(this.messages, tempIndex, convertedMsg);
  693. }
  694. console.log('✅ 消息发送成功');
  695. this.syncMessageToMySQL(message);
  696. } catch (error) {
  697. console.error('❌ 消息发送失败:', error);
  698. // 更新临时消息为失败状态
  699. const tempIndex = this.messages.findIndex(m => m.messageId === tempMessageId);
  700. if (tempIndex > -1) {
  701. this.$set(this.messages[tempIndex], 'sendStatus', 4);
  702. }
  703. // 恢复输入框内容
  704. this.inputText = content;
  705. uni.showToast({
  706. title: '发送失败: ' + error.message,
  707. icon: 'none'
  708. });
  709. }
  710. },
  711. /**
  712. * 选择图片
  713. */
  714. chooseImage() {
  715. uni.chooseImage({
  716. count: 1,
  717. sizeType: ['compressed'],
  718. sourceType: ['album', 'camera'],
  719. success: async (res) => {
  720. // 1. 先检查是否被拉黑
  721. const isBlocked = await this.checkIsBlockedByTarget();
  722. if (isBlocked) {
  723. uni.showToast({
  724. title: '你已被对方拉黑,无法发送消息',
  725. icon: 'none'
  726. });
  727. return;
  728. }
  729. const tempFilePath = res.tempFilePaths[0];
  730. try {
  731. uni.showLoading({ title: '发送中...' });
  732. const message = await timManager.sendImageMessage(this.targetUserId, tempFilePath);
  733. this.messages.push(this.convertMessage(message));
  734. this.scrollToBottom();
  735. uni.hideLoading();
  736. console.log('✅ 图片发送成功');
  737. } catch (error) {
  738. uni.hideLoading();
  739. console.error('❌ 图片发送失败:', error);
  740. uni.showToast({
  741. title: '发送失败',
  742. icon: 'none'
  743. });
  744. }
  745. }
  746. });
  747. this.showMorePanel = false;
  748. },
  749. /**
  750. * 输入框内容变化
  751. */
  752. onInputChange() {
  753. // 腾讯云 IM 可以实现正在输入状态,这里暂时省略
  754. console.log('输入中...');
  755. },
  756. /**
  757. * 同步消息到MySQL数据库(双重存储保障)
  758. */
  759. async syncMessageToMySQL(timMessage) {
  760. try {
  761. console.log('🔄 同步消息到MySQL...', timMessage.ID);
  762. // 构建同步参数
  763. const syncData = {
  764. messageId: timMessage.ID,
  765. fromUserId: timMessage.from,
  766. toUserId: timMessage.to,
  767. messageType: this.getMessageType(timMessage),
  768. content: this.getMessageContent(timMessage),
  769. sendTime: timMessage.time // TIM返回的是秒级时间戳
  770. };
  771. // 如果是图片消息,添加媒体信息
  772. if (timMessage.type === 'TIMImageElem' && timMessage.payload.imageInfoArray) {
  773. const imageInfo = timMessage.payload.imageInfoArray[0];
  774. syncData.mediaUrl = imageInfo.imageUrl;
  775. syncData.thumbnailUrl = imageInfo.imageUrl;
  776. }
  777. // 调用后端同步接口
  778. const res = await uni.request({
  779. url: 'http://localhost:1004/api/chat/syncTIMMessage',
  780. method: 'POST',
  781. data: syncData,
  782. header: {
  783. 'Content-Type': 'application/json'
  784. }
  785. });
  786. if (res[1].data.code === 200) {
  787. console.log('✅ 消息已同步到MySQL:', timMessage.ID);
  788. } else {
  789. console.warn('⚠️ 消息同步失败:', res[1].data.message);
  790. }
  791. } catch (error) {
  792. console.error('❌ 同步消息到MySQL失败:', error);
  793. // 同步失败不影响聊天功能,只记录日志
  794. }
  795. },
  796. /**
  797. * 获取消息类型
  798. */
  799. getMessageType(timMessage) {
  800. const typeMap = {
  801. 'TIMTextElem': 1, // 文本
  802. 'TIMImageElem': 2, // 图片
  803. 'TIMSoundElem': 3, // 语音
  804. 'TIMVideoFileElem': 4, // 视频
  805. 'TIMFileElem': 5 // 文件
  806. };
  807. return typeMap[timMessage.type] || 1;
  808. },
  809. /**
  810. * 获取消息内容
  811. */
  812. getMessageContent(timMessage) {
  813. switch (timMessage.type) {
  814. case 'TIMTextElem':
  815. return timMessage.payload.text || '';
  816. case 'TIMImageElem':
  817. return '[图片]';
  818. case 'TIMSoundElem':
  819. return '[语音]';
  820. case 'TIMVideoFileElem':
  821. return '[视频]';
  822. case 'TIMFileElem':
  823. return '[文件]';
  824. default:
  825. return '[未知消息]';
  826. }
  827. },
  828. /**
  829. * 滚动到底部
  830. */
  831. scrollToBottom() {
  832. this.$nextTick(() => {
  833. const lastIndex = this.messages.length - 1;
  834. this.scrollToView = 'msg-' + lastIndex;
  835. });
  836. },
  837. /**
  838. * 判断是否显示时间分隔线
  839. */
  840. shouldShowTime(msg, index) {
  841. if (index === 0) return true;
  842. const prevMsg = this.messages[index - 1];
  843. const timeDiff = new Date(msg.sendTime) - new Date(prevMsg.sendTime);
  844. // 超过5分钟显示时间
  845. return timeDiff > 5 * 60 * 1000;
  846. },
  847. /**
  848. * 格式化消息时间(用于时间分隔线)
  849. */
  850. formatMessageTime(time) {
  851. const date = new Date(time);
  852. const now = new Date();
  853. const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  854. const yesterday = new Date(today - 86400000);
  855. // 今天
  856. if (date >= today) {
  857. return date.toLocaleTimeString('zh-CN', {
  858. hour: '2-digit',
  859. minute: '2-digit'
  860. });
  861. }
  862. // 昨天
  863. if (date >= yesterday) {
  864. return '昨天 ' + date.toLocaleTimeString('zh-CN', {
  865. hour: '2-digit',
  866. minute: '2-digit'
  867. });
  868. }
  869. // 本周
  870. if (date > new Date(now - 7 * 86400000)) {
  871. const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  872. return days[date.getDay()] + ' ' + date.toLocaleTimeString('zh-CN', {
  873. hour: '2-digit',
  874. minute: '2-digit'
  875. });
  876. }
  877. // 更早
  878. return date.toLocaleString('zh-CN', {
  879. month: '2-digit',
  880. day: '2-digit',
  881. hour: '2-digit',
  882. minute: '2-digit'
  883. });
  884. },
  885. /**
  886. * 格式化时间(消息状态用)
  887. */
  888. formatTime(time) {
  889. const date = new Date(time);
  890. const now = new Date();
  891. const diff = now - date;
  892. if (diff < 60000) {
  893. return '刚刚';
  894. } else if (diff < 3600000) {
  895. return Math.floor(diff / 60000) + '分钟前';
  896. } else if (diff < 86400000) {
  897. return Math.floor(diff / 3600000) + '小时前';
  898. } else {
  899. return date.toLocaleString('zh-CN', {
  900. month: '2-digit',
  901. day: '2-digit',
  902. hour: '2-digit',
  903. minute: '2-digit'
  904. });
  905. }
  906. },
  907. /**
  908. * 预览图片
  909. */
  910. previewImage(url) {
  911. uni.previewImage({
  912. urls: [url],
  913. current: url
  914. });
  915. },
  916. /**
  917. * 返回
  918. */
  919. goBack() {
  920. uni.navigateBack({
  921. success: () => {
  922. // 通知消息列表页面刷新
  923. uni.$emit('refreshConversations');
  924. }
  925. });
  926. },
  927. /**
  928. * 显示消息操作菜单
  929. */
  930. showMessageMenu(msg, index) {
  931. this.selectedMessage = msg;
  932. this.selectedMessageIndex = index;
  933. this.showMessageAction = true;
  934. // 计算菜单位置
  935. uni.createSelectorQuery().select('.message-item').boundingClientRect(rect => {
  936. if (rect) {
  937. this.menuTop = rect.top + rect.height;
  938. }
  939. }).exec();
  940. },
  941. /**
  942. * 隐藏消息操作菜单
  943. */
  944. hideMessageMenu() {
  945. this.showMessageAction = false;
  946. this.selectedMessage = null;
  947. this.selectedMessageIndex = -1;
  948. },
  949. /**
  950. * 复制消息
  951. */
  952. copyMessage() {
  953. if (!this.selectedMessage || this.selectedMessage.messageType !== 1) {
  954. return;
  955. }
  956. uni.setClipboardData({
  957. data: this.selectedMessage.content,
  958. success: () => {
  959. uni.showToast({
  960. title: '已复制',
  961. icon: 'success'
  962. });
  963. }
  964. });
  965. this.hideMessageMenu();
  966. },
  967. /**
  968. * 判断是否可以撤回
  969. */
  970. canRecall(msg) {
  971. const diff = Date.now() - new Date(msg.sendTime).getTime();
  972. return diff < 2 * 60 * 1000; // 2分钟内可撤回
  973. },
  974. /**
  975. * 撤回消息
  976. */
  977. async recallMessage() {
  978. if (!this.selectedMessage) {
  979. return;
  980. }
  981. try {
  982. // 查找TIM消息对象
  983. const timMessage = await timManager.tim.findMessage(this.selectedMessage.messageId);
  984. if (timMessage) {
  985. await timManager.revokeMessage(timMessage);
  986. // 更新本地消息状态
  987. this.selectedMessage.isRecalled = true;
  988. this.selectedMessage.content = '你撤回了一条消息';
  989. uni.showToast({
  990. title: '已撤回',
  991. icon: 'success'
  992. });
  993. }
  994. } catch (error) {
  995. console.error('撤回失败:', error);
  996. uni.showToast({
  997. title: '撤回失败',
  998. icon: 'none'
  999. });
  1000. }
  1001. this.hideMessageMenu();
  1002. },
  1003. /**
  1004. * 删除消息
  1005. */
  1006. deleteMessage() {
  1007. if (!this.selectedMessage) {
  1008. return;
  1009. }
  1010. uni.showModal({
  1011. title: '确认删除',
  1012. content: '确定要删除这条消息吗?',
  1013. success: (res) => {
  1014. if (res.confirm) {
  1015. // 从列表中删除
  1016. this.messages.splice(this.selectedMessageIndex, 1);
  1017. uni.showToast({
  1018. title: '已删除',
  1019. icon: 'success'
  1020. });
  1021. }
  1022. }
  1023. });
  1024. this.hideMessageMenu();
  1025. },
  1026. /**
  1027. * 处理消息点击
  1028. */
  1029. handleMessageClick(msg) {
  1030. // 如果是发送失败的消息,提示重试
  1031. if (msg.sendStatus === 4) {
  1032. uni.showModal({
  1033. title: '发送失败',
  1034. content: '消息发送失败,是否重试?',
  1035. success: (res) => {
  1036. if (res.confirm) {
  1037. this.retryMessage(msg);
  1038. }
  1039. }
  1040. });
  1041. }
  1042. },
  1043. /**
  1044. * 重试发送消息
  1045. */
  1046. async retryMessage(msg) {
  1047. if (msg.messageType !== 1) {
  1048. uni.showToast({ title: '暂不支持重发该类型消息', icon: 'none' });
  1049. return;
  1050. }
  1051. const isBlocked = await this.checkIsBlockedByTarget();
  1052. if (isBlocked) {
  1053. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1054. if (index > -1) {
  1055. this.$set(this.messages[index], 'sendStatus', 4);
  1056. }
  1057. uni.showToast({ title: '对方已拉黑你,无法发送', icon: 'none' });
  1058. return;
  1059. }
  1060. try {
  1061. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1062. if (index > -1) {
  1063. this.$set(this.messages[index], 'sendStatus', 1); // 发送中
  1064. }
  1065. const message = await timManager.sendTextMessage(this.targetUserId, msg.content);
  1066. // 更新消息状态为已送达
  1067. if (index > -1) {
  1068. const convertedMsg = this.convertMessage(message);
  1069. convertedMsg.sendStatus = 2; // 强制已送达
  1070. convertedMsg.messageId = msg.messageId; // 保持原ID
  1071. this.$set(this.messages, index, convertedMsg);
  1072. }
  1073. console.log('✅ 消息重发成功');
  1074. this.syncMessageToMySQL(message);
  1075. } catch (error) {
  1076. console.error('❌ 消息重发失败:', error);
  1077. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1078. if (index > -1) {
  1079. this.$set(this.messages[index], 'sendStatus', 4);
  1080. }
  1081. uni.showToast({ title: '发送失败', icon: 'none' });
  1082. }
  1083. },
  1084. // 其他功能方法
  1085. switchInputType() {
  1086. this.inputType = this.inputType === 'text' ? 'voice' : 'text';
  1087. },
  1088. startVoiceRecord() {
  1089. uni.showToast({
  1090. title: '按住说话',
  1091. icon: 'none'
  1092. });
  1093. },
  1094. stopVoiceRecord() {
  1095. uni.showToast({
  1096. title: '语音功能开发中',
  1097. icon: 'none'
  1098. });
  1099. },
  1100. insertEmoji(emoji) {
  1101. this.inputText += emoji;
  1102. this.showEmojiPanel = false;
  1103. },
  1104. chooseVideo() {
  1105. uni.showToast({
  1106. title: '视频功能开发中',
  1107. icon: 'none'
  1108. });
  1109. this.showMorePanel = false;
  1110. },
  1111. chooseFile() {
  1112. uni.showToast({
  1113. title: '文件功能开发中',
  1114. icon: 'none'
  1115. });
  1116. this.showMorePanel = false;
  1117. },
  1118. playVoice() {
  1119. uni.showToast({
  1120. title: '语音播放功能开发中',
  1121. icon: 'none'
  1122. });
  1123. },
  1124. showMoreOptions() {
  1125. this.showMoreOptionsModal = true;
  1126. },
  1127. closeMoreOptions() {
  1128. this.showMoreOptionsModal = false;
  1129. },
  1130. /**
  1131. * 查看用户资料(跳转到原有more页面)
  1132. */
  1133. goToUserProfile() {
  1134. this.closeMoreOptions();
  1135. uni.navigateTo({
  1136. url: `/pages/message/more?userid=${this.targetUserId}`,
  1137. fail: (err) => {
  1138. console.error('跳转失败:', err);
  1139. uni.showToast({
  1140. title: '页面不存在',
  1141. icon: 'none'
  1142. });
  1143. }
  1144. });
  1145. },
  1146. /**
  1147. * 显示拉黑确认弹窗
  1148. */
  1149. blockFriend() {
  1150. this.closeMoreOptions();
  1151. this.showBlockConfirmModal = true;
  1152. },
  1153. /**
  1154. * 关闭拉黑确认弹窗
  1155. */
  1156. closeBlockConfirm() {
  1157. this.showBlockConfirmModal = false;
  1158. },
  1159. /**
  1160. * 确认拉黑好友
  1161. */
  1162. async confirmBlockFriend() {
  1163. try {
  1164. uni.showLoading({
  1165. title: '处理中...'
  1166. });
  1167. // 调用后端拉黑接口(根据实际接口调整)
  1168. const [err, res] = await uni.request({
  1169. url: 'http://localhost:8083/api/chatfriend/block',
  1170. method: 'POST',
  1171. data: {
  1172. userId: this.userId,
  1173. targetUserId: this.targetUserId,
  1174. targetUserName: this.targetUserName,
  1175. targetUserAvatar: this.targetUserAvatar
  1176. },
  1177. header: {
  1178. 'Content-Type': 'application/json',
  1179. // 'Authorization': 'Bearer ' + uni.getStorageSync('token')
  1180. }
  1181. });
  1182. uni.hideLoading();
  1183. if (err) throw new Error('网络请求失败');
  1184. if (res.data && res.data.code === 200) {
  1185. uni.showToast({ title: '拉黑成功', icon: 'success' });
  1186. this.closeBlockConfirm();
  1187. // 触发拉黑列表更新事件,通知消息页面实时刷新
  1188. uni.$emit('blacklistUpdated');
  1189. // 拉黑成功后立即返回消息列表页面(优化体验)
  1190. setTimeout(() => {
  1191. uni.navigateBack({
  1192. delta: 1,
  1193. success: () => {
  1194. // 返回成功后再次触发一次刷新,确保万无一失
  1195. uni.$emit('blacklistUpdated');
  1196. }
  1197. });
  1198. }, 1500);
  1199. } else {
  1200. throw new Error(res.data?.message || '拉黑失败');
  1201. }
  1202. } catch (error) {
  1203. console.error('拉黑失败:', error);
  1204. uni.showToast({ title: error.message || '拉黑失败', icon: 'none' });
  1205. }
  1206. },
  1207. }
  1208. };
  1209. </script>
  1210. <style scoped>
  1211. /* 弹窗遮罩 */
  1212. .modal-mask {
  1213. position: fixed;
  1214. top: 0;
  1215. left: 0;
  1216. right: 0;
  1217. bottom: 0;
  1218. background-color: rgba(0, 0, 0, 0.5);
  1219. z-index: 10000;
  1220. display: flex;
  1221. align-items: center;
  1222. justify-content: center;
  1223. }
  1224. /* 更多选项弹窗内容 */
  1225. .modal-content {
  1226. width: 70%;
  1227. background-color: #fff;
  1228. border-radius: 20rpx;
  1229. overflow: hidden;
  1230. }
  1231. .modal-header {
  1232. padding: 30rpx;
  1233. text-align: center;
  1234. border-bottom: 1px solid #eee;
  1235. }
  1236. .modal-title {
  1237. font-size: 32rpx;
  1238. font-weight: bold;
  1239. display: block;
  1240. }
  1241. .modal-subtitle {
  1242. font-size: 24rpx;
  1243. color: #999;
  1244. display: block;
  1245. margin-top: 10rpx;
  1246. }
  1247. .modal-body {
  1248. padding: 20rpx 0;
  1249. }
  1250. .modal-item {
  1251. display: flex;
  1252. align-items: center;
  1253. padding: 25rpx 40rpx;
  1254. font-size: 30rpx;
  1255. }
  1256. .modal-item.danger {
  1257. color: #fa5151;
  1258. }
  1259. .item-icon {
  1260. font-size: 32rpx;
  1261. margin-right: 20rpx;
  1262. }
  1263. .modal-footer {
  1264. padding: 20rpx;
  1265. border-top: 1px solid #eee;
  1266. }
  1267. .modal-close-btn {
  1268. width: 94%;
  1269. background-color: #f5f5f5;
  1270. border: none;
  1271. border-radius: 10rpx;
  1272. padding: 20rpx;
  1273. font-size: 30rpx;
  1274. }
  1275. /* 确认弹窗样式 */
  1276. .confirm-modal {
  1277. width: 60%;
  1278. background-color: #fff;
  1279. border-radius: 20rpx;
  1280. padding: 40rpx;
  1281. text-align: center;
  1282. }
  1283. .confirm-title {
  1284. font-size: 32rpx;
  1285. font-weight: bold;
  1286. margin-bottom: 30rpx;
  1287. }
  1288. .confirm-content {
  1289. font-size: 28rpx;
  1290. color: #666;
  1291. margin-bottom: 40rpx;
  1292. line-height: 1.5;
  1293. }
  1294. .confirm-buttons {
  1295. display: flex;
  1296. justify-content: space-between;
  1297. }
  1298. .confirm-btn {
  1299. flex: 1;
  1300. margin: 0 10rpx;
  1301. padding: 20rpx;
  1302. border-radius: 10rpx;
  1303. border: none;
  1304. font-size: 28rpx;
  1305. }
  1306. .confirm-btn.cancel {
  1307. background-color: #f5f5f5;
  1308. }
  1309. .confirm-btn.confirm {
  1310. background-color: #fa5151;
  1311. color: #fff;
  1312. }
  1313. .chat-page {
  1314. display: flex;
  1315. flex-direction: column;
  1316. height: 100vh;
  1317. background-color: #f5f5f5;
  1318. }
  1319. /* 顶部导航 */
  1320. .chat-header {
  1321. display: flex;
  1322. align-items: center;
  1323. justify-content: space-between;
  1324. padding: 20rpx 30rpx;
  1325. background-color: #fff;
  1326. border-bottom: 1px solid #e5e5e5;
  1327. }
  1328. .header-left, .header-right {
  1329. width: 80rpx;
  1330. }
  1331. .icon-back, .icon-more {
  1332. font-size: 40rpx;
  1333. }
  1334. .header-center {
  1335. flex: 1;
  1336. text-align: center;
  1337. }
  1338. .chat-title {
  1339. display: block;
  1340. font-size: 36rpx;
  1341. font-weight: bold;
  1342. }
  1343. .online-status {
  1344. display: block;
  1345. font-size: 24rpx;
  1346. color: #999;
  1347. margin-top: 5rpx;
  1348. }
  1349. .online-status.online {
  1350. color: #07c160;
  1351. }
  1352. /* 消息列表 */
  1353. .message-list {
  1354. flex: 1;
  1355. padding: 20rpx;
  1356. overflow-y: scroll;
  1357. }
  1358. .loading-tip {
  1359. text-align: center;
  1360. padding: 20rpx;
  1361. color: #999;
  1362. font-size: 28rpx;
  1363. }
  1364. .message-item {
  1365. display: flex;
  1366. margin-bottom: 30rpx;
  1367. }
  1368. .message-item.message-self {
  1369. flex-direction: row-reverse;
  1370. }
  1371. .avatar {
  1372. width: 80rpx;
  1373. height: 80rpx;
  1374. border-radius: 8rpx;
  1375. margin: 0 20rpx;
  1376. }
  1377. .message-content-wrapper {
  1378. max-width: 70%;
  1379. display: inline-block;
  1380. }
  1381. .message-item.message-self .message-content-wrapper {
  1382. text-align: right; /* 关键:让气泡和状态提示整体右对齐 */
  1383. }
  1384. .message-name {
  1385. display: block;
  1386. font-size: 24rpx;
  1387. color: #999;
  1388. margin-bottom: 10rpx;
  1389. }
  1390. .message-bubble {
  1391. padding: 20rpx;
  1392. border-radius: 8rpx;
  1393. background-color: #fff;
  1394. word-wrap: break-word;
  1395. display: inline-block; /* 关键:气泡宽度由内容决定 */
  1396. max-width: 100%; /* 防止内容过长超出容器 */
  1397. position: relative;
  1398. }
  1399. .message-self .message-bubble {
  1400. background-color: #95ec69;
  1401. border-top-right-radius: 4rpx;
  1402. }
  1403. .message-bubble.bubble-self {
  1404. background-color: #95ec69;
  1405. }
  1406. .message-text {
  1407. font-size: 30rpx;
  1408. line-height: 1.5;
  1409. }
  1410. .message-image {
  1411. max-width: 400rpx;
  1412. border-radius: 8rpx;
  1413. }
  1414. .message-voice {
  1415. display: flex;
  1416. align-items: center;
  1417. gap: 10rpx;
  1418. }
  1419. .message-video {
  1420. width: 400rpx;
  1421. height: 300rpx;
  1422. }
  1423. .message-recalled {
  1424. color: #999;
  1425. font-size: 28rpx;
  1426. }
  1427. .message-status {
  1428. text-align: right;
  1429. font-size: 24rpx;
  1430. color: #999;
  1431. margin-top: 5rpx;
  1432. }
  1433. .message-status .read {
  1434. color: #07c160;
  1435. }
  1436. .message-status .failed {
  1437. color: #fa5151;
  1438. }
  1439. .message-time {
  1440. display: block;
  1441. text-align: right;
  1442. font-size: 22rpx;
  1443. color: #ccc;
  1444. margin-top: 5rpx;
  1445. }
  1446. /* 输入框 */
  1447. .input-bar {
  1448. display: flex;
  1449. align-items: center;
  1450. padding: 20rpx;
  1451. background-color: #fff;
  1452. border-top: 1px solid #e5e5e5;
  1453. }
  1454. .input-icon {
  1455. width: 80rpx;
  1456. height: 80rpx;
  1457. display: flex;
  1458. align-items: center;
  1459. justify-content: center;
  1460. font-size: 50rpx;
  1461. }
  1462. .input-field {
  1463. flex: 1;
  1464. height: 70rpx;
  1465. padding: 0 20rpx;
  1466. background-color: #f5f5f5;
  1467. border-radius: 8rpx;
  1468. font-size: 30rpx;
  1469. }
  1470. .voice-button {
  1471. flex: 1;
  1472. height: 70rpx;
  1473. line-height: 70rpx;
  1474. background-color: #f5f5f5;
  1475. border-radius: 8rpx;
  1476. text-align: center;
  1477. font-size: 30rpx;
  1478. border: none;
  1479. }
  1480. /* 表情面板 */
  1481. .emoji-panel {
  1482. display: flex;
  1483. flex-wrap: wrap;
  1484. padding: 20rpx;
  1485. background-color: #fff;
  1486. border-top: 1px solid #e5e5e5;
  1487. }
  1488. .emoji-item {
  1489. width: 80rpx;
  1490. height: 80rpx;
  1491. display: flex;
  1492. align-items: center;
  1493. justify-content: center;
  1494. font-size: 60rpx;
  1495. }
  1496. /* 更多功能面板 */
  1497. .more-panel {
  1498. display: flex;
  1499. padding: 40rpx;
  1500. background-color: #fff;
  1501. border-top: 1px solid #e5e5e5;
  1502. }
  1503. .more-item {
  1504. display: flex;
  1505. flex-direction: column;
  1506. align-items: center;
  1507. margin: 0 40rpx;
  1508. }
  1509. .more-icon {
  1510. width: 100rpx;
  1511. height: 100rpx;
  1512. display: flex;
  1513. align-items: center;
  1514. justify-content: center;
  1515. font-size: 60rpx;
  1516. background-color: #f5f5f5;
  1517. border-radius: 16rpx;
  1518. margin-bottom: 10rpx;
  1519. }
  1520. .more-text {
  1521. font-size: 24rpx;
  1522. color: #666;
  1523. }
  1524. /* 时间分隔线 */
  1525. .time-divider {
  1526. text-align: center;
  1527. padding: 20rpx 0;
  1528. }
  1529. .time-text {
  1530. display: inline-block;
  1531. padding: 8rpx 20rpx;
  1532. background-color: rgba(0, 0, 0, 0.1);
  1533. border-radius: 8rpx;
  1534. font-size: 22rpx;
  1535. color: #999;
  1536. }
  1537. /* 消息气泡失败状态 */
  1538. .bubble-failed {
  1539. background-color: #95ec69;
  1540. opacity: 0.6;
  1541. border: 2rpx solid #fa5151;
  1542. }
  1543. /* 消息状态优化 */
  1544. .message-status .sending {
  1545. color: #576b95;
  1546. }
  1547. .message-status .failed-group {
  1548. display: flex;
  1549. align-items: center;
  1550. gap: 10rpx;
  1551. }
  1552. .message-status .retry-btn {
  1553. color: #576b95;
  1554. text-decoration: underline;
  1555. cursor: pointer;
  1556. }
  1557. /* 消息操作菜单遮罩 */
  1558. .message-action-mask {
  1559. position: fixed;
  1560. top: 0;
  1561. left: 0;
  1562. right: 0;
  1563. bottom: 0;
  1564. background-color: rgba(0, 0, 0, 0.4);
  1565. z-index: 9999;
  1566. display: flex;
  1567. align-items: center;
  1568. justify-content: center;
  1569. }
  1570. /* 消息操作菜单 */
  1571. .message-action-menu {
  1572. width: 600rpx;
  1573. background-color: #fff;
  1574. border-radius: 20rpx;
  1575. overflow: hidden;
  1576. }
  1577. .message-action-menu .menu-item {
  1578. display: flex;
  1579. align-items: center;
  1580. justify-content: center;
  1581. gap: 15rpx;
  1582. padding: 30rpx;
  1583. font-size: 32rpx;
  1584. color: #333;
  1585. border-bottom: 1rpx solid #f0f0f0;
  1586. transition: background-color 0.2s;
  1587. }
  1588. .message-action-menu .menu-item:active {
  1589. background-color: #f5f5f5;
  1590. }
  1591. .message-action-menu .menu-item.cancel {
  1592. color: #999;
  1593. border-bottom: none;
  1594. margin-top: 20rpx;
  1595. border-top: 10rpx solid #f5f5f5;
  1596. }
  1597. .message-action-menu .menu-icon {
  1598. font-size: 36rpx;
  1599. }
  1600. </style>