chat.vue 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929
  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
  108. v-else-if="msg.messageType === 3"
  109. class="message-voice"
  110. :style="{width: getVoiceWidth(msg.duration)}"
  111. @click.stop="toggleVoicePlay(msg)">
  112. <text class="voice-duration">{{ msg.duration }}''</text>
  113. <view class="voice-icon-wrapper" :class="{playing: playingVoiceId === msg.messageId}">
  114. <image
  115. class="voice-icon"
  116. :src="msg.fromUserId === userId ? 'http://115.190.125.125:9000/static-images/%E6%88%91%E6%96%B9%E8%AF%AD%E9%9F%B3%E6%B6%88%E6%81%AF' : 'http://115.190.125.125:9000/static-images/%E5%AF%B9%E6%96%B9%E8%AF%AD%E9%9F%B3%E6%B6%88%E6%81%AF'"
  117. mode="aspectFit"></image>
  118. </view>
  119. <!-- 暂停后的继续播放按钮 -->
  120. <view
  121. v-if="pausedVoiceId === msg.messageId"
  122. class="voice-resume-btn"
  123. :class="{'resume-btn-left': msg.fromUserId === userId, 'resume-btn-right': msg.fromUserId !== userId}"
  124. @click.stop="resumeVoice">
  125. <text class="resume-icon">▶</text>
  126. </view>
  127. </view>
  128. <!-- 视频消息 -->
  129. <video
  130. v-else-if="msg.messageType === 4"
  131. class="message-video"
  132. :src="msg.mediaUrl"
  133. controls />
  134. <!-- 撤回消息 -->
  135. <text v-if="msg.isRecalled" class="message-recalled">
  136. 消息已撤回
  137. </text>
  138. </view>
  139. <!-- 消息状态(自己的消息) -->
  140. <view v-if="msg.fromUserId === userId" class="message-status">
  141. <text v-if="msg.sendStatus === 1" class="sending">发送中...</text>
  142. <text v-else-if="msg.sendStatus === 2">已送达</text>
  143. <text v-else-if="msg.sendStatus === 3" class="read">已读</text>
  144. <view v-else-if="msg.sendStatus === 4" class="failed-group">
  145. <text class="failed">发送失败</text>
  146. <text class="retry-btn" @click.stop="retryMessage(msg)">重试</text>
  147. </view>
  148. </view>
  149. </view>
  150. </view>
  151. </view>
  152. </scroll-view>
  153. <!-- 新增:消息发送限制提示 -->
  154. <view class="message-limit-tip">
  155. <!-- 同时判断isVip和hasMessageLimit,增强可靠性 -->
  156. <text v-if="isVip || !hasMessageLimit" class="vip-tip">✨ VIP特权:无发送次数限制</text>
  157. <text v-else class="limit-tip">
  158. 今日剩余可发送消息:{{ Math.max(remainingCount, 0) }} 条<text class="vip-link" @click="goToVipPage">(非VIP每日限5条)</text>
  159. </text>
  160. </view>
  161. <!-- 输入框 -->
  162. <view class="input-bar">
  163. <!-- 语音按钮 -->
  164. <view class="input-icon" @click="switchInputType">
  165. <text>{{ inputType === 'text' ? '🎤' : '⌨️' }}</text>
  166. </view>
  167. <!-- 文本输入 -->
  168. <input
  169. v-if="inputType === 'text'"
  170. class="input-field"
  171. v-model="inputText"
  172. placeholder="说点什么..."
  173. confirm-type="send"
  174. @confirm="sendTextMessage"
  175. @input="onInputChange" />
  176. <!-- 语音按钮 -->
  177. <button
  178. v-else
  179. class="voice-button"
  180. @touchstart="startVoiceRecord"
  181. @touchmove="onVoiceTouchMove"
  182. @touchend="stopVoiceRecord"
  183. @touchcancel="cancelVoiceRecord">
  184. 按住说话
  185. </button>
  186. <!-- 表情按钮 -->
  187. <view v-if="inputType === 'text'" class="input-icon" @click="showEmojiPanel = !showEmojiPanel">
  188. <text>😊</text>
  189. </view>
  190. <!-- 发送按钮 -->
  191. <view v-if="inputType === 'text'" class="send-button" :class="{disabled: !inputText.trim()}" @click="sendTextMessage">
  192. <text>发送</text>
  193. </view>
  194. </view>
  195. <!-- 表情面板 -->
  196. <view v-if="showEmojiPanel" class="emoji-panel">
  197. <text
  198. v-for="emoji in emojis"
  199. :key="emoji"
  200. class="emoji-item"
  201. @click="insertEmoji(emoji)">
  202. {{ emoji }}
  203. </text>
  204. </view>
  205. <!-- 消息操作菜单 -->
  206. <view v-if="showMessageAction" class="message-action-mask" @click="hideMessageMenu">
  207. <view class="message-action-menu" @click.stop>
  208. <view class="menu-item" @click="copyMessage" v-if="selectedMessage && selectedMessage.messageType === 1">
  209. <text class="menu-icon">📋</text>
  210. <text>复制</text>
  211. </view>
  212. <view class="menu-item" @click="recallMessage" v-if="selectedMessage && selectedMessage.fromUserId === userId && canRecall(selectedMessage)">
  213. <text class="menu-icon">↩️</text>
  214. <text>撤回</text>
  215. </view>
  216. <view class="menu-item" @click="deleteMessage">
  217. <text class="menu-icon">🗑️</text>
  218. <text>删除</text>
  219. </view>
  220. <view class="menu-item cancel" @click="hideMessageMenu">
  221. <text>取消</text>
  222. </view>
  223. </view>
  224. </view>
  225. <!-- 录音中提示 -->
  226. <view v-if="showVoiceRecording" class="voice-recording-mask">
  227. <view class="voice-recording-box" :class="{'canceling': voiceCanceling}">
  228. <view class="voice-wave-container">
  229. <view class="voice-wave-bar bar1" :style="{transform: `scaleY(${voiceVolume})`}"></view>
  230. <view class="voice-wave-bar bar2" :style="{transform: `scaleY(${voiceVolume * 1.2})`}"></view>
  231. <view class="voice-wave-bar bar3" :style="{transform: `scaleY(${voiceVolume * 1.5})`}"></view>
  232. <view class="voice-wave-bar bar4" :style="{transform: `scaleY(${voiceVolume * 1.3})`}"></view>
  233. <view class="voice-wave-bar bar5" :style="{transform: `scaleY(${voiceVolume})`}"></view>
  234. </view>
  235. <text class="voice-text">{{ voiceCanceling ? '松开取消发送' : '正在录音...' }}</text>
  236. <text class="voice-time">{{ voiceRecordingTime }}''</text>
  237. <text class="voice-tip" v-if="!voiceCanceling">松开发送,上滑取消</text>
  238. </view>
  239. </view>
  240. </view>
  241. </template>
  242. <script>
  243. import timManager from '@/utils/tim-manager.js';
  244. import TIM from 'tim-wx-sdk';
  245. import presenceManager from '@/utils/presence-manager.js';
  246. export default {
  247. data() {
  248. return {
  249. isBlockedByTarget: false,
  250. userId: null,
  251. userAvatar: '',
  252. targetUserId: null,
  253. targetUserName: '',
  254. targetUserAvatar: '',
  255. messages: [],
  256. inputText: '',
  257. inputType: 'text',
  258. conversationID: '',
  259. scrollToView: '',
  260. showEmojiPanel: false,
  261. isLogin: false,
  262. // 消息操作菜单
  263. showMessageAction: false,
  264. selectedMessage: null,
  265. selectedMessageIndex: -1,
  266. menuTop: 0,
  267. // 加载更多
  268. loading: false,
  269. noMore: false,
  270. nextReqMessageID: '',
  271. isTargetOnline: false,
  272. emojis: ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩', '🥳'],
  273. showMoreOptionsModal: false, // 控制更多选项弹窗显示
  274. showBlockConfirmModal: false, // 控制拉黑确认弹窗显示
  275. isVip: false, // 是否VIP用户
  276. remainingCount: 5, // 剩余可发送消息数(非VIP默认5)
  277. hasMessageLimit: true, // 是否有发送限制(VIP为false)
  278. // 语音录制相关
  279. recorderManager: null, // 录音管理器
  280. isRecording: false, // 是否正在录音
  281. voiceStartTime: 0, // 录音开始时间
  282. voiceDuration: 0, // 录音时长
  283. voiceTempPath: '', // 录音临时文件路径
  284. showVoiceRecording: false, // 显示录音中提示
  285. voiceRecordingTime: 0, // 录音计时(秒)
  286. voiceRecordingTimer: null, // 录音计时器
  287. voiceTouchStartY: 0, // 录音按下时的Y坐标
  288. voiceCanceling: false, // 是否正在取消录音
  289. voiceVolume: 0.3, // 录音音量(0-1),控制波形高度
  290. playingVoiceId: null, // 当前播放的语音消息ID
  291. pausedVoiceId: null, // 当前暂停的语音消息ID
  292. currentAudioContext: null, // 当前音频上下文
  293. onlineStatusPollingTimer: null, // 在线状态轮询定时器
  294. voiceRecordCancelled: false // 录音是否已被取消(防止权限允许后自动恢复)
  295. };
  296. },
  297. async onLoad(options) {
  298. console.log('=== 聊天页面加载 ===');
  299. // 严格验证登录状态
  300. const token = uni.getStorageSync('token');
  301. const userInfo = uni.getStorageSync('userInfo');
  302. const storedUserId = uni.getStorageSync('userId');
  303. console.log('登录状态检查:');
  304. console.log('- token:', token ? '存在' : '不存在');
  305. console.log('- userInfo:', userInfo);
  306. console.log('- storedUserId:', storedUserId);
  307. if (!token || !userInfo) {
  308. console.error('❌ 未登录或登录信息不完整');
  309. uni.showModal({
  310. title: '需要登录',
  311. content: '请先登录后再进行聊天',
  312. showCancel: false,
  313. success: () => {
  314. uni.reLaunch({
  315. url: '/pages/page3/page3'
  316. });
  317. }
  318. });
  319. return;
  320. }
  321. // 优先使用 storage 中的 userId,确保一致性
  322. let rawUserId = storedUserId || userInfo.userId || userInfo.id || userInfo.user_id;
  323. // 转换为数字类型(确保与消息列表页面一致)
  324. if (typeof rawUserId === 'string') {
  325. rawUserId = parseInt(rawUserId);
  326. }
  327. if (!rawUserId || isNaN(rawUserId)) {
  328. console.error('❌ 无法获取有效的用户ID');
  329. uni.showModal({
  330. title: '用户信息错误',
  331. content: '无法获取用户ID,请重新登录',
  332. showCancel: false,
  333. success: () => {
  334. uni.removeStorageSync('token');
  335. uni.removeStorageSync('userInfo');
  336. uni.removeStorageSync('userId');
  337. uni.reLaunch({
  338. url: '/pages/page3/page3'
  339. });
  340. }
  341. });
  342. return;
  343. }
  344. // 保存用户ID(TIM需要字符串格式)
  345. this.userId = String(rawUserId);
  346. this.userAvatar = userInfo.avatar || userInfo.avatarUrl || '/static/default-avatar.svg';
  347. // 获取对方用户信息(确保是字符串格式)
  348. this.targetUserId = String(options.targetUserId);
  349. this.targetUserName = decodeURIComponent(options.targetUserName || '用户');
  350. this.targetUserAvatar = decodeURIComponent(options.targetUserAvatar || '/static/default-avatar.svg');
  351. // 生成会话 ID
  352. this.conversationID = `C2C${this.targetUserId}`;
  353. console.log('✅ 聊天页面初始化成功:');
  354. console.log(' - 当前用户ID:', rawUserId, '(TIM格式:', this.userId, ')');
  355. console.log(' - 对方用户ID:', this.targetUserId);
  356. console.log(' - 会话ID:', this.conversationID);
  357. // 初始化 TIM
  358. await this.initTIM();
  359. // 获取用户消息发送限制(VIP状态+剩余次数)
  360. await this.getUserMessageLimit();
  361. // 等待 SDK Ready 后再加载消息
  362. await this.waitForSDKReady();
  363. // 先检查拉黑状态
  364. this.isBlockedByTarget = await this.checkIsBlockedByTarget();
  365. if (this.isBlockedByTarget) {
  366. uni.showToast({
  367. title: '你已被对方拉黑,无法发送消息',
  368. icon: 'none',
  369. duration: 3000
  370. });
  371. }
  372. // 加载历史消息
  373. await this.loadMessages();
  374. // 监听新消息
  375. this.listenMessages();
  376. // 初始化在线状态监听
  377. this.initPresence();
  378. // 发送已读回执(标记对方发来的消息为已读)
  379. this.sendReadReceipt();
  380. },
  381. onUnload() {
  382. // 页面卸载时移除监听
  383. timManager.offMessage(this.handleNewMessage);
  384. // 移除消息状态变更监听(已注释)
  385. /*
  386. if (timManager.tim && this.handleStatusChange) {
  387. timManager.tim.off(TIM.EVENT.MESSAGE_STATUS_CHANGED, this.handleStatusChange);
  388. }
  389. */
  390. // 清理在线状态监听
  391. this.cleanupPresence();
  392. },
  393. methods: {
  394. /**
  395. * 计算语音消息宽度(根据时长动态变化)
  396. * @param {Number} duration 语音时长(秒)
  397. * @return {String} 宽度值
  398. */
  399. getVoiceWidth(duration) {
  400. // 基础宽度 100rpx,每秒增加 10rpx,最大 400rpx
  401. const baseWidth = 100;
  402. const widthPerSecond = 10;
  403. const maxWidth = 400;
  404. const width = Math.min(baseWidth + (duration * widthPerSecond), maxWidth);
  405. return width + 'rpx';
  406. },
  407. /**
  408. * 初始化 TIM
  409. */
  410. async initTIM() {
  411. try {
  412. // 如果未初始化,先初始化
  413. if (!timManager.tim) {
  414. timManager.init(1600109674); // ✅ 已更新为正确的 SDKAppID
  415. }
  416. // 如果未登录,获取 userSig 并登录
  417. if (!timManager.isLogin) {
  418. // 先导入当前用户和目标用户到腾讯云IM
  419. await this.importUsers();
  420. // 从后端获取 userSig
  421. const userSig = await this.getUserSig();
  422. await timManager.login(this.userId, userSig);
  423. }
  424. this.isLogin = true;
  425. console.log('✅ TIM 初始化完成');
  426. } catch (error) {
  427. console.error('❌ TIM 初始化失败:', error);
  428. uni.showToast({
  429. title: '连接失败,请重试',
  430. icon: 'none'
  431. });
  432. }
  433. },
  434. /**
  435. * 跳转到VIP页面
  436. */
  437. goToVipPage() {
  438. console.log('点击跳转VIP页面');
  439. // 替换为你的实际VIP页面路径(例如会员开通页面)
  440. uni.navigateTo({
  441. url: '/pages/vip/index', // 请根据项目实际路径修改
  442. success: () => {
  443. console.log('跳转VIP页面成功');
  444. },
  445. fail: (err) => {
  446. console.error('跳转VIP页面失败:', err);
  447. uni.showToast({
  448. title: 'VIP页面不存在',
  449. icon: 'none'
  450. });
  451. }
  452. });
  453. },
  454. more(userid) {
  455. console.log('点击了更多按钮,开始跳转...', userid);
  456. // 如果目标页面是普通页面,用navigateTo(保留当前页面);如果是tabbar页面,用switchTab
  457. uni.navigateTo({
  458. url: `/pages/message/more?userid=${userid}`,
  459. success: () => {
  460. console.log('跳转成功');
  461. },
  462. fail: (err) => {
  463. console.error('跳转失败:', err);
  464. uni.showToast({
  465. title: '页面不存在或路径错误',
  466. icon: 'none'
  467. });
  468. }
  469. });
  470. },
  471. /**
  472. * 导入用户到腾讯云IM
  473. */
  474. async importUsers() {
  475. try {
  476. console.log('📥 开始导入用户到腾讯云IM...');
  477. console.log(' - 当前用户ID:', this.userId, '(类型:', typeof this.userId, ')');
  478. console.log(' - 目标用户ID:', this.targetUserId, '(类型:', typeof this.targetUserId, ')');
  479. // 验证用户ID
  480. if (!this.userId || this.userId === 'undefined' || this.userId === 'null') {
  481. throw new Error('当前用户ID无效: ' + this.userId);
  482. }
  483. if (!this.targetUserId || this.targetUserId === 'undefined' || this.targetUserId === 'null') {
  484. throw new Error('目标用户ID无效: ' + this.targetUserId);
  485. }
  486. // 导入当前用户(确保userId是字符串)
  487. const currentUserRes = await uni.request({
  488. url: 'http://localhost:8083/api/im/importUser',
  489. method: 'POST',
  490. data: {
  491. userId: String(this.userId),
  492. nickname: '用户' + this.userId
  493. },
  494. header: {
  495. 'Content-Type': 'application/json'
  496. }
  497. });
  498. console.log(' - 当前用户导入结果:', currentUserRes[1].data);
  499. // 导入目标用户(确保userId是字符串)
  500. const targetUserRes = await uni.request({
  501. url: 'http://localhost:8083/api/im/importUser',
  502. method: 'POST',
  503. data: {
  504. userId: String(this.targetUserId),
  505. nickname: this.targetUserName || '用户' + this.targetUserId
  506. },
  507. header: {
  508. 'Content-Type': 'application/json'
  509. }
  510. });
  511. console.log(' - 目标用户导入结果:', targetUserRes[1].data);
  512. console.log('✅ 用户导入成功');
  513. } catch (error) {
  514. console.log('⚠️ 用户导入失败(可能已存在):', error);
  515. // 导入失败不影响登录,因为用户可能已经存在
  516. }
  517. },
  518. /**
  519. * 获取 UserSig
  520. */
  521. async getUserSig() {
  522. try {
  523. const [err, res] = await uni.request({
  524. url: 'http://localhost:8083/api/im/getUserSig',
  525. method: 'GET',
  526. data: {
  527. userId: this.userId
  528. }
  529. });
  530. if (err) {
  531. throw new Error('请求失败');
  532. }
  533. if (res.data && res.data.code === 200) {
  534. return res.data.data.userSig;
  535. } else {
  536. throw new Error('获取 UserSig 失败');
  537. }
  538. } catch (error) {
  539. console.error('❌ 获取 UserSig 失败:', error);
  540. throw error;
  541. }
  542. },
  543. /**
  544. * 等待 SDK Ready
  545. */
  546. async waitForSDKReady() {
  547. return new Promise((resolve) => {
  548. // 如果已经 ready,立即返回
  549. if (timManager.isLogin) {
  550. console.log('✅ SDK 已就绪');
  551. resolve();
  552. return;
  553. }
  554. // 否则等待 SDK ready 事件
  555. console.log('⏳ 等待 SDK 就绪...');
  556. const checkReady = setInterval(() => {
  557. if (timManager.isLogin) {
  558. console.log('✅ SDK 已就绪');
  559. clearInterval(checkReady);
  560. resolve();
  561. }
  562. }, 100); // 每 100ms 检查一次
  563. // 超时保护(10秒后强制继续)
  564. setTimeout(() => {
  565. console.log('⚠️ 等待 SDK 就绪超时,继续执行');
  566. clearInterval(checkReady);
  567. resolve();
  568. }, 10000);
  569. });
  570. },
  571. /**
  572. * 加载历史消息
  573. */
  574. async loadMessages() {
  575. try {
  576. const res = await timManager.tim.getMessageList({
  577. conversationID: this.conversationID,
  578. count: 20
  579. });
  580. const messageList = res.data.messageList;
  581. this.nextReqMessageID = res.data.nextReqMessageID;
  582. this.noMore = !res.data.isCompleted;
  583. // 转换为我们的消息格式
  584. this.messages = messageList.map(msg => this.convertMessage(msg));
  585. // 滚动到底部
  586. this.$nextTick(() => {
  587. this.scrollToBottom();
  588. });
  589. // 标记已读
  590. await timManager.setMessageRead(this.conversationID);
  591. } catch (error) {
  592. console.error('❌ 加载消息失败:', error);
  593. }
  594. },
  595. /**
  596. * 加载更多消息(上拉)
  597. */
  598. async loadMoreMessages() {
  599. if (this.loading || !this.nextReqMessageID) {
  600. return;
  601. }
  602. this.loading = true;
  603. try {
  604. const res = await timManager.tim.getMessageList({
  605. conversationID: this.conversationID,
  606. nextReqMessageID: this.nextReqMessageID,
  607. count: 20
  608. });
  609. const messageList = res.data.messageList;
  610. this.nextReqMessageID = res.data.nextReqMessageID;
  611. this.noMore = !res.data.isCompleted;
  612. // 转换并添加到消息列表前面
  613. const newMessages = messageList.map(msg => this.convertMessage(msg));
  614. this.messages = [...newMessages, ...this.messages];
  615. } catch (error) {
  616. console.error('❌ 加载更多消息失败:', error);
  617. } finally {
  618. this.loading = false;
  619. }
  620. },
  621. /**
  622. * 监听新消息
  623. */
  624. listenMessages() {
  625. const handleNewMessage = (event) => {
  626. // 兼容不同格式的事件数据
  627. const messageList = event.data || event || [];
  628. // 确保是数组格式
  629. const messagesToProcess = Array.isArray(messageList) ? messageList : [messageList];
  630. messagesToProcess.forEach(msg => {
  631. // 只处理当前会话的消息
  632. if (msg.conversationID === this.conversationID) {
  633. // 查找消息在本地列表中的位置
  634. const existingIndex = this.messages.findIndex(m => m.messageId === msg.ID);
  635. if (existingIndex > -1) {
  636. // 更新现有消息状态(使用$set确保视图更新)
  637. this.$set(this.messages, existingIndex, this.convertMessage(msg));
  638. } else {
  639. // 添加新消息
  640. this.messages.push(this.convertMessage(msg));
  641. this.$nextTick(() => {
  642. this.scrollToBottom();
  643. });
  644. }
  645. // 标记已读
  646. timManager.setMessageRead(this.conversationID);
  647. }
  648. });
  649. };
  650. this.handleNewMessage = handleNewMessage;
  651. timManager.onMessage(handleNewMessage);
  652. // 添加消息状态变更监听
  653. // 注释原因:TIM.EVENT.MESSAGE_STATUS_CHANGED 在当前SDK版本中可能不存在,导致参数验证失败
  654. // 消息状态更新已通过 handleNewMessage 处理,暂时不需要单独监听
  655. /*
  656. if (timManager.tim) {
  657. const handleStatusChange = (event) => {
  658. console.log('📝 消息状态变更:', event);
  659. // MESSAGE_STATUS_CHANGED 事件的数据结构不同
  660. if (event && event.data && Array.isArray(event.data)) {
  661. event.data.forEach(msg => {
  662. if (msg.conversationID === this.conversationID) {
  663. const existingIndex = this.messages.findIndex(m => m.messageId === msg.ID);
  664. if (existingIndex > -1) {
  665. this.$set(this.messages, existingIndex, this.convertMessage(msg));
  666. }
  667. }
  668. });
  669. }
  670. };
  671. this.handleStatusChange = handleStatusChange;
  672. timManager.tim.on(TIM.EVENT.MESSAGE_STATUS_CHANGED, handleStatusChange);
  673. }
  674. */
  675. },
  676. /**
  677. * 发送已读回执
  678. */
  679. sendReadReceipt() {
  680. try {
  681. console.log('📨 发送已读回执给用户:', this.targetUserId);
  682. // 通过WebSocket发送已读回执
  683. const message = {
  684. type: 'READ_RECEIPT', // 已读回执类型
  685. fromUserId: parseInt(this.userId),
  686. toUserId: parseInt(this.targetUserId),
  687. timestamp: Date.now()
  688. };
  689. // 使用presenceManager的WebSocket发送
  690. const presenceManager = require('@/utils/presence-manager.js').default;
  691. if (presenceManager.isConnected) {
  692. presenceManager.sendMessage(message);
  693. console.log('✅ 已读回执发送成功');
  694. } else {
  695. console.warn('⚠️ WebSocket未连接,无法发送已读回执');
  696. }
  697. } catch (error) {
  698. console.error('❌ 发送已读回执失败:', error);
  699. }
  700. },
  701. /**
  702. * 监听已读回执
  703. */
  704. listenReadReceipt() {
  705. // 在WebSocket消息处理中添加已读回执的监听
  706. // 这个方法会在initPresence中被调用
  707. console.log('👂 开始监听已读回执');
  708. },
  709. /**
  710. * 处理已读回执
  711. */
  712. handleReadReceipt(data) {
  713. try {
  714. console.log('📬 收到已读回执:', data);
  715. // 更新本地消息状态为已读
  716. this.messages.forEach((msg, index) => {
  717. // 只更新自己发送给对方的消息
  718. if (msg.fromUserId === this.userId &&
  719. msg.toUserId === this.targetUserId &&
  720. msg.sendStatus === 2) { // 只更新已送达的消息
  721. this.$set(this.messages[index], 'sendStatus', 3); // 更新为已读
  722. console.log(`✅ 消息 ${msg.messageId} 状态更新为已读`);
  723. }
  724. });
  725. } catch (error) {
  726. console.error('❌ 处理已读回执失败:', error);
  727. }
  728. },
  729. /**
  730. * 转换消息格式
  731. */
  732. convertMessage(timMsg) {
  733. let sendStatus = 1; // 默认发送中
  734. // 完善的状态判断逻辑
  735. if (timMsg.status === TIM.TYPES.MSG_STATUS_SEND_SUCC ||
  736. timMsg.status === 'success' ||
  737. timMsg.status === TIM.TYPES.MSG_STATUS_RECEIVED) {
  738. sendStatus = 2; // 已送达
  739. } else if (timMsg.status === TIM.TYPES.MSG_STATUS_SEND_FAIL ||
  740. timMsg.status === 'fail') {
  741. sendStatus = 4; // 发送失败
  742. } else if (timMsg.status === TIM.TYPES.MSG_STATUS_HAS_READ ||
  743. timMsg.status === 'read') {
  744. sendStatus = 3; // 已读
  745. } else if (timMsg.status === TIM.TYPES.MSG_STATUS_SENDING) {
  746. sendStatus = 1; // 发送中
  747. }
  748. // 处理不同类型消息的URL和时长
  749. let mediaUrl = '';
  750. let duration = 0;
  751. let messageType = 1;
  752. let content = '';
  753. if (timMsg.type === TIM.TYPES.MSG_TEXT) {
  754. messageType = 1;
  755. content = timMsg.payload.text;
  756. } else if (timMsg.type === TIM.TYPES.MSG_IMAGE && timMsg.payload.imageInfoArray) {
  757. messageType = 2;
  758. content = '[图片]';
  759. mediaUrl = timMsg.payload.imageInfoArray[0]?.url || '';
  760. } else if (timMsg.type === TIM.TYPES.MSG_SOUND) {
  761. // 原生语音消息
  762. messageType = 3;
  763. content = '[语音]';
  764. mediaUrl = timMsg.payload.url || timMsg.payload.remoteAudioUrl || '';
  765. duration = timMsg.payload.second || 0;
  766. } else if (timMsg.type === TIM.TYPES.MSG_CUSTOM) {
  767. // 自定义消息(我们的语音消息)
  768. try {
  769. const customData = JSON.parse(timMsg.payload.data);
  770. if (customData.type === 'voice') {
  771. messageType = 3;
  772. content = '[语音]';
  773. mediaUrl = customData.url;
  774. // duration已经是秒数,直接使用
  775. duration = parseInt(customData.duration) || 0;
  776. }
  777. } catch (e) {
  778. console.error('解析自定义消息失败:', e);
  779. }
  780. } else if (timMsg.type === TIM.TYPES.MSG_VIDEO) {
  781. messageType = 4;
  782. content = '[视频]';
  783. }
  784. return {
  785. messageId: timMsg.ID,
  786. fromUserId: timMsg.from,
  787. toUserId: timMsg.to,
  788. messageType: messageType,
  789. content: content || '[消息]',
  790. mediaUrl: mediaUrl,
  791. duration: duration,
  792. payload: timMsg.payload, // 保留原始payload
  793. sendStatus: sendStatus,
  794. sendTime: new Date(timMsg.time * 1000),
  795. isRecalled: timMsg.isRevoked,
  796. fromUserName: timMsg.from === this.userId ? '我' : this.targetUserName
  797. };
  798. },
  799. /**
  800. * 检查对方是否拉黑自己
  801. */
  802. async checkIsBlockedByTarget() {
  803. try {
  804. const [err, res] = await uni.request({
  805. url: 'http://localhost:8083/api/chatfriend/checkBlock',
  806. method: 'POST',
  807. data: {
  808. userId: this.userId, // 自己的ID
  809. targetUserId: this.targetUserId // 对方的ID
  810. },
  811. header: {
  812. 'Content-Type': 'application/json'
  813. }
  814. });
  815. console.log('拉黑检查接口响应:', res.data); // 方便调试
  816. if (err) {
  817. console.error('网络请求失败:', err);
  818. return false; // 网络错误时默认按“未被拉黑”处理(避免误拦截)
  819. }
  820. // 严格校验接口返回格式
  821. if (!res.data || res.data.code !== 200) {
  822. console.error('接口返回格式错误:', res.data);
  823. return false;
  824. }
  825. // 关键修复:后端返回 data:true 表示“已被拉黑”,直接返回该值
  826. // 你的接口中 data 就是布尔值,无需额外解析
  827. const isBlocked = res.data.data;
  828. console.log('是否被拉黑:', isBlocked); // 确认这里输出为 true(被拉黑时)
  829. return isBlocked;
  830. } catch (error) {
  831. console.error('检查拉黑状态失败:', error);
  832. return false;
  833. }
  834. },
  835. /**
  836. * 发送文本消息
  837. */
  838. async sendTextMessage() {
  839. if (this.hasMessageLimit && this.remainingCount <= 0) {
  840. uni.showToast({
  841. title: '今日消息发送次数已用完,开通VIP无限制',
  842. icon: 'none',
  843. duration: 2000
  844. });
  845. return;
  846. }
  847. if (!this.inputText.trim()) {
  848. return;
  849. }
  850. const content = this.inputText;
  851. this.inputText = '';
  852. // 先检查是否被拉黑
  853. const isBlocked = await this.checkIsBlockedByTarget();
  854. if (isBlocked) {
  855. // 被拉黑时的处理保持不变
  856. const failedMessage = {
  857. messageId: 'failed_' + Date.now(),
  858. fromUserId: this.userId,
  859. toUserId: this.targetUserId,
  860. messageType: 1,
  861. content: content,
  862. sendStatus: 4, // 4表示发送失败
  863. sendTime: new Date(),
  864. fromUserName: '我'
  865. };
  866. this.messages.push(failedMessage);
  867. this.scrollToBottom();
  868. uni.showToast({
  869. title: '消息发送失败',
  870. icon: 'none'
  871. });
  872. return;
  873. }
  874. // 创建临时消息显示"发送中"
  875. const tempMessageId = 'temp_' + Date.now();
  876. const tempMessage = {
  877. messageId: tempMessageId,
  878. fromUserId: this.userId,
  879. toUserId: this.targetUserId,
  880. messageType: 1,
  881. content: content,
  882. sendStatus: 1, // 发送中
  883. sendTime: new Date(),
  884. fromUserName: '我'
  885. };
  886. this.messages.push(tempMessage);
  887. this.scrollToBottom();
  888. // 未被拉黑,正常发送
  889. try {
  890. const sendPromise = timManager.sendTextMessage(this.targetUserId, content);
  891. const timeoutPromise = new Promise((_, reject) => {
  892. setTimeout(() => reject(new Error('发送超时')), 15000);
  893. });
  894. const message = await Promise.race([sendPromise, timeoutPromise]);
  895. // 替换临时消息
  896. const tempIndex = this.messages.findIndex(m => m.messageId === tempMessageId);
  897. if (tempIndex > -1) {
  898. const convertedMsg = this.convertMessage(message);
  899. // 强制设置为已送达
  900. convertedMsg.sendStatus = 2;
  901. this.$set(this.messages, tempIndex, convertedMsg);
  902. }
  903. console.log('✅ 消息发送成功');
  904. this.syncMessageToMySQL(message);
  905. if (!this.isVip) {
  906. await this.updateMessageCount();
  907. }
  908. } catch (error) {
  909. console.error('❌ 消息发送失败:', error);
  910. // 更新临时消息为失败状态
  911. const tempIndex = this.messages.findIndex(m => m.messageId === tempMessageId);
  912. if (tempIndex > -1) {
  913. this.$set(this.messages[tempIndex], 'sendStatus', 4);
  914. }
  915. // 恢复输入框内容
  916. this.inputText = content;
  917. uni.showToast({
  918. title: '发送失败: ' + error.message,
  919. icon: 'none'
  920. });
  921. }
  922. },
  923. /**
  924. * 选择图片
  925. */
  926. chooseImage() {
  927. uni.chooseImage({
  928. count: 1,
  929. sizeType: ['compressed'],
  930. sourceType: ['album', 'camera'],
  931. success: async (res) => {
  932. // 1. 先检查是否被拉黑
  933. const isBlocked = await this.checkIsBlockedByTarget();
  934. if (isBlocked) {
  935. uni.showToast({
  936. title: '你已被对方拉黑,无法发送消息',
  937. icon: 'none'
  938. });
  939. return;
  940. }
  941. const tempFilePath = res.tempFilePaths[0];
  942. try {
  943. uni.showLoading({ title: '发送中...' });
  944. const message = await timManager.sendImageMessage(this.targetUserId, tempFilePath);
  945. this.messages.push(this.convertMessage(message));
  946. this.scrollToBottom();
  947. uni.hideLoading();
  948. console.log('✅ 图片发送成功');
  949. } catch (error) {
  950. uni.hideLoading();
  951. console.error('❌ 图片发送失败:', error);
  952. uni.showToast({
  953. title: '发送失败',
  954. icon: 'none'
  955. });
  956. }
  957. }
  958. });
  959. },
  960. /**
  961. * 输入框内容变化
  962. */
  963. onInputChange() {
  964. // 腾讯云 IM 可以实现正在输入状态,这里暂时省略
  965. console.log('输入中...');
  966. },
  967. /**
  968. * 同步消息到MySQL数据库(双重存储保障)
  969. */
  970. async syncMessageToMySQL(timMessage) {
  971. try {
  972. console.log('🔄 同步消息到MySQL...', timMessage.ID);
  973. // 构建同步参数
  974. const syncData = {
  975. messageId: timMessage.ID,
  976. fromUserId: timMessage.from,
  977. toUserId: timMessage.to,
  978. messageType: this.getMessageType(timMessage),
  979. content: this.getMessageContent(timMessage),
  980. sendTime: timMessage.time // TIM返回的是秒级时间戳
  981. };
  982. // 如果是图片消息,添加媒体信息
  983. if (timMessage.type === 'TIMImageElem' && timMessage.payload.imageInfoArray) {
  984. const imageInfo = timMessage.payload.imageInfoArray[0];
  985. syncData.mediaUrl = imageInfo.imageUrl;
  986. syncData.thumbnailUrl = imageInfo.imageUrl;
  987. }
  988. // 如果是语音消息,添加语音信息
  989. if (timMessage.type === 'TIMSoundElem' && timMessage.payload) {
  990. syncData.mediaUrl = timMessage.payload.url || timMessage.payload.remoteAudioUrl;
  991. syncData.duration = timMessage.payload.second || 0;
  992. syncData.mediaSize = timMessage.payload.size || 0;
  993. }
  994. // 如果是自定义消息(我们的语音消息)
  995. if (timMessage.type === 'TIMCustomElem' && timMessage.payload) {
  996. try {
  997. const customData = JSON.parse(timMessage.payload.data);
  998. if (customData.type === 'voice') {
  999. syncData.mediaUrl = customData.url;
  1000. syncData.duration = customData.duration;
  1001. syncData.mediaSize = customData.size || 0;
  1002. }
  1003. } catch (e) {
  1004. console.error('解析自定义消息失败:', e);
  1005. }
  1006. }
  1007. // 调用后端同步接口
  1008. const res = await uni.request({
  1009. url: 'http://localhost:8083/api/chat/syncTIMMessage',
  1010. method: 'POST',
  1011. data: syncData,
  1012. header: {
  1013. 'Content-Type': 'application/json'
  1014. }
  1015. });
  1016. if (res[1].data.code === 200) {
  1017. console.log('✅ 消息已同步到MySQL:', timMessage.ID);
  1018. } else {
  1019. console.warn('⚠️ 消息同步失败:', res[1].data.message);
  1020. }
  1021. } catch (error) {
  1022. console.error('❌ 同步消息到MySQL失败:', error);
  1023. // 同步失败不影响聊天功能,只记录日志
  1024. }
  1025. },
  1026. /**
  1027. * 获取消息类型
  1028. */
  1029. getMessageType(timMessage) {
  1030. const typeMap = {
  1031. 'TIMTextElem': 1, // 文本
  1032. 'TIMImageElem': 2, // 图片
  1033. 'TIMSoundElem': 3, // 语音
  1034. 'TIMVideoFileElem': 4, // 视频
  1035. 'TIMFileElem': 5 // 文件
  1036. };
  1037. // 处理自定义消息(我们的语音消息)
  1038. if (timMessage.type === 'TIMCustomElem' && timMessage.payload) {
  1039. try {
  1040. const customData = JSON.parse(timMessage.payload.data);
  1041. if (customData.type === 'voice') {
  1042. return 3; // 语音消息
  1043. }
  1044. } catch (e) {
  1045. console.error('解析自定义消息类型失败:', e);
  1046. }
  1047. }
  1048. return typeMap[timMessage.type] || 1;
  1049. },
  1050. /**
  1051. * 获取消息内容
  1052. */
  1053. getMessageContent(timMessage) {
  1054. switch (timMessage.type) {
  1055. case 'TIMTextElem':
  1056. return timMessage.payload.text || '';
  1057. case 'TIMImageElem':
  1058. return '[图片]';
  1059. case 'TIMSoundElem':
  1060. return '[语音]';
  1061. case 'TIMVideoFileElem':
  1062. return '[视频]';
  1063. case 'TIMFileElem':
  1064. return '[文件]';
  1065. default:
  1066. return '[未知消息]';
  1067. }
  1068. },
  1069. /**
  1070. * 滚动到底部
  1071. */
  1072. scrollToBottom() {
  1073. this.$nextTick(() => {
  1074. const lastIndex = this.messages.length - 1;
  1075. this.scrollToView = 'msg-' + lastIndex;
  1076. });
  1077. },
  1078. /**
  1079. * 判断是否显示时间分隔线
  1080. */
  1081. shouldShowTime(msg, index) {
  1082. if (index === 0) return true;
  1083. const prevMsg = this.messages[index - 1];
  1084. const timeDiff = new Date(msg.sendTime) - new Date(prevMsg.sendTime);
  1085. // 超过5分钟显示时间
  1086. return timeDiff > 5 * 60 * 1000;
  1087. },
  1088. /**
  1089. * 格式化消息时间(用于时间分隔线)
  1090. */
  1091. formatMessageTime(time) {
  1092. const date = new Date(time);
  1093. const now = new Date();
  1094. const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  1095. const yesterday = new Date(today - 86400000);
  1096. // 今天
  1097. if (date >= today) {
  1098. return date.toLocaleTimeString('zh-CN', {
  1099. hour: '2-digit',
  1100. minute: '2-digit'
  1101. });
  1102. }
  1103. // 昨天
  1104. if (date >= yesterday) {
  1105. return '昨天 ' + date.toLocaleTimeString('zh-CN', {
  1106. hour: '2-digit',
  1107. minute: '2-digit'
  1108. });
  1109. }
  1110. // 本周
  1111. if (date > new Date(now - 7 * 86400000)) {
  1112. const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  1113. return days[date.getDay()] + ' ' + date.toLocaleTimeString('zh-CN', {
  1114. hour: '2-digit',
  1115. minute: '2-digit'
  1116. });
  1117. }
  1118. // 更早
  1119. return date.toLocaleString('zh-CN', {
  1120. month: '2-digit',
  1121. day: '2-digit',
  1122. hour: '2-digit',
  1123. minute: '2-digit'
  1124. });
  1125. },
  1126. /**
  1127. * 格式化时间(消息状态用)
  1128. */
  1129. formatTime(time) {
  1130. const date = new Date(time);
  1131. const now = new Date();
  1132. const diff = now - date;
  1133. if (diff < 60000) {
  1134. return '刚刚';
  1135. } else if (diff < 3600000) {
  1136. return Math.floor(diff / 60000) + '分钟前';
  1137. } else if (diff < 86400000) {
  1138. return Math.floor(diff / 3600000) + '小时前';
  1139. } else {
  1140. return date.toLocaleString('zh-CN', {
  1141. month: '2-digit',
  1142. day: '2-digit',
  1143. hour: '2-digit',
  1144. minute: '2-digit'
  1145. });
  1146. }
  1147. },
  1148. /**
  1149. * 预览图片
  1150. */
  1151. previewImage(url) {
  1152. uni.previewImage({
  1153. urls: [url],
  1154. current: url
  1155. });
  1156. },
  1157. /**
  1158. * 返回
  1159. */
  1160. goBack() {
  1161. uni.navigateBack({
  1162. success: () => {
  1163. // 通知消息列表页面刷新
  1164. uni.$emit('refreshConversations');
  1165. }
  1166. });
  1167. },
  1168. /**
  1169. * 显示消息操作菜单
  1170. */
  1171. showMessageMenu(msg, index) {
  1172. this.selectedMessage = msg;
  1173. this.selectedMessageIndex = index;
  1174. this.showMessageAction = true;
  1175. // 计算菜单位置
  1176. uni.createSelectorQuery().select('.message-item').boundingClientRect(rect => {
  1177. if (rect) {
  1178. this.menuTop = rect.top + rect.height;
  1179. }
  1180. }).exec();
  1181. },
  1182. /**
  1183. * 隐藏消息操作菜单
  1184. */
  1185. hideMessageMenu() {
  1186. this.showMessageAction = false;
  1187. this.selectedMessage = null;
  1188. this.selectedMessageIndex = -1;
  1189. },
  1190. /**
  1191. * 复制消息
  1192. */
  1193. copyMessage() {
  1194. if (!this.selectedMessage || this.selectedMessage.messageType !== 1) {
  1195. return;
  1196. }
  1197. uni.setClipboardData({
  1198. data: this.selectedMessage.content,
  1199. success: () => {
  1200. uni.showToast({
  1201. title: '已复制',
  1202. icon: 'success'
  1203. });
  1204. }
  1205. });
  1206. this.hideMessageMenu();
  1207. },
  1208. /**
  1209. * 判断是否可以撤回
  1210. */
  1211. canRecall(msg) {
  1212. const diff = Date.now() - new Date(msg.sendTime).getTime();
  1213. return diff < 2 * 60 * 1000; // 2分钟内可撤回
  1214. },
  1215. /**
  1216. * 撤回消息
  1217. */
  1218. async recallMessage() {
  1219. if (!this.selectedMessage) {
  1220. return;
  1221. }
  1222. try {
  1223. // 查找TIM消息对象
  1224. const timMessage = await timManager.tim.findMessage(this.selectedMessage.messageId);
  1225. if (timMessage) {
  1226. await timManager.revokeMessage(timMessage);
  1227. // 更新本地消息状态
  1228. this.selectedMessage.isRecalled = true;
  1229. this.selectedMessage.content = '你撤回了一条消息';
  1230. uni.showToast({
  1231. title: '已撤回',
  1232. icon: 'success'
  1233. });
  1234. }
  1235. } catch (error) {
  1236. console.error('撤回失败:', error);
  1237. uni.showToast({
  1238. title: '撤回失败',
  1239. icon: 'none'
  1240. });
  1241. }
  1242. this.hideMessageMenu();
  1243. },
  1244. /**
  1245. * 删除消息
  1246. */
  1247. deleteMessage() {
  1248. if (!this.selectedMessage) {
  1249. return;
  1250. }
  1251. uni.showModal({
  1252. title: '确认删除',
  1253. content: '确定要删除这条消息吗?',
  1254. success: (res) => {
  1255. if (res.confirm) {
  1256. // 从列表中删除
  1257. this.messages.splice(this.selectedMessageIndex, 1);
  1258. uni.showToast({
  1259. title: '已删除',
  1260. icon: 'success'
  1261. });
  1262. }
  1263. }
  1264. });
  1265. this.hideMessageMenu();
  1266. },
  1267. /**
  1268. * 处理消息点击
  1269. */
  1270. handleMessageClick(msg) {
  1271. // 如果是发送失败的消息,提示重试
  1272. if (msg.sendStatus === 4) {
  1273. uni.showModal({
  1274. title: '发送失败',
  1275. content: '消息发送失败,是否重试?',
  1276. success: (res) => {
  1277. if (res.confirm) {
  1278. this.retryMessage(msg);
  1279. }
  1280. }
  1281. });
  1282. }
  1283. },
  1284. /**
  1285. * 重试发送消息
  1286. */
  1287. async retryMessage(msg) {
  1288. if (msg.messageType !== 1) {
  1289. uni.showToast({ title: '暂不支持重发该类型消息', icon: 'none' });
  1290. return;
  1291. }
  1292. const isBlocked = await this.checkIsBlockedByTarget();
  1293. if (isBlocked) {
  1294. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1295. if (index > -1) {
  1296. this.$set(this.messages[index], 'sendStatus', 4);
  1297. }
  1298. uni.showToast({ title: '对方已拉黑你,无法发送', icon: 'none' });
  1299. return;
  1300. }
  1301. try {
  1302. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1303. if (index > -1) {
  1304. this.$set(this.messages[index], 'sendStatus', 1); // 发送中
  1305. }
  1306. const message = await timManager.sendTextMessage(this.targetUserId, msg.content);
  1307. // 更新消息状态为已送达
  1308. if (index > -1) {
  1309. const convertedMsg = this.convertMessage(message);
  1310. convertedMsg.sendStatus = 2; // 强制已送达
  1311. convertedMsg.messageId = msg.messageId; // 保持原ID
  1312. this.$set(this.messages, index, convertedMsg);
  1313. }
  1314. console.log('✅ 消息重发成功');
  1315. this.syncMessageToMySQL(message);
  1316. } catch (error) {
  1317. console.error('❌ 消息重发失败:', error);
  1318. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1319. if (index > -1) {
  1320. this.$set(this.messages[index], 'sendStatus', 4);
  1321. }
  1322. uni.showToast({ title: '发送失败', icon: 'none' });
  1323. }
  1324. },
  1325. // 其他功能方法
  1326. switchInputType() {
  1327. this.inputType = this.inputType === 'text' ? 'voice' : 'text';
  1328. },
  1329. /**
  1330. * 初始化在线状态监听
  1331. */
  1332. async initPresence() {
  1333. console.log('🔌 初始化在线状态监听');
  1334. console.log(' - 当前用户ID:', this.userId);
  1335. console.log(' - 对方用户ID:', this.targetUserId);
  1336. // 1. 首先通过HTTP API查询对方的在线状态(立即显示)
  1337. try {
  1338. const isOnline = await presenceManager.queryOnlineStatus(this.targetUserId);
  1339. this.isTargetOnline = isOnline;
  1340. console.log(' - HTTP查询初始在线状态:', this.isTargetOnline);
  1341. } catch (error) {
  1342. console.error('❌ HTTP查询在线状态失败:', error);
  1343. this.isTargetOnline = false;
  1344. }
  1345. // 2. 连接WebSocket(如果未连接)
  1346. if (!presenceManager.getConnectionStatus()) {
  1347. presenceManager.connect(this.userId);
  1348. // 等待WebSocket连接建立
  1349. await this.waitForWebSocketConnection();
  1350. }
  1351. // 3. 监听对方用户的在线状态变化
  1352. this.handleStatusChange = (status) => {
  1353. console.log(`👤 对方用户 ${this.targetUserId} 状态变更: ${status}`);
  1354. this.isTargetOnline = (status === 'online');
  1355. console.log(' - 更新后的在线状态:', this.isTargetOnline);
  1356. };
  1357. presenceManager.onStatusChange(this.targetUserId, this.handleStatusChange);
  1358. console.log('✅ 已订阅对方用户状态');
  1359. // 4. 监听已读回执(通过WebSocket)
  1360. // 注册已读回执的回调
  1361. this.readReceiptCallback = (data) => {
  1362. if (data.type === 'READ_RECEIPT' && data.fromUserId == this.targetUserId) {
  1363. console.log('📬 收到已读回执:', data);
  1364. this.handleReadReceipt(data);
  1365. }
  1366. };
  1367. // 将回调添加到presenceManager的消息处理中
  1368. if (!presenceManager.messageCallbacks) {
  1369. presenceManager.messageCallbacks = [];
  1370. }
  1371. presenceManager.messageCallbacks.push(this.readReceiptCallback);
  1372. console.log('✅ 已监听已读回执');
  1373. // 4. 定期轮询在线状态(作为补充,每30秒查询一次)
  1374. this.onlineStatusPollingTimer = setInterval(async () => {
  1375. try {
  1376. const isOnline = await presenceManager.queryOnlineStatus(this.targetUserId);
  1377. if (this.isTargetOnline !== isOnline) {
  1378. console.log(`🔄 轮询检测到状态变化: ${this.isTargetOnline} -> ${isOnline}`);
  1379. this.isTargetOnline = isOnline;
  1380. }
  1381. } catch (error) {
  1382. console.error('❌ 轮询查询在线状态失败:', error);
  1383. }
  1384. }, 30000); // 30秒轮询一次
  1385. },
  1386. /**
  1387. * 等待WebSocket连接建立
  1388. */
  1389. async waitForWebSocketConnection() {
  1390. return new Promise((resolve) => {
  1391. const maxWaitTime = 5000; // 最多等待5秒
  1392. const startTime = Date.now();
  1393. const checkConnection = setInterval(() => {
  1394. if (presenceManager.getConnectionStatus()) {
  1395. console.log('✅ WebSocket已连接');
  1396. clearInterval(checkConnection);
  1397. resolve();
  1398. } else if (Date.now() - startTime > maxWaitTime) {
  1399. console.log('⚠️ WebSocket连接超时,继续使用HTTP轮询');
  1400. clearInterval(checkConnection);
  1401. resolve();
  1402. }
  1403. }, 100);
  1404. });
  1405. },
  1406. /**
  1407. * 清理在线状态监听
  1408. */
  1409. cleanupPresence() {
  1410. console.log('🔌 清理在线状态监听');
  1411. const presenceManager = require('@/utils/presence-manager.js').default;
  1412. // 清除轮询定时器
  1413. if (this.onlineStatusPollingTimer) {
  1414. clearInterval(this.onlineStatusPollingTimer);
  1415. this.onlineStatusPollingTimer = null;
  1416. }
  1417. // 移除在线状态监听
  1418. if (this.handleStatusChange) {
  1419. presenceManager.offStatusChange(this.targetUserId, this.handleStatusChange);
  1420. this.handleStatusChange = null;
  1421. }
  1422. // 移除已读回执回调
  1423. if (this.readReceiptCallback && presenceManager.messageCallbacks) {
  1424. const index = presenceManager.messageCallbacks.indexOf(this.readReceiptCallback);
  1425. if (index > -1) {
  1426. presenceManager.messageCallbacks.splice(index, 1);
  1427. console.log('✅ 已移除已读回执监听');
  1428. }
  1429. this.readReceiptCallback = null;
  1430. }
  1431. // 注意:不要断开WebSocket连接,因为其他页面可能还在使用
  1432. // presenceManager.disconnect();
  1433. },
  1434. /**
  1435. * 开始录音
  1436. */
  1437. startVoiceRecord(e) {
  1438. console.log('🎤 [按住说话] startVoiceRecord 方法被调用');
  1439. // 记录触摸起始位置
  1440. this.voiceTouchStartY = e.touches[0].clientY;
  1441. this.voiceCanceling = false;
  1442. // 检查消息发送限制
  1443. if (this.hasMessageLimit && this.remainingCount <= 0) {
  1444. uni.showToast({
  1445. title: '今日消息发送次数已用完',
  1446. icon: 'none'
  1447. });
  1448. return;
  1449. }
  1450. // 初始化录音管理器
  1451. if (!this.recorderManager) {
  1452. console.log('📱 初始化录音管理器');
  1453. this.recorderManager = uni.getRecorderManager();
  1454. // 录音开始
  1455. this.recorderManager.onStart(() => {
  1456. console.log('✅ 录音开始回调触发, voiceRecordCancelled:', this.voiceRecordCancelled);
  1457. // 关键修复:如果录音已被取消,不再恢复录音状态
  1458. if (this.voiceRecordCancelled) {
  1459. console.log('⚠️ 录音已被取消,忽略onStart回调');
  1460. // 立即停止录音
  1461. if (this.recorderManager) {
  1462. this.recorderManager.stop();
  1463. }
  1464. return;
  1465. }
  1466. this.isRecording = true;
  1467. this.showVoiceRecording = true;
  1468. this.voiceStartTime = Date.now();
  1469. console.log(' - isRecording:', this.isRecording);
  1470. console.log(' - showVoiceRecording:', this.showVoiceRecording);
  1471. });
  1472. // 录音结束
  1473. this.recorderManager.onStop((res) => {
  1474. console.log('🎤 录音结束:', res, ', voiceCanceling:', this.voiceCanceling);
  1475. this.isRecording = false;
  1476. this.showVoiceRecording = false;
  1477. // 如果是取消状态,不发送
  1478. if (this.voiceCanceling) {
  1479. console.log('❌ 录音已取消,不发送');
  1480. this.voiceCanceling = false;
  1481. return;
  1482. }
  1483. this.voiceTempPath = res.tempFilePath;
  1484. this.voiceDuration = Math.floor(res.duration / 1000); // 转换为秒
  1485. console.log(' - 文件路径:', this.voiceTempPath);
  1486. console.log(' - 时长:', this.voiceDuration, '秒');
  1487. // 时长验证
  1488. if (this.voiceDuration < 1) {
  1489. uni.showToast({
  1490. title: '录音时间太短',
  1491. icon: 'none'
  1492. });
  1493. return;
  1494. }
  1495. if (this.voiceDuration > 60) {
  1496. uni.showToast({
  1497. title: '录音时间不能超过60秒',
  1498. icon: 'none'
  1499. });
  1500. return;
  1501. }
  1502. // 发送语音消息
  1503. this.sendVoiceMessage();
  1504. });
  1505. // 录音错误
  1506. this.recorderManager.onError((err) => {
  1507. console.error('❌ 录音错误:', err);
  1508. this.isRecording = false;
  1509. this.showVoiceRecording = false;
  1510. uni.showToast({
  1511. title: '录音失败',
  1512. icon: 'none'
  1513. });
  1514. });
  1515. }
  1516. // 立即设置录音状态(不等待onStart回调)
  1517. this.isRecording = true;
  1518. this.showVoiceRecording = true;
  1519. this.voiceRecordCancelled = false; // 重置取消标志
  1520. this.voiceStartTime = Date.now();
  1521. this.voiceRecordingTime = 0;
  1522. this.voiceVolume = 0.3;
  1523. console.log('🎬 立即设置录音状态');
  1524. console.log(' - isRecording:', this.isRecording);
  1525. console.log(' - showVoiceRecording:', this.showVoiceRecording);
  1526. // 启动计时器
  1527. let volumeDirection = 1;
  1528. let currentVolume = 0.3;
  1529. this.voiceRecordingTimer = setInterval(() => {
  1530. this.voiceRecordingTime = Math.floor((Date.now() - this.voiceStartTime) / 1000);
  1531. // 模拟更真实的音量波动
  1532. // 随机决定是否有声音(80%概率有声音)
  1533. if (Math.random() > 0.2) {
  1534. // 有声音:平滑波动
  1535. currentVolume += volumeDirection * (0.1 + Math.random() * 0.2);
  1536. if (currentVolume > 1.0) {
  1537. currentVolume = 1.0;
  1538. volumeDirection = -1;
  1539. } else if (currentVolume < 0.4) {
  1540. currentVolume = 0.4;
  1541. volumeDirection = 1;
  1542. }
  1543. this.voiceVolume = currentVolume;
  1544. } else {
  1545. // 无声音:降低到最小
  1546. this.voiceVolume = Math.max(0.2, this.voiceVolume * 0.8);
  1547. }
  1548. }, 100);
  1549. // 开始录音
  1550. console.log('🎙️ 调用 recorderManager.start()');
  1551. try {
  1552. this.recorderManager.start({
  1553. format: 'mp3',
  1554. sampleRate: 16000,
  1555. numberOfChannels: 1,
  1556. encodeBitRate: 48000
  1557. });
  1558. console.log('✅ recorderManager.start() 调用成功');
  1559. } catch (err) {
  1560. console.error('❌ recorderManager.start() 调用失败:', err);
  1561. this.isRecording = false;
  1562. this.showVoiceRecording = false;
  1563. }
  1564. },
  1565. /**
  1566. * 停止录音
  1567. */
  1568. stopVoiceRecord() {
  1569. console.log('🎤 [松开] stopVoiceRecord 方法被调用, isRecording:', this.isRecording, ', voiceCanceling:', this.voiceCanceling);
  1570. // 清除计时器
  1571. if (this.voiceRecordingTimer) {
  1572. clearInterval(this.voiceRecordingTimer);
  1573. this.voiceRecordingTimer = null;
  1574. }
  1575. // 如果正在取消,则取消录音
  1576. if (this.voiceCanceling) {
  1577. console.log('🚫 检测到取消状态,调用 cancelVoiceRecord');
  1578. this.cancelVoiceRecord();
  1579. return;
  1580. }
  1581. if (this.isRecording && this.recorderManager) {
  1582. const duration = Date.now() - this.voiceStartTime;
  1583. // 录音时间太短
  1584. if (duration < 1000) {
  1585. this.recorderManager.stop();
  1586. this.isRecording = false;
  1587. this.showVoiceRecording = false;
  1588. uni.showToast({
  1589. title: '录音时间太短',
  1590. icon: 'none'
  1591. });
  1592. return;
  1593. }
  1594. this.recorderManager.stop();
  1595. }
  1596. },
  1597. /**
  1598. * 触摸移动 - 检测上滑取消
  1599. */
  1600. onVoiceTouchMove(e) {
  1601. if (!this.isRecording) return;
  1602. const currentY = e.touches[0].clientY;
  1603. const deltaY = this.voiceTouchStartY - currentY;
  1604. // 上滑超过100px,显示取消提示
  1605. if (deltaY > 100) {
  1606. this.voiceCanceling = true;
  1607. console.log('⬆️ 上滑取消录音');
  1608. } else {
  1609. this.voiceCanceling = false;
  1610. }
  1611. },
  1612. /**
  1613. * 取消录音
  1614. */
  1615. cancelVoiceRecord() {
  1616. console.log('❌ 取消录音, voiceCanceling:', this.voiceCanceling);
  1617. // 关键修复:标记录音已被取消,防止onStart回调恢复录音
  1618. this.voiceRecordCancelled = true;
  1619. // 清除计时器
  1620. if (this.voiceRecordingTimer) {
  1621. clearInterval(this.voiceRecordingTimer);
  1622. this.voiceRecordingTimer = null;
  1623. }
  1624. // 先设置取消状态,再停止录音
  1625. // 这样onStop回调中能正确判断
  1626. if (!this.voiceCanceling) {
  1627. this.voiceCanceling = true;
  1628. }
  1629. // 立即隐藏录音UI
  1630. this.isRecording = false;
  1631. this.showVoiceRecording = false;
  1632. if (this.recorderManager) {
  1633. // 尝试停止录音(如果已经开始)
  1634. try {
  1635. this.recorderManager.stop();
  1636. } catch (err) {
  1637. console.log('⚠️ 停止录音失败(可能还未开始):', err);
  1638. }
  1639. }
  1640. // 重置取消状态
  1641. this.voiceCanceling = false;
  1642. uni.showToast({
  1643. title: '已取消录音',
  1644. icon: 'none'
  1645. });
  1646. },
  1647. /**
  1648. * 发送语音消息
  1649. */
  1650. async sendVoiceMessage() {
  1651. // 检查是否被拉黑
  1652. const isBlocked = await this.checkIsBlockedByTarget();
  1653. if (isBlocked) {
  1654. uni.showToast({
  1655. title: '你已被对方拉黑,无法发送消息',
  1656. icon: 'none'
  1657. });
  1658. return;
  1659. }
  1660. try {
  1661. uni.showLoading({ title: '上传中...' });
  1662. // 第一步:上传语音文件到MinIO
  1663. const uploadResult = await this.uploadVoiceToMinIO();
  1664. if (!uploadResult.success) {
  1665. throw new Error(uploadResult.message || '上传失败');
  1666. }
  1667. console.log('✅ 语音文件上传成功:', uploadResult.fileUrl);
  1668. uni.showLoading({ title: '发送中...' });
  1669. // 第二步:通过腾讯IM发送语音消息(携带MinIO URL)
  1670. const message = await timManager.sendVoiceMessage(
  1671. this.targetUserId,
  1672. uploadResult.fileUrl,
  1673. this.voiceDuration,
  1674. uploadResult.fileSize
  1675. );
  1676. // 添加到消息列表
  1677. this.messages.push(this.convertMessage(message));
  1678. this.scrollToBottom();
  1679. uni.hideLoading();
  1680. console.log('✅ 语音消息发送成功');
  1681. // 同步到MySQL
  1682. this.syncMessageToMySQL(message);
  1683. // 更新消息计数
  1684. if (!this.isVip) {
  1685. await this.updateMessageCount();
  1686. }
  1687. } catch (error) {
  1688. uni.hideLoading();
  1689. console.error('❌ 语音消息发送失败:', error);
  1690. uni.showToast({
  1691. title: '发送失败: ' + error.message,
  1692. icon: 'none'
  1693. });
  1694. }
  1695. },
  1696. /**
  1697. * 上传语音文件到MinIO
  1698. */
  1699. async uploadVoiceToMinIO() {
  1700. try {
  1701. console.log('📤 开始上传语音文件到MinIO...');
  1702. console.log(' - 文件路径:', this.voiceTempPath);
  1703. console.log(' - 时长:', this.voiceDuration, '秒');
  1704. // 使用uni.uploadFile上传到后端MinIO接口
  1705. const [err, res] = await uni.uploadFile({
  1706. url: 'http://localhost:8083/api/voice/upload',
  1707. filePath: this.voiceTempPath,
  1708. name: 'file',
  1709. header: {
  1710. 'Content-Type': 'multipart/form-data'
  1711. }
  1712. });
  1713. if (err) {
  1714. console.error('❌ 上传请求失败:', err);
  1715. return {
  1716. success: false,
  1717. message: '网络请求失败'
  1718. };
  1719. }
  1720. // 解析响应
  1721. const result = JSON.parse(res.data);
  1722. console.log('📥 MinIO上传响应:', result);
  1723. if (result.success) {
  1724. return {
  1725. success: true,
  1726. fileUrl: result.fileUrl,
  1727. fileSize: result.fileSize
  1728. };
  1729. } else {
  1730. return {
  1731. success: false,
  1732. message: result.message || '上传失败'
  1733. };
  1734. }
  1735. } catch (error) {
  1736. console.error('❌ 上传语音文件失败:', error);
  1737. return {
  1738. success: false,
  1739. message: error.message || '上传异常'
  1740. };
  1741. }
  1742. },
  1743. insertEmoji(emoji) {
  1744. this.inputText += emoji;
  1745. this.showEmojiPanel = false;
  1746. },
  1747. chooseVideo() {
  1748. uni.showToast({
  1749. title: '视频功能开发中',
  1750. icon: 'none'
  1751. });
  1752. },
  1753. chooseFile() {
  1754. uni.showToast({
  1755. title: '文件功能开发中',
  1756. icon: 'none'
  1757. });
  1758. },
  1759. /**
  1760. * 切换语音播放/暂停
  1761. */
  1762. toggleVoicePlay(msg) {
  1763. // 如果正在播放这条语音,则暂停
  1764. if (this.playingVoiceId === msg.messageId) {
  1765. this.pauseVoice(msg);
  1766. } else {
  1767. // 否则开始播放
  1768. this.playVoice(msg);
  1769. }
  1770. },
  1771. /**
  1772. * 播放语音
  1773. */
  1774. playVoice(msg) {
  1775. console.log('📢 [播放语音] 开始 - messageId:', msg.messageId);
  1776. if (!msg.mediaUrl) {
  1777. // 如果是TIM消息,从payload中获取URL
  1778. const audioUrl = msg.payload?.url || msg.payload?.remoteAudioUrl;
  1779. if (!audioUrl) {
  1780. uni.showToast({
  1781. title: '语音文件不存在',
  1782. icon: 'none'
  1783. });
  1784. return;
  1785. }
  1786. msg.mediaUrl = audioUrl;
  1787. }
  1788. // 如果有其他语音正在播放,先停止
  1789. if (this.currentAudioContext) {
  1790. console.log('⏹️ 停止之前的语音');
  1791. this.currentAudioContext.stop();
  1792. this.currentAudioContext.destroy();
  1793. this.currentAudioContext = null;
  1794. }
  1795. // 清除暂停状态
  1796. this.pausedVoiceId = null;
  1797. // 设置当前播放的语音ID,触发动画
  1798. this.playingVoiceId = msg.messageId;
  1799. console.log('🎬 [动画开始] playingVoiceId =', this.playingVoiceId);
  1800. // 创建音频上下文
  1801. const innerAudioContext = uni.createInnerAudioContext();
  1802. innerAudioContext.src = msg.mediaUrl;
  1803. innerAudioContext.loop = false; // 不循环播放
  1804. this.currentAudioContext = innerAudioContext;
  1805. innerAudioContext.onPlay(() => {
  1806. console.log('🔊 开始播放语音');
  1807. });
  1808. innerAudioContext.onEnded(() => {
  1809. console.log('✅ 语音播放完成');
  1810. this.playingVoiceId = null; // 停止动画
  1811. this.pausedVoiceId = null;
  1812. this.currentAudioContext = null;
  1813. console.log('🛑 [动画停止] playingVoiceId =', this.playingVoiceId);
  1814. innerAudioContext.destroy();
  1815. });
  1816. innerAudioContext.onError((err) => {
  1817. console.error('❌ 语音播放失败:', err);
  1818. this.playingVoiceId = null; // 停止动画
  1819. this.pausedVoiceId = null;
  1820. this.currentAudioContext = null;
  1821. console.log('🛑 [动画停止-错误] playingVoiceId =', this.playingVoiceId);
  1822. uni.showToast({
  1823. title: '播放失败',
  1824. icon: 'none'
  1825. });
  1826. innerAudioContext.destroy();
  1827. });
  1828. innerAudioContext.play();
  1829. },
  1830. /**
  1831. * 暂停语音
  1832. */
  1833. pauseVoice(msg) {
  1834. if (this.currentAudioContext) {
  1835. this.currentAudioContext.pause();
  1836. this.playingVoiceId = null; // 停止动画
  1837. this.pausedVoiceId = msg.messageId; // 设置暂停状态
  1838. console.log('⏸️ [暂停] playingVoiceId =', this.playingVoiceId, ', pausedVoiceId =', this.pausedVoiceId);
  1839. }
  1840. },
  1841. /**
  1842. * 继续播放语音
  1843. */
  1844. resumeVoice() {
  1845. if (this.currentAudioContext && this.pausedVoiceId) {
  1846. this.currentAudioContext.play();
  1847. this.playingVoiceId = this.pausedVoiceId; // 恢复动画
  1848. const resumedId = this.pausedVoiceId;
  1849. this.pausedVoiceId = null; // 清除暂停状态
  1850. console.log('▶️ [继续播放] playingVoiceId =', this.playingVoiceId, ', pausedVoiceId =', this.pausedVoiceId);
  1851. }
  1852. },
  1853. showMoreOptions() {
  1854. this.showMoreOptionsModal = true;
  1855. },
  1856. closeMoreOptions() {
  1857. this.showMoreOptionsModal = false;
  1858. },
  1859. /**
  1860. * 查看用户资料(跳转到原有more页面)
  1861. */
  1862. goToUserProfile() {
  1863. this.closeMoreOptions();
  1864. uni.navigateTo({
  1865. url: `/pages/message/more?userid=${this.targetUserId}`,
  1866. fail: (err) => {
  1867. console.error('跳转失败:', err);
  1868. uni.showToast({
  1869. title: '页面不存在',
  1870. icon: 'none'
  1871. });
  1872. }
  1873. });
  1874. },
  1875. /**
  1876. * 显示拉黑确认弹窗
  1877. */
  1878. blockFriend() {
  1879. this.closeMoreOptions();
  1880. this.showBlockConfirmModal = true;
  1881. },
  1882. /**
  1883. * 关闭拉黑确认弹窗
  1884. */
  1885. closeBlockConfirm() {
  1886. this.showBlockConfirmModal = false;
  1887. },
  1888. /**
  1889. * 从后端获取VIP状态和今日剩余发送次数
  1890. */
  1891. async getUserMessageLimit() {
  1892. try {
  1893. const [err, res] = await uni.request({
  1894. url: 'http://localhost:8083/api/chat/getUserMessageLimit',
  1895. method: 'GET',
  1896. data: {
  1897. userId: this.userId ,// 已在onLoad中初始化的当前用户ID
  1898. targetUserId: this.targetUserId
  1899. },
  1900. header: {
  1901. 'Content-Type': 'application/json'
  1902. }
  1903. });
  1904. if (err) throw new Error('网络请求失败');
  1905. if (res.data.code !== 200) throw new Error(res.data.message || '获取限制信息失败');
  1906. const { isVip, remainingCount, hasMessageLimit } = res.data.data;
  1907. this.isVip = isVip;
  1908. this.remainingCount = remainingCount;
  1909. this.hasMessageLimit = hasMessageLimit;
  1910. console.log('✅ 用户消息限制信息:', { isVip, remainingCount, hasMessageLimit });
  1911. } catch (error) {
  1912. console.error('❌ 获取消息限制失败:', error);
  1913. // 异常降级:默认非VIP,剩余5次
  1914. this.isVip = false;
  1915. this.remainingCount = 5;
  1916. this.hasMessageLimit = true;
  1917. }
  1918. },
  1919. /**
  1920. * 发送成功后,更新后端计数并同步前端剩余次数
  1921. */
  1922. async updateMessageCount() {
  1923. try {
  1924. const [err, res] = await uni.request({
  1925. url: 'http://localhost:8083/api/chat/updateMessageCount',
  1926. method: 'get',
  1927. data: {
  1928. userId: this.userId ,// 已在onLoad中初始化的当前用户ID
  1929. targetUserId: this.targetUserId
  1930. },
  1931. header: {
  1932. 'Content-Type': 'application/json'
  1933. }
  1934. });
  1935. if (err) throw new Error('更新计数失败');
  1936. if (res.data.code === 200) {
  1937. this.remainingCount = res.data.data.remainingCount; // 同步后端返回的剩余次数
  1938. }
  1939. } catch (error) {
  1940. console.error('❌ 更新发送次数失败:', error);
  1941. // 前端本地降级:避免影响用户体验,本地暂减1(刷新页面后同步真实数据)
  1942. if (this.remainingCount > 0) {
  1943. this.remainingCount--;
  1944. }
  1945. }
  1946. },
  1947. /**
  1948. * 确认拉黑好友
  1949. */
  1950. async confirmBlockFriend() {
  1951. try {
  1952. uni.showLoading({
  1953. title: '处理中...'
  1954. });
  1955. // 调用后端拉黑接口(根据实际接口调整)
  1956. const [err, res] = await uni.request({
  1957. url: 'http://localhost:8083/api/chatfriend/block',
  1958. method: 'POST',
  1959. data: {
  1960. userId: this.userId,
  1961. targetUserId: this.targetUserId,
  1962. targetUserName: this.targetUserName,
  1963. targetUserAvatar: this.targetUserAvatar
  1964. },
  1965. header: {
  1966. 'Content-Type': 'application/json',
  1967. // 'Authorization': 'Bearer ' + uni.getStorageSync('token')
  1968. }
  1969. });
  1970. uni.hideLoading();
  1971. if (err) throw new Error('网络请求失败');
  1972. if (res.data && res.data.code === 200) {
  1973. uni.showToast({ title: '拉黑成功', icon: 'success' });
  1974. this.closeBlockConfirm();
  1975. // 触发拉黑列表更新事件,通知消息页面实时刷新
  1976. uni.$emit('blacklistUpdated');
  1977. // 拉黑成功后立即返回消息列表页面(优化体验)
  1978. setTimeout(() => {
  1979. uni.navigateBack({
  1980. delta: 1,
  1981. success: () => {
  1982. // 返回成功后再次触发一次刷新,确保万无一失
  1983. uni.$emit('blacklistUpdated');
  1984. }
  1985. });
  1986. }, 1500);
  1987. } else {
  1988. throw new Error(res.data?.message || '拉黑失败');
  1989. }
  1990. } catch (error) {
  1991. console.error('拉黑失败:', error);
  1992. uni.showToast({ title: error.message || '拉黑失败', icon: 'none' });
  1993. }
  1994. },
  1995. }
  1996. };
  1997. </script>
  1998. <style scoped>
  1999. /* 弹窗遮罩 */
  2000. .modal-mask {
  2001. position: fixed;
  2002. top: 0;
  2003. left: 0;
  2004. right: 0;
  2005. bottom: 0;
  2006. background-color: rgba(0, 0, 0, 0.5);
  2007. z-index: 10000;
  2008. display: flex;
  2009. align-items: center;
  2010. justify-content: center;
  2011. }
  2012. /* 更多选项弹窗内容 */
  2013. .modal-content {
  2014. width: 70%;
  2015. background-color: #fff;
  2016. border-radius: 20rpx;
  2017. overflow: hidden;
  2018. }
  2019. .modal-header {
  2020. padding: 30rpx;
  2021. text-align: center;
  2022. border-bottom: 1px solid #eee;
  2023. }
  2024. .modal-title {
  2025. font-size: 32rpx;
  2026. font-weight: bold;
  2027. display: block;
  2028. }
  2029. .modal-subtitle {
  2030. font-size: 24rpx;
  2031. color: #999;
  2032. display: block;
  2033. margin-top: 10rpx;
  2034. }
  2035. .modal-body {
  2036. padding: 20rpx 0;
  2037. }
  2038. .modal-item {
  2039. display: flex;
  2040. align-items: center;
  2041. padding: 25rpx 40rpx;
  2042. font-size: 30rpx;
  2043. }
  2044. .modal-item.danger {
  2045. color: #fa5151;
  2046. }
  2047. .item-icon {
  2048. font-size: 32rpx;
  2049. margin-right: 20rpx;
  2050. }
  2051. .modal-footer {
  2052. padding: 20rpx;
  2053. border-top: 1px solid #eee;
  2054. }
  2055. .modal-close-btn {
  2056. width: 94%;
  2057. background-color: #f5f5f5;
  2058. border: none;
  2059. border-radius: 10rpx;
  2060. padding: 20rpx;
  2061. font-size: 30rpx;
  2062. }
  2063. /* 确认弹窗样式 */
  2064. .confirm-modal {
  2065. width: 60%;
  2066. background-color: #fff;
  2067. border-radius: 20rpx;
  2068. padding: 40rpx;
  2069. text-align: center;
  2070. }
  2071. .confirm-title {
  2072. font-size: 32rpx;
  2073. font-weight: bold;
  2074. margin-bottom: 30rpx;
  2075. }
  2076. .confirm-content {
  2077. font-size: 28rpx;
  2078. color: #666;
  2079. margin-bottom: 40rpx;
  2080. line-height: 1.5;
  2081. }
  2082. .confirm-buttons {
  2083. display: flex;
  2084. justify-content: space-between;
  2085. }
  2086. .confirm-btn {
  2087. flex: 1;
  2088. margin: 0 10rpx;
  2089. padding: 20rpx;
  2090. border-radius: 10rpx;
  2091. border: none;
  2092. font-size: 28rpx;
  2093. }
  2094. .confirm-btn.cancel {
  2095. background-color: #f5f5f5;
  2096. }
  2097. .confirm-btn.confirm {
  2098. background-color: #fa5151;
  2099. color: #fff;
  2100. }
  2101. .chat-page {
  2102. display: flex;
  2103. flex-direction: column;
  2104. height: 100vh;
  2105. background-color: #f5f5f5;
  2106. }
  2107. /* 顶部导航 */
  2108. .chat-header {
  2109. display: flex;
  2110. align-items: center;
  2111. justify-content: space-between;
  2112. padding: 20rpx 30rpx;
  2113. background-color: #fff;
  2114. border-bottom: 1px solid #e5e5e5;
  2115. }
  2116. .header-left, .header-right {
  2117. width: 80rpx;
  2118. }
  2119. .icon-back, .icon-more {
  2120. font-size: 40rpx;
  2121. }
  2122. .header-center {
  2123. flex: 1;
  2124. text-align: center;
  2125. }
  2126. .chat-title {
  2127. display: block;
  2128. font-size: 36rpx;
  2129. font-weight: bold;
  2130. }
  2131. .online-status {
  2132. display: block;
  2133. font-size: 24rpx;
  2134. color: #999;
  2135. margin-top: 5rpx;
  2136. }
  2137. .online-status.online {
  2138. color: #07c160;
  2139. }
  2140. /* 消息列表 */
  2141. .message-list {
  2142. flex: 1;
  2143. padding: 20rpx;
  2144. overflow-y: scroll;
  2145. }
  2146. .loading-tip {
  2147. text-align: center;
  2148. padding: 20rpx;
  2149. color: #999;
  2150. font-size: 28rpx;
  2151. }
  2152. .message-item {
  2153. display: flex;
  2154. margin-bottom: 30rpx;
  2155. }
  2156. .message-item.message-self {
  2157. flex-direction: row-reverse;
  2158. }
  2159. .avatar {
  2160. width: 80rpx;
  2161. height: 80rpx;
  2162. border-radius: 8rpx;
  2163. margin: 0 20rpx;
  2164. }
  2165. .message-content-wrapper {
  2166. max-width: 70%;
  2167. display: inline-block;
  2168. }
  2169. .message-item.message-self .message-content-wrapper {
  2170. text-align: right; /* 关键:让气泡和状态提示整体右对齐 */
  2171. }
  2172. .message-name {
  2173. display: block;
  2174. font-size: 24rpx;
  2175. color: #999;
  2176. margin-bottom: 10rpx;
  2177. }
  2178. .message-bubble {
  2179. padding: 20rpx;
  2180. border-radius: 8rpx;
  2181. background-color: #fff;
  2182. word-wrap: break-word;
  2183. display: inline-block; /* 关键:气泡宽度由内容决定 */
  2184. max-width: 100%; /* 防止内容过长超出容器 */
  2185. position: relative;
  2186. }
  2187. .message-self .message-bubble {
  2188. background-color: #95ec69;
  2189. border-top-right-radius: 4rpx;
  2190. }
  2191. .message-bubble.bubble-self {
  2192. background-color: #95ec69;
  2193. }
  2194. .message-text {
  2195. font-size: 30rpx;
  2196. line-height: 1.5;
  2197. }
  2198. .message-image {
  2199. max-width: 400rpx;
  2200. border-radius: 8rpx;
  2201. }
  2202. .message-voice {
  2203. display: flex;
  2204. align-items: center;
  2205. gap: 12rpx;
  2206. padding: 0rpx 0;
  2207. min-width: 30rpx;
  2208. max-width: 400rpx;
  2209. cursor: pointer;
  2210. -webkit-tap-highlight-color: transparent;
  2211. outline: none;
  2212. border: none;
  2213. position: relative;
  2214. }
  2215. .voice-duration {
  2216. font-size: 27rpx;
  2217. color: #333;
  2218. flex-shrink: 0;
  2219. line-height: 1;
  2220. }
  2221. .voice-icon-wrapper {
  2222. display: flex;
  2223. flex-shrink: 0;
  2224. line-height: 0;
  2225. position: relative;
  2226. top: 1rpx;
  2227. }
  2228. .voice-icon {
  2229. width: 22rpx;
  2230. height: 22rpx;
  2231. display: block;
  2232. transform: none;
  2233. animation: none;
  2234. }
  2235. .voice-icon-wrapper.playing .voice-icon {
  2236. animation: voice-bounce 0.6s ease-in-out infinite;
  2237. }
  2238. .voice-resume-btn {
  2239. position: absolute;
  2240. top: 50%;
  2241. transform: translateY(-50%);
  2242. width: 32rpx;
  2243. height: 32rpx;
  2244. background: #07c160;
  2245. border-radius: 50%;
  2246. display: flex;
  2247. align-items: center;
  2248. justify-content: center;
  2249. box-shadow: 0 2rpx 8rpx rgba(7, 193, 96, 0.3);
  2250. }
  2251. .voice-resume-btn.resume-btn-left {
  2252. left: -40rpx;
  2253. }
  2254. .voice-resume-btn.resume-btn-right {
  2255. right: -40rpx;
  2256. }
  2257. .resume-icon {
  2258. color: #fff;
  2259. font-size: 16rpx;
  2260. margin-left: 2rpx;
  2261. }
  2262. @keyframes voice-bounce {
  2263. 0%, 100% {
  2264. transform: scale(1);
  2265. }
  2266. 50% {
  2267. transform: scale(1.2);
  2268. }
  2269. }
  2270. .message-video {
  2271. width: 400rpx;
  2272. height: 300rpx;
  2273. }
  2274. .message-recalled {
  2275. color: #999;
  2276. font-size: 28rpx;
  2277. }
  2278. .message-status {
  2279. text-align: right;
  2280. font-size: 24rpx;
  2281. color: #999;
  2282. margin-top: 5rpx;
  2283. }
  2284. .message-status .read {
  2285. color: #07c160;
  2286. }
  2287. .message-status .failed {
  2288. color: #fa5151;
  2289. }
  2290. .message-time {
  2291. display: block;
  2292. text-align: right;
  2293. font-size: 22rpx;
  2294. color: #ccc;
  2295. margin-top: 5rpx;
  2296. }
  2297. /* 输入框 */
  2298. .input-bar {
  2299. display: flex;
  2300. align-items: center;
  2301. padding: 20rpx;
  2302. background-color: #fff;
  2303. border-top: 1px solid #e5e5e5;
  2304. }
  2305. .input-icon {
  2306. width: 80rpx;
  2307. height: 80rpx;
  2308. display: flex;
  2309. align-items: center;
  2310. justify-content: center;
  2311. font-size: 50rpx;
  2312. }
  2313. .send-button {
  2314. padding: 0 30rpx;
  2315. height: 70rpx;
  2316. line-height: 70rpx;
  2317. background-color: #07c160;
  2318. color: #fff;
  2319. border-radius: 8rpx;
  2320. text-align: center;
  2321. font-size: 28rpx;
  2322. margin-left: 10rpx;
  2323. transition: opacity 0.3s;
  2324. }
  2325. .send-button.disabled {
  2326. opacity: 0.5;
  2327. background-color: #95ec69;
  2328. }
  2329. .input-field {
  2330. flex: 1;
  2331. height: 70rpx;
  2332. padding: 0 20rpx;
  2333. background-color: #f5f5f5;
  2334. border-radius: 8rpx;
  2335. font-size: 30rpx;
  2336. }
  2337. .voice-button {
  2338. flex: 1;
  2339. height: 70rpx;
  2340. line-height: 70rpx;
  2341. background-color: #f5f5f5;
  2342. border-radius: 8rpx;
  2343. text-align: center;
  2344. font-size: 30rpx;
  2345. border: none;
  2346. }
  2347. /* 表情面板 */
  2348. .emoji-panel {
  2349. display: flex;
  2350. flex-wrap: wrap;
  2351. padding: 20rpx;
  2352. background-color: #fff;
  2353. border-top: 1px solid #e5e5e5;
  2354. }
  2355. .emoji-item {
  2356. width: 80rpx;
  2357. height: 80rpx;
  2358. display: flex;
  2359. align-items: center;
  2360. justify-content: center;
  2361. font-size: 60rpx;
  2362. }
  2363. /* 更多功能面板 */
  2364. .more-panel {
  2365. display: flex;
  2366. padding: 40rpx;
  2367. background-color: #fff;
  2368. border-top: 1px solid #e5e5e5;
  2369. }
  2370. .more-item {
  2371. display: flex;
  2372. flex-direction: column;
  2373. align-items: center;
  2374. margin: 0 40rpx;
  2375. }
  2376. .more-icon {
  2377. width: 100rpx;
  2378. height: 100rpx;
  2379. display: flex;
  2380. align-items: center;
  2381. justify-content: center;
  2382. font-size: 60rpx;
  2383. background-color: #f5f5f5;
  2384. border-radius: 16rpx;
  2385. margin-bottom: 10rpx;
  2386. }
  2387. .more-text {
  2388. font-size: 24rpx;
  2389. color: #666;
  2390. }
  2391. /* 时间分隔线 */
  2392. .time-divider {
  2393. text-align: center;
  2394. padding: 20rpx 0;
  2395. }
  2396. .time-text {
  2397. display: inline-block;
  2398. padding: 8rpx 20rpx;
  2399. background-color: rgba(0, 0, 0, 0.1);
  2400. border-radius: 8rpx;
  2401. font-size: 22rpx;
  2402. color: #999;
  2403. }
  2404. /* 消息气泡失败状态 */
  2405. .bubble-failed {
  2406. background-color: #95ec69;
  2407. opacity: 0.6;
  2408. border: 2rpx solid #fa5151;
  2409. }
  2410. /* 消息状态优化 */
  2411. .message-status .sending {
  2412. color: #576b95;
  2413. }
  2414. .message-status .failed-group {
  2415. display: flex;
  2416. align-items: center;
  2417. gap: 10rpx;
  2418. }
  2419. .message-status .retry-btn {
  2420. color: #576b95;
  2421. text-decoration: underline;
  2422. cursor: pointer;
  2423. }
  2424. /* 消息操作菜单遮罩 */
  2425. .message-action-mask {
  2426. position: fixed;
  2427. top: 0;
  2428. left: 0;
  2429. right: 0;
  2430. bottom: 0;
  2431. background-color: rgba(0, 0, 0, 0.4);
  2432. z-index: 9999;
  2433. display: flex;
  2434. align-items: center;
  2435. justify-content: center;
  2436. }
  2437. /* 消息操作菜单 */
  2438. .message-action-menu {
  2439. width: 600rpx;
  2440. background-color: #fff;
  2441. border-radius: 20rpx;
  2442. overflow: hidden;
  2443. }
  2444. .message-action-menu .menu-item {
  2445. display: flex;
  2446. align-items: center;
  2447. justify-content: center;
  2448. gap: 15rpx;
  2449. padding: 30rpx;
  2450. font-size: 32rpx;
  2451. color: #333;
  2452. border-bottom: 1rpx solid #f0f0f0;
  2453. transition: background-color 0.2s;
  2454. }
  2455. .message-action-menu .menu-item:active {
  2456. background-color: #f5f5f5;
  2457. }
  2458. .message-action-menu .menu-item.cancel {
  2459. color: #999;
  2460. border-bottom: none;
  2461. margin-top: 20rpx;
  2462. border-top: 10rpx solid #f5f5f5;
  2463. }
  2464. .message-action-menu .menu-icon {
  2465. font-size: 36rpx;
  2466. }
  2467. /* 消息发送限制提示 */
  2468. .message-limit-tip {
  2469. padding: 10rpx 20rpx;
  2470. font-size: 24rpx;
  2471. text-align: center;
  2472. background-color: #fff;
  2473. border-bottom: 1px solid #f5f5f5;
  2474. }
  2475. .vip-tip {
  2476. color: #ff9500; /* VIP橙色提示 */
  2477. }
  2478. .limit-tip {
  2479. color: #666; /* 普通灰色提示 */
  2480. }
  2481. .vip-link {
  2482. color: #2c9fff; /* 蓝色文字 */
  2483. text-decoration: underline; /* 下划线 */
  2484. cursor: pointer; /* 鼠标悬浮时显示手型 */
  2485. margin-left: 5rpx;
  2486. }
  2487. /* 点击时添加轻微反馈 */
  2488. .vip-link:active {
  2489. opacity: 0.7; /* 点击时透明度降低 */
  2490. }
  2491. /* 录音中提示遮罩 */
  2492. .voice-recording-mask {
  2493. position: fixed;
  2494. top: 0;
  2495. left: 0;
  2496. right: 0;
  2497. bottom: 0;
  2498. background-color: rgba(0, 0, 0, 0.6);
  2499. z-index: 10000;
  2500. display: flex;
  2501. align-items: center;
  2502. justify-content: center;
  2503. }
  2504. /* 录音提示框 */
  2505. .voice-recording-box {
  2506. width: 300rpx;
  2507. height: 300rpx;
  2508. background-color: rgba(0, 0, 0, 0.8);
  2509. border-radius: 20rpx;
  2510. display: flex;
  2511. flex-direction: column;
  2512. align-items: center;
  2513. justify-content: center;
  2514. color: #fff;
  2515. transition: background-color 0.3s;
  2516. }
  2517. .voice-recording-box.canceling {
  2518. background-color: rgba(220, 38, 38, 0.9);
  2519. }
  2520. .voice-wave-container {
  2521. display: flex;
  2522. align-items: center;
  2523. justify-content: center;
  2524. gap: 8rpx;
  2525. height: 100rpx;
  2526. margin-bottom: 20rpx;
  2527. }
  2528. .voice-wave-bar {
  2529. width: 6rpx;
  2530. background: #fff;
  2531. border-radius: 3rpx;
  2532. transition: transform 0.1s ease-out;
  2533. transform-origin: center;
  2534. }
  2535. .voice-wave-bar.bar1 {
  2536. height: 30rpx;
  2537. }
  2538. .voice-wave-bar.bar2 {
  2539. height: 45rpx;
  2540. }
  2541. .voice-wave-bar.bar3 {
  2542. height: 60rpx;
  2543. }
  2544. .voice-wave-bar.bar4 {
  2545. height: 50rpx;
  2546. }
  2547. .voice-wave-bar.bar5 {
  2548. height: 35rpx;
  2549. }
  2550. .voice-text {
  2551. font-size: 32rpx;
  2552. margin-bottom: 10rpx;
  2553. }
  2554. .voice-time {
  2555. font-size: 48rpx;
  2556. font-weight: bold;
  2557. color: #07c160;
  2558. margin: 10rpx 0;
  2559. }
  2560. .voice-tip {
  2561. font-size: 24rpx;
  2562. color: #ccc;
  2563. }
  2564. </style>