chat.vue 78 KB

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