chat.vue 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921
  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:1004/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:1004/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:1004/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', // 已读回执类型
  685. fromUserId: parseInt(this.userId),
  686. toUserId: parseInt(this.targetUserId),
  687. timestamp: Date.now()
  688. };
  689. // 发送WebSocket消息
  690. if (timManager.websocket && timManager.websocket.readyState === 1) {
  691. timManager.websocket.send(JSON.stringify(message));
  692. console.log('✅ 已读回执发送成功');
  693. } else {
  694. console.warn('⚠️ WebSocket未连接,无法发送已读回执');
  695. }
  696. } catch (error) {
  697. console.error('❌ 发送已读回执失败:', error);
  698. }
  699. },
  700. /**
  701. * 监听已读回执
  702. */
  703. listenReadReceipt() {
  704. // 在WebSocket消息处理中添加已读回执的监听
  705. // 这个方法会在initPresence中被调用
  706. console.log('👂 开始监听已读回执');
  707. },
  708. /**
  709. * 处理已读回执
  710. */
  711. handleReadReceipt(data) {
  712. try {
  713. console.log('📬 收到已读回执:', data);
  714. // 更新本地消息状态为已读
  715. this.messages.forEach((msg, index) => {
  716. // 只更新自己发送给对方的消息
  717. if (msg.fromUserId === this.userId &&
  718. msg.toUserId === this.targetUserId &&
  719. msg.sendStatus === 2) { // 只更新已送达的消息
  720. this.$set(this.messages[index], 'sendStatus', 3); // 更新为已读
  721. console.log(`✅ 消息 ${msg.messageId} 状态更新为已读`);
  722. }
  723. });
  724. } catch (error) {
  725. console.error('❌ 处理已读回执失败:', error);
  726. }
  727. },
  728. /**
  729. * 转换消息格式
  730. */
  731. convertMessage(timMsg) {
  732. let sendStatus = 1; // 默认发送中
  733. // 完善的状态判断逻辑
  734. if (timMsg.status === TIM.TYPES.MSG_STATUS_SEND_SUCC ||
  735. timMsg.status === 'success' ||
  736. timMsg.status === TIM.TYPES.MSG_STATUS_RECEIVED) {
  737. sendStatus = 2; // 已送达
  738. } else if (timMsg.status === TIM.TYPES.MSG_STATUS_SEND_FAIL ||
  739. timMsg.status === 'fail') {
  740. sendStatus = 4; // 发送失败
  741. } else if (timMsg.status === TIM.TYPES.MSG_STATUS_HAS_READ ||
  742. timMsg.status === 'read') {
  743. sendStatus = 3; // 已读
  744. } else if (timMsg.status === TIM.TYPES.MSG_STATUS_SENDING) {
  745. sendStatus = 1; // 发送中
  746. }
  747. // 处理不同类型消息的URL和时长
  748. let mediaUrl = '';
  749. let duration = 0;
  750. let messageType = 1;
  751. let content = '';
  752. if (timMsg.type === TIM.TYPES.MSG_TEXT) {
  753. messageType = 1;
  754. content = timMsg.payload.text;
  755. } else if (timMsg.type === TIM.TYPES.MSG_IMAGE && timMsg.payload.imageInfoArray) {
  756. messageType = 2;
  757. content = '[图片]';
  758. mediaUrl = timMsg.payload.imageInfoArray[0]?.url || '';
  759. } else if (timMsg.type === TIM.TYPES.MSG_SOUND) {
  760. // 原生语音消息
  761. messageType = 3;
  762. content = '[语音]';
  763. mediaUrl = timMsg.payload.url || timMsg.payload.remoteAudioUrl || '';
  764. duration = timMsg.payload.second || 0;
  765. } else if (timMsg.type === TIM.TYPES.MSG_CUSTOM) {
  766. // 自定义消息(我们的语音消息)
  767. try {
  768. const customData = JSON.parse(timMsg.payload.data);
  769. if (customData.type === 'voice') {
  770. messageType = 3;
  771. content = '[语音]';
  772. mediaUrl = customData.url;
  773. // duration已经是秒数,直接使用
  774. duration = parseInt(customData.duration) || 0;
  775. }
  776. } catch (e) {
  777. console.error('解析自定义消息失败:', e);
  778. }
  779. } else if (timMsg.type === TIM.TYPES.MSG_VIDEO) {
  780. messageType = 4;
  781. content = '[视频]';
  782. }
  783. return {
  784. messageId: timMsg.ID,
  785. fromUserId: timMsg.from,
  786. toUserId: timMsg.to,
  787. messageType: messageType,
  788. content: content || '[消息]',
  789. mediaUrl: mediaUrl,
  790. duration: duration,
  791. payload: timMsg.payload, // 保留原始payload
  792. sendStatus: sendStatus,
  793. sendTime: new Date(timMsg.time * 1000),
  794. isRecalled: timMsg.isRevoked,
  795. fromUserName: timMsg.from === this.userId ? '我' : this.targetUserName
  796. };
  797. },
  798. /**
  799. * 检查对方是否拉黑自己
  800. */
  801. async checkIsBlockedByTarget() {
  802. try {
  803. const [err, res] = await uni.request({
  804. url: 'http://localhost:8083/api/chatfriend/checkBlock',
  805. method: 'POST',
  806. data: {
  807. userId: this.userId, // 自己的ID
  808. targetUserId: this.targetUserId // 对方的ID
  809. },
  810. header: {
  811. 'Content-Type': 'application/json'
  812. }
  813. });
  814. console.log('拉黑检查接口响应:', res.data); // 方便调试
  815. if (err) {
  816. console.error('网络请求失败:', err);
  817. return false; // 网络错误时默认按“未被拉黑”处理(避免误拦截)
  818. }
  819. // 严格校验接口返回格式
  820. if (!res.data || res.data.code !== 200) {
  821. console.error('接口返回格式错误:', res.data);
  822. return false;
  823. }
  824. // 关键修复:后端返回 data:true 表示“已被拉黑”,直接返回该值
  825. // 你的接口中 data 就是布尔值,无需额外解析
  826. const isBlocked = res.data.data;
  827. console.log('是否被拉黑:', isBlocked); // 确认这里输出为 true(被拉黑时)
  828. return isBlocked;
  829. } catch (error) {
  830. console.error('检查拉黑状态失败:', error);
  831. return false;
  832. }
  833. },
  834. /**
  835. * 发送文本消息
  836. */
  837. async sendTextMessage() {
  838. if (this.hasMessageLimit && this.remainingCount <= 0) {
  839. uni.showToast({
  840. title: '今日消息发送次数已用完,开通VIP无限制',
  841. icon: 'none',
  842. duration: 2000
  843. });
  844. return;
  845. }
  846. if (!this.inputText.trim()) {
  847. return;
  848. }
  849. const content = this.inputText;
  850. this.inputText = '';
  851. // 先检查是否被拉黑
  852. const isBlocked = await this.checkIsBlockedByTarget();
  853. if (isBlocked) {
  854. // 被拉黑时的处理保持不变
  855. const failedMessage = {
  856. messageId: 'failed_' + Date.now(),
  857. fromUserId: this.userId,
  858. toUserId: this.targetUserId,
  859. messageType: 1,
  860. content: content,
  861. sendStatus: 4, // 4表示发送失败
  862. sendTime: new Date(),
  863. fromUserName: '我'
  864. };
  865. this.messages.push(failedMessage);
  866. this.scrollToBottom();
  867. uni.showToast({
  868. title: '消息发送失败',
  869. icon: 'none'
  870. });
  871. return;
  872. }
  873. // 创建临时消息显示"发送中"
  874. const tempMessageId = 'temp_' + Date.now();
  875. const tempMessage = {
  876. messageId: tempMessageId,
  877. fromUserId: this.userId,
  878. toUserId: this.targetUserId,
  879. messageType: 1,
  880. content: content,
  881. sendStatus: 1, // 发送中
  882. sendTime: new Date(),
  883. fromUserName: '我'
  884. };
  885. this.messages.push(tempMessage);
  886. this.scrollToBottom();
  887. // 未被拉黑,正常发送
  888. try {
  889. const sendPromise = timManager.sendTextMessage(this.targetUserId, content);
  890. const timeoutPromise = new Promise((_, reject) => {
  891. setTimeout(() => reject(new Error('发送超时')), 15000);
  892. });
  893. const message = await Promise.race([sendPromise, timeoutPromise]);
  894. // 替换临时消息
  895. const tempIndex = this.messages.findIndex(m => m.messageId === tempMessageId);
  896. if (tempIndex > -1) {
  897. const convertedMsg = this.convertMessage(message);
  898. // 强制设置为已送达
  899. convertedMsg.sendStatus = 2;
  900. this.$set(this.messages, tempIndex, convertedMsg);
  901. }
  902. console.log('✅ 消息发送成功');
  903. this.syncMessageToMySQL(message);
  904. if (!this.isVip) {
  905. await this.updateMessageCount();
  906. }
  907. } catch (error) {
  908. console.error('❌ 消息发送失败:', error);
  909. // 更新临时消息为失败状态
  910. const tempIndex = this.messages.findIndex(m => m.messageId === tempMessageId);
  911. if (tempIndex > -1) {
  912. this.$set(this.messages[tempIndex], 'sendStatus', 4);
  913. }
  914. // 恢复输入框内容
  915. this.inputText = content;
  916. uni.showToast({
  917. title: '发送失败: ' + error.message,
  918. icon: 'none'
  919. });
  920. }
  921. },
  922. /**
  923. * 选择图片
  924. */
  925. chooseImage() {
  926. uni.chooseImage({
  927. count: 1,
  928. sizeType: ['compressed'],
  929. sourceType: ['album', 'camera'],
  930. success: async (res) => {
  931. // 1. 先检查是否被拉黑
  932. const isBlocked = await this.checkIsBlockedByTarget();
  933. if (isBlocked) {
  934. uni.showToast({
  935. title: '你已被对方拉黑,无法发送消息',
  936. icon: 'none'
  937. });
  938. return;
  939. }
  940. const tempFilePath = res.tempFilePaths[0];
  941. try {
  942. uni.showLoading({ title: '发送中...' });
  943. const message = await timManager.sendImageMessage(this.targetUserId, tempFilePath);
  944. this.messages.push(this.convertMessage(message));
  945. this.scrollToBottom();
  946. uni.hideLoading();
  947. console.log('✅ 图片发送成功');
  948. } catch (error) {
  949. uni.hideLoading();
  950. console.error('❌ 图片发送失败:', error);
  951. uni.showToast({
  952. title: '发送失败',
  953. icon: 'none'
  954. });
  955. }
  956. }
  957. });
  958. },
  959. /**
  960. * 输入框内容变化
  961. */
  962. onInputChange() {
  963. // 腾讯云 IM 可以实现正在输入状态,这里暂时省略
  964. console.log('输入中...');
  965. },
  966. /**
  967. * 同步消息到MySQL数据库(双重存储保障)
  968. */
  969. async syncMessageToMySQL(timMessage) {
  970. try {
  971. console.log('🔄 同步消息到MySQL...', timMessage.ID);
  972. // 构建同步参数
  973. const syncData = {
  974. messageId: timMessage.ID,
  975. fromUserId: timMessage.from,
  976. toUserId: timMessage.to,
  977. messageType: this.getMessageType(timMessage),
  978. content: this.getMessageContent(timMessage),
  979. sendTime: timMessage.time // TIM返回的是秒级时间戳
  980. };
  981. // 如果是图片消息,添加媒体信息
  982. if (timMessage.type === 'TIMImageElem' && timMessage.payload.imageInfoArray) {
  983. const imageInfo = timMessage.payload.imageInfoArray[0];
  984. syncData.mediaUrl = imageInfo.imageUrl;
  985. syncData.thumbnailUrl = imageInfo.imageUrl;
  986. }
  987. // 如果是语音消息,添加语音信息
  988. if (timMessage.type === 'TIMSoundElem' && timMessage.payload) {
  989. syncData.mediaUrl = timMessage.payload.url || timMessage.payload.remoteAudioUrl;
  990. syncData.duration = timMessage.payload.second || 0;
  991. syncData.mediaSize = timMessage.payload.size || 0;
  992. }
  993. // 如果是自定义消息(我们的语音消息)
  994. if (timMessage.type === 'TIMCustomElem' && timMessage.payload) {
  995. try {
  996. const customData = JSON.parse(timMessage.payload.data);
  997. if (customData.type === 'voice') {
  998. syncData.mediaUrl = customData.url;
  999. syncData.duration = customData.duration;
  1000. syncData.mediaSize = customData.size || 0;
  1001. }
  1002. } catch (e) {
  1003. console.error('解析自定义消息失败:', e);
  1004. }
  1005. }
  1006. // 调用后端同步接口
  1007. const res = await uni.request({
  1008. url: 'http://localhost:1004/api/chat/syncTIMMessage',
  1009. method: 'POST',
  1010. data: syncData,
  1011. header: {
  1012. 'Content-Type': 'application/json'
  1013. }
  1014. });
  1015. if (res[1].data.code === 200) {
  1016. console.log('✅ 消息已同步到MySQL:', timMessage.ID);
  1017. } else {
  1018. console.warn('⚠️ 消息同步失败:', res[1].data.message);
  1019. }
  1020. } catch (error) {
  1021. console.error('❌ 同步消息到MySQL失败:', error);
  1022. // 同步失败不影响聊天功能,只记录日志
  1023. }
  1024. },
  1025. /**
  1026. * 获取消息类型
  1027. */
  1028. getMessageType(timMessage) {
  1029. const typeMap = {
  1030. 'TIMTextElem': 1, // 文本
  1031. 'TIMImageElem': 2, // 图片
  1032. 'TIMSoundElem': 3, // 语音
  1033. 'TIMVideoFileElem': 4, // 视频
  1034. 'TIMFileElem': 5 // 文件
  1035. };
  1036. // 处理自定义消息(我们的语音消息)
  1037. if (timMessage.type === 'TIMCustomElem' && timMessage.payload) {
  1038. try {
  1039. const customData = JSON.parse(timMessage.payload.data);
  1040. if (customData.type === 'voice') {
  1041. return 3; // 语音消息
  1042. }
  1043. } catch (e) {
  1044. console.error('解析自定义消息类型失败:', e);
  1045. }
  1046. }
  1047. return typeMap[timMessage.type] || 1;
  1048. },
  1049. /**
  1050. * 获取消息内容
  1051. */
  1052. getMessageContent(timMessage) {
  1053. switch (timMessage.type) {
  1054. case 'TIMTextElem':
  1055. return timMessage.payload.text || '';
  1056. case 'TIMImageElem':
  1057. return '[图片]';
  1058. case 'TIMSoundElem':
  1059. return '[语音]';
  1060. case 'TIMVideoFileElem':
  1061. return '[视频]';
  1062. case 'TIMFileElem':
  1063. return '[文件]';
  1064. default:
  1065. return '[未知消息]';
  1066. }
  1067. },
  1068. /**
  1069. * 滚动到底部
  1070. */
  1071. scrollToBottom() {
  1072. this.$nextTick(() => {
  1073. const lastIndex = this.messages.length - 1;
  1074. this.scrollToView = 'msg-' + lastIndex;
  1075. });
  1076. },
  1077. /**
  1078. * 判断是否显示时间分隔线
  1079. */
  1080. shouldShowTime(msg, index) {
  1081. if (index === 0) return true;
  1082. const prevMsg = this.messages[index - 1];
  1083. const timeDiff = new Date(msg.sendTime) - new Date(prevMsg.sendTime);
  1084. // 超过5分钟显示时间
  1085. return timeDiff > 5 * 60 * 1000;
  1086. },
  1087. /**
  1088. * 格式化消息时间(用于时间分隔线)
  1089. */
  1090. formatMessageTime(time) {
  1091. const date = new Date(time);
  1092. const now = new Date();
  1093. const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  1094. const yesterday = new Date(today - 86400000);
  1095. // 今天
  1096. if (date >= today) {
  1097. return date.toLocaleTimeString('zh-CN', {
  1098. hour: '2-digit',
  1099. minute: '2-digit'
  1100. });
  1101. }
  1102. // 昨天
  1103. if (date >= yesterday) {
  1104. return '昨天 ' + date.toLocaleTimeString('zh-CN', {
  1105. hour: '2-digit',
  1106. minute: '2-digit'
  1107. });
  1108. }
  1109. // 本周
  1110. if (date > new Date(now - 7 * 86400000)) {
  1111. const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  1112. return days[date.getDay()] + ' ' + date.toLocaleTimeString('zh-CN', {
  1113. hour: '2-digit',
  1114. minute: '2-digit'
  1115. });
  1116. }
  1117. // 更早
  1118. return date.toLocaleString('zh-CN', {
  1119. month: '2-digit',
  1120. day: '2-digit',
  1121. hour: '2-digit',
  1122. minute: '2-digit'
  1123. });
  1124. },
  1125. /**
  1126. * 格式化时间(消息状态用)
  1127. */
  1128. formatTime(time) {
  1129. const date = new Date(time);
  1130. const now = new Date();
  1131. const diff = now - date;
  1132. if (diff < 60000) {
  1133. return '刚刚';
  1134. } else if (diff < 3600000) {
  1135. return Math.floor(diff / 60000) + '分钟前';
  1136. } else if (diff < 86400000) {
  1137. return Math.floor(diff / 3600000) + '小时前';
  1138. } else {
  1139. return date.toLocaleString('zh-CN', {
  1140. month: '2-digit',
  1141. day: '2-digit',
  1142. hour: '2-digit',
  1143. minute: '2-digit'
  1144. });
  1145. }
  1146. },
  1147. /**
  1148. * 预览图片
  1149. */
  1150. previewImage(url) {
  1151. uni.previewImage({
  1152. urls: [url],
  1153. current: url
  1154. });
  1155. },
  1156. /**
  1157. * 返回
  1158. */
  1159. goBack() {
  1160. uni.navigateBack({
  1161. success: () => {
  1162. // 通知消息列表页面刷新
  1163. uni.$emit('refreshConversations');
  1164. }
  1165. });
  1166. },
  1167. /**
  1168. * 显示消息操作菜单
  1169. */
  1170. showMessageMenu(msg, index) {
  1171. this.selectedMessage = msg;
  1172. this.selectedMessageIndex = index;
  1173. this.showMessageAction = true;
  1174. // 计算菜单位置
  1175. uni.createSelectorQuery().select('.message-item').boundingClientRect(rect => {
  1176. if (rect) {
  1177. this.menuTop = rect.top + rect.height;
  1178. }
  1179. }).exec();
  1180. },
  1181. /**
  1182. * 隐藏消息操作菜单
  1183. */
  1184. hideMessageMenu() {
  1185. this.showMessageAction = false;
  1186. this.selectedMessage = null;
  1187. this.selectedMessageIndex = -1;
  1188. },
  1189. /**
  1190. * 复制消息
  1191. */
  1192. copyMessage() {
  1193. if (!this.selectedMessage || this.selectedMessage.messageType !== 1) {
  1194. return;
  1195. }
  1196. uni.setClipboardData({
  1197. data: this.selectedMessage.content,
  1198. success: () => {
  1199. uni.showToast({
  1200. title: '已复制',
  1201. icon: 'success'
  1202. });
  1203. }
  1204. });
  1205. this.hideMessageMenu();
  1206. },
  1207. /**
  1208. * 判断是否可以撤回
  1209. */
  1210. canRecall(msg) {
  1211. const diff = Date.now() - new Date(msg.sendTime).getTime();
  1212. return diff < 2 * 60 * 1000; // 2分钟内可撤回
  1213. },
  1214. /**
  1215. * 撤回消息
  1216. */
  1217. async recallMessage() {
  1218. if (!this.selectedMessage) {
  1219. return;
  1220. }
  1221. try {
  1222. // 查找TIM消息对象
  1223. const timMessage = await timManager.tim.findMessage(this.selectedMessage.messageId);
  1224. if (timMessage) {
  1225. await timManager.revokeMessage(timMessage);
  1226. // 更新本地消息状态
  1227. this.selectedMessage.isRecalled = true;
  1228. this.selectedMessage.content = '你撤回了一条消息';
  1229. uni.showToast({
  1230. title: '已撤回',
  1231. icon: 'success'
  1232. });
  1233. }
  1234. } catch (error) {
  1235. console.error('撤回失败:', error);
  1236. uni.showToast({
  1237. title: '撤回失败',
  1238. icon: 'none'
  1239. });
  1240. }
  1241. this.hideMessageMenu();
  1242. },
  1243. /**
  1244. * 删除消息
  1245. */
  1246. deleteMessage() {
  1247. if (!this.selectedMessage) {
  1248. return;
  1249. }
  1250. uni.showModal({
  1251. title: '确认删除',
  1252. content: '确定要删除这条消息吗?',
  1253. success: (res) => {
  1254. if (res.confirm) {
  1255. // 从列表中删除
  1256. this.messages.splice(this.selectedMessageIndex, 1);
  1257. uni.showToast({
  1258. title: '已删除',
  1259. icon: 'success'
  1260. });
  1261. }
  1262. }
  1263. });
  1264. this.hideMessageMenu();
  1265. },
  1266. /**
  1267. * 处理消息点击
  1268. */
  1269. handleMessageClick(msg) {
  1270. // 如果是发送失败的消息,提示重试
  1271. if (msg.sendStatus === 4) {
  1272. uni.showModal({
  1273. title: '发送失败',
  1274. content: '消息发送失败,是否重试?',
  1275. success: (res) => {
  1276. if (res.confirm) {
  1277. this.retryMessage(msg);
  1278. }
  1279. }
  1280. });
  1281. }
  1282. },
  1283. /**
  1284. * 重试发送消息
  1285. */
  1286. async retryMessage(msg) {
  1287. if (msg.messageType !== 1) {
  1288. uni.showToast({ title: '暂不支持重发该类型消息', icon: 'none' });
  1289. return;
  1290. }
  1291. const isBlocked = await this.checkIsBlockedByTarget();
  1292. if (isBlocked) {
  1293. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1294. if (index > -1) {
  1295. this.$set(this.messages[index], 'sendStatus', 4);
  1296. }
  1297. uni.showToast({ title: '对方已拉黑你,无法发送', icon: 'none' });
  1298. return;
  1299. }
  1300. try {
  1301. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1302. if (index > -1) {
  1303. this.$set(this.messages[index], 'sendStatus', 1); // 发送中
  1304. }
  1305. const message = await timManager.sendTextMessage(this.targetUserId, msg.content);
  1306. // 更新消息状态为已送达
  1307. if (index > -1) {
  1308. const convertedMsg = this.convertMessage(message);
  1309. convertedMsg.sendStatus = 2; // 强制已送达
  1310. convertedMsg.messageId = msg.messageId; // 保持原ID
  1311. this.$set(this.messages, index, convertedMsg);
  1312. }
  1313. console.log('✅ 消息重发成功');
  1314. this.syncMessageToMySQL(message);
  1315. } catch (error) {
  1316. console.error('❌ 消息重发失败:', error);
  1317. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1318. if (index > -1) {
  1319. this.$set(this.messages[index], 'sendStatus', 4);
  1320. }
  1321. uni.showToast({ title: '发送失败', icon: 'none' });
  1322. }
  1323. },
  1324. // 其他功能方法
  1325. switchInputType() {
  1326. this.inputType = this.inputType === 'text' ? 'voice' : 'text';
  1327. },
  1328. /**
  1329. * 初始化在线状态监听
  1330. */
  1331. async initPresence() {
  1332. console.log('🔌 初始化在线状态监听');
  1333. console.log(' - 当前用户ID:', this.userId);
  1334. console.log(' - 对方用户ID:', this.targetUserId);
  1335. // 1. 首先通过HTTP API查询对方的在线状态(立即显示)
  1336. try {
  1337. const isOnline = await presenceManager.queryOnlineStatus(this.targetUserId);
  1338. this.isTargetOnline = isOnline;
  1339. console.log(' - HTTP查询初始在线状态:', this.isTargetOnline);
  1340. } catch (error) {
  1341. console.error('❌ HTTP查询在线状态失败:', error);
  1342. this.isTargetOnline = false;
  1343. }
  1344. // 2. 连接WebSocket(如果未连接)
  1345. if (!presenceManager.getConnectionStatus()) {
  1346. presenceManager.connect(this.userId);
  1347. // 等待WebSocket连接建立
  1348. await this.waitForWebSocketConnection();
  1349. }
  1350. // 3. 监听对方用户的在线状态变化
  1351. this.handleStatusChange = (status) => {
  1352. console.log(`👤 对方用户 ${this.targetUserId} 状态变更: ${status}`);
  1353. this.isTargetOnline = (status === 'online');
  1354. console.log(' - 更新后的在线状态:', this.isTargetOnline);
  1355. };
  1356. presenceManager.onStatusChange(this.targetUserId, this.handleStatusChange);
  1357. console.log('✅ 已订阅对方用户状态');
  1358. // 4. 监听已读回执(通过WebSocket)
  1359. if (presenceManager.websocket) {
  1360. const originalOnMessage = presenceManager.websocket.onmessage;
  1361. presenceManager.websocket.onmessage = (event) => {
  1362. // 先调用原有的消息处理
  1363. if (originalOnMessage) {
  1364. originalOnMessage.call(presenceManager.websocket, event);
  1365. }
  1366. // 处理已读回执
  1367. try {
  1368. const data = JSON.parse(event.data);
  1369. if (data.type === 'read' && data.fromUserId == this.targetUserId) {
  1370. this.handleReadReceipt(data);
  1371. }
  1372. } catch (error) {
  1373. console.error('❌ 解析WebSocket消息失败:', error);
  1374. }
  1375. };
  1376. console.log('✅ 已监听已读回执');
  1377. }
  1378. // 4. 定期轮询在线状态(作为补充,每30秒查询一次)
  1379. this.onlineStatusPollingTimer = setInterval(async () => {
  1380. try {
  1381. const isOnline = await presenceManager.queryOnlineStatus(this.targetUserId);
  1382. if (this.isTargetOnline !== isOnline) {
  1383. console.log(`🔄 轮询检测到状态变化: ${this.isTargetOnline} -> ${isOnline}`);
  1384. this.isTargetOnline = isOnline;
  1385. }
  1386. } catch (error) {
  1387. console.error('❌ 轮询查询在线状态失败:', error);
  1388. }
  1389. }, 30000); // 30秒轮询一次
  1390. },
  1391. /**
  1392. * 等待WebSocket连接建立
  1393. */
  1394. async waitForWebSocketConnection() {
  1395. return new Promise((resolve) => {
  1396. const maxWaitTime = 5000; // 最多等待5秒
  1397. const startTime = Date.now();
  1398. const checkConnection = setInterval(() => {
  1399. if (presenceManager.getConnectionStatus()) {
  1400. console.log('✅ WebSocket已连接');
  1401. clearInterval(checkConnection);
  1402. resolve();
  1403. } else if (Date.now() - startTime > maxWaitTime) {
  1404. console.log('⚠️ WebSocket连接超时,继续使用HTTP轮询');
  1405. clearInterval(checkConnection);
  1406. resolve();
  1407. }
  1408. }, 100);
  1409. });
  1410. },
  1411. /**
  1412. * 清理在线状态监听
  1413. */
  1414. cleanupPresence() {
  1415. console.log('🔌 清理在线状态监听');
  1416. // 清除轮询定时器
  1417. if (this.onlineStatusPollingTimer) {
  1418. clearInterval(this.onlineStatusPollingTimer);
  1419. this.onlineStatusPollingTimer = null;
  1420. }
  1421. if (this.handleStatusChange) {
  1422. presenceManager.offStatusChange(this.targetUserId, this.handleStatusChange);
  1423. this.handleStatusChange = null;
  1424. }
  1425. // 注意:不要断开WebSocket连接,因为其他页面可能还在使用
  1426. // presenceManager.disconnect();
  1427. },
  1428. /**
  1429. * 开始录音
  1430. */
  1431. startVoiceRecord(e) {
  1432. console.log('🎤 [按住说话] startVoiceRecord 方法被调用');
  1433. // 记录触摸起始位置
  1434. this.voiceTouchStartY = e.touches[0].clientY;
  1435. this.voiceCanceling = false;
  1436. // 检查消息发送限制
  1437. if (this.hasMessageLimit && this.remainingCount <= 0) {
  1438. uni.showToast({
  1439. title: '今日消息发送次数已用完',
  1440. icon: 'none'
  1441. });
  1442. return;
  1443. }
  1444. // 初始化录音管理器
  1445. if (!this.recorderManager) {
  1446. console.log('📱 初始化录音管理器');
  1447. this.recorderManager = uni.getRecorderManager();
  1448. // 录音开始
  1449. this.recorderManager.onStart(() => {
  1450. console.log('✅ 录音开始回调触发, voiceRecordCancelled:', this.voiceRecordCancelled);
  1451. // 关键修复:如果录音已被取消,不再恢复录音状态
  1452. if (this.voiceRecordCancelled) {
  1453. console.log('⚠️ 录音已被取消,忽略onStart回调');
  1454. // 立即停止录音
  1455. if (this.recorderManager) {
  1456. this.recorderManager.stop();
  1457. }
  1458. return;
  1459. }
  1460. this.isRecording = true;
  1461. this.showVoiceRecording = true;
  1462. this.voiceStartTime = Date.now();
  1463. console.log(' - isRecording:', this.isRecording);
  1464. console.log(' - showVoiceRecording:', this.showVoiceRecording);
  1465. });
  1466. // 录音结束
  1467. this.recorderManager.onStop((res) => {
  1468. console.log('🎤 录音结束:', res, ', voiceCanceling:', this.voiceCanceling);
  1469. this.isRecording = false;
  1470. this.showVoiceRecording = false;
  1471. // 如果是取消状态,不发送
  1472. if (this.voiceCanceling) {
  1473. console.log('❌ 录音已取消,不发送');
  1474. this.voiceCanceling = false;
  1475. return;
  1476. }
  1477. this.voiceTempPath = res.tempFilePath;
  1478. this.voiceDuration = Math.floor(res.duration / 1000); // 转换为秒
  1479. console.log(' - 文件路径:', this.voiceTempPath);
  1480. console.log(' - 时长:', this.voiceDuration, '秒');
  1481. // 时长验证
  1482. if (this.voiceDuration < 1) {
  1483. uni.showToast({
  1484. title: '录音时间太短',
  1485. icon: 'none'
  1486. });
  1487. return;
  1488. }
  1489. if (this.voiceDuration > 60) {
  1490. uni.showToast({
  1491. title: '录音时间不能超过60秒',
  1492. icon: 'none'
  1493. });
  1494. return;
  1495. }
  1496. // 发送语音消息
  1497. this.sendVoiceMessage();
  1498. });
  1499. // 录音错误
  1500. this.recorderManager.onError((err) => {
  1501. console.error('❌ 录音错误:', err);
  1502. this.isRecording = false;
  1503. this.showVoiceRecording = false;
  1504. uni.showToast({
  1505. title: '录音失败',
  1506. icon: 'none'
  1507. });
  1508. });
  1509. }
  1510. // 立即设置录音状态(不等待onStart回调)
  1511. this.isRecording = true;
  1512. this.showVoiceRecording = true;
  1513. this.voiceRecordCancelled = false; // 重置取消标志
  1514. this.voiceStartTime = Date.now();
  1515. this.voiceRecordingTime = 0;
  1516. this.voiceVolume = 0.3;
  1517. console.log('🎬 立即设置录音状态');
  1518. console.log(' - isRecording:', this.isRecording);
  1519. console.log(' - showVoiceRecording:', this.showVoiceRecording);
  1520. // 启动计时器
  1521. let volumeDirection = 1;
  1522. let currentVolume = 0.3;
  1523. this.voiceRecordingTimer = setInterval(() => {
  1524. this.voiceRecordingTime = Math.floor((Date.now() - this.voiceStartTime) / 1000);
  1525. // 模拟更真实的音量波动
  1526. // 随机决定是否有声音(80%概率有声音)
  1527. if (Math.random() > 0.2) {
  1528. // 有声音:平滑波动
  1529. currentVolume += volumeDirection * (0.1 + Math.random() * 0.2);
  1530. if (currentVolume > 1.0) {
  1531. currentVolume = 1.0;
  1532. volumeDirection = -1;
  1533. } else if (currentVolume < 0.4) {
  1534. currentVolume = 0.4;
  1535. volumeDirection = 1;
  1536. }
  1537. this.voiceVolume = currentVolume;
  1538. } else {
  1539. // 无声音:降低到最小
  1540. this.voiceVolume = Math.max(0.2, this.voiceVolume * 0.8);
  1541. }
  1542. }, 100);
  1543. // 开始录音
  1544. console.log('🎙️ 调用 recorderManager.start()');
  1545. try {
  1546. this.recorderManager.start({
  1547. format: 'mp3',
  1548. sampleRate: 16000,
  1549. numberOfChannels: 1,
  1550. encodeBitRate: 48000
  1551. });
  1552. console.log('✅ recorderManager.start() 调用成功');
  1553. } catch (err) {
  1554. console.error('❌ recorderManager.start() 调用失败:', err);
  1555. this.isRecording = false;
  1556. this.showVoiceRecording = false;
  1557. }
  1558. },
  1559. /**
  1560. * 停止录音
  1561. */
  1562. stopVoiceRecord() {
  1563. console.log('🎤 [松开] stopVoiceRecord 方法被调用, isRecording:', this.isRecording, ', voiceCanceling:', this.voiceCanceling);
  1564. // 清除计时器
  1565. if (this.voiceRecordingTimer) {
  1566. clearInterval(this.voiceRecordingTimer);
  1567. this.voiceRecordingTimer = null;
  1568. }
  1569. // 如果正在取消,则取消录音
  1570. if (this.voiceCanceling) {
  1571. console.log('🚫 检测到取消状态,调用 cancelVoiceRecord');
  1572. this.cancelVoiceRecord();
  1573. return;
  1574. }
  1575. if (this.isRecording && this.recorderManager) {
  1576. const duration = Date.now() - this.voiceStartTime;
  1577. // 录音时间太短
  1578. if (duration < 1000) {
  1579. this.recorderManager.stop();
  1580. this.isRecording = false;
  1581. this.showVoiceRecording = false;
  1582. uni.showToast({
  1583. title: '录音时间太短',
  1584. icon: 'none'
  1585. });
  1586. return;
  1587. }
  1588. this.recorderManager.stop();
  1589. }
  1590. },
  1591. /**
  1592. * 触摸移动 - 检测上滑取消
  1593. */
  1594. onVoiceTouchMove(e) {
  1595. if (!this.isRecording) return;
  1596. const currentY = e.touches[0].clientY;
  1597. const deltaY = this.voiceTouchStartY - currentY;
  1598. // 上滑超过100px,显示取消提示
  1599. if (deltaY > 100) {
  1600. this.voiceCanceling = true;
  1601. console.log('⬆️ 上滑取消录音');
  1602. } else {
  1603. this.voiceCanceling = false;
  1604. }
  1605. },
  1606. /**
  1607. * 取消录音
  1608. */
  1609. cancelVoiceRecord() {
  1610. console.log('❌ 取消录音, voiceCanceling:', this.voiceCanceling);
  1611. // 关键修复:标记录音已被取消,防止onStart回调恢复录音
  1612. this.voiceRecordCancelled = true;
  1613. // 清除计时器
  1614. if (this.voiceRecordingTimer) {
  1615. clearInterval(this.voiceRecordingTimer);
  1616. this.voiceRecordingTimer = null;
  1617. }
  1618. // 先设置取消状态,再停止录音
  1619. // 这样onStop回调中能正确判断
  1620. if (!this.voiceCanceling) {
  1621. this.voiceCanceling = true;
  1622. }
  1623. // 立即隐藏录音UI
  1624. this.isRecording = false;
  1625. this.showVoiceRecording = false;
  1626. if (this.recorderManager) {
  1627. // 尝试停止录音(如果已经开始)
  1628. try {
  1629. this.recorderManager.stop();
  1630. } catch (err) {
  1631. console.log('⚠️ 停止录音失败(可能还未开始):', err);
  1632. }
  1633. }
  1634. // 重置取消状态
  1635. this.voiceCanceling = false;
  1636. uni.showToast({
  1637. title: '已取消录音',
  1638. icon: 'none'
  1639. });
  1640. },
  1641. /**
  1642. * 发送语音消息
  1643. */
  1644. async sendVoiceMessage() {
  1645. // 检查是否被拉黑
  1646. const isBlocked = await this.checkIsBlockedByTarget();
  1647. if (isBlocked) {
  1648. uni.showToast({
  1649. title: '你已被对方拉黑,无法发送消息',
  1650. icon: 'none'
  1651. });
  1652. return;
  1653. }
  1654. try {
  1655. uni.showLoading({ title: '上传中...' });
  1656. // 第一步:上传语音文件到MinIO
  1657. const uploadResult = await this.uploadVoiceToMinIO();
  1658. if (!uploadResult.success) {
  1659. throw new Error(uploadResult.message || '上传失败');
  1660. }
  1661. console.log('✅ 语音文件上传成功:', uploadResult.fileUrl);
  1662. uni.showLoading({ title: '发送中...' });
  1663. // 第二步:通过腾讯IM发送语音消息(携带MinIO URL)
  1664. const message = await timManager.sendVoiceMessage(
  1665. this.targetUserId,
  1666. uploadResult.fileUrl,
  1667. this.voiceDuration,
  1668. uploadResult.fileSize
  1669. );
  1670. // 添加到消息列表
  1671. this.messages.push(this.convertMessage(message));
  1672. this.scrollToBottom();
  1673. uni.hideLoading();
  1674. console.log('✅ 语音消息发送成功');
  1675. // 同步到MySQL
  1676. this.syncMessageToMySQL(message);
  1677. // 更新消息计数
  1678. if (!this.isVip) {
  1679. await this.updateMessageCount();
  1680. }
  1681. } catch (error) {
  1682. uni.hideLoading();
  1683. console.error('❌ 语音消息发送失败:', error);
  1684. uni.showToast({
  1685. title: '发送失败: ' + error.message,
  1686. icon: 'none'
  1687. });
  1688. }
  1689. },
  1690. /**
  1691. * 上传语音文件到MinIO
  1692. */
  1693. async uploadVoiceToMinIO() {
  1694. try {
  1695. console.log('📤 开始上传语音文件到MinIO...');
  1696. console.log(' - 文件路径:', this.voiceTempPath);
  1697. console.log(' - 时长:', this.voiceDuration, '秒');
  1698. // 使用uni.uploadFile上传到后端MinIO接口
  1699. const [err, res] = await uni.uploadFile({
  1700. url: 'http://localhost:1004/api/voice/upload',
  1701. filePath: this.voiceTempPath,
  1702. name: 'file',
  1703. header: {
  1704. 'Content-Type': 'multipart/form-data'
  1705. }
  1706. });
  1707. if (err) {
  1708. console.error('❌ 上传请求失败:', err);
  1709. return {
  1710. success: false,
  1711. message: '网络请求失败'
  1712. };
  1713. }
  1714. // 解析响应
  1715. const result = JSON.parse(res.data);
  1716. console.log('📥 MinIO上传响应:', result);
  1717. if (result.success) {
  1718. return {
  1719. success: true,
  1720. fileUrl: result.fileUrl,
  1721. fileSize: result.fileSize
  1722. };
  1723. } else {
  1724. return {
  1725. success: false,
  1726. message: result.message || '上传失败'
  1727. };
  1728. }
  1729. } catch (error) {
  1730. console.error('❌ 上传语音文件失败:', error);
  1731. return {
  1732. success: false,
  1733. message: error.message || '上传异常'
  1734. };
  1735. }
  1736. },
  1737. insertEmoji(emoji) {
  1738. this.inputText += emoji;
  1739. this.showEmojiPanel = false;
  1740. },
  1741. chooseVideo() {
  1742. uni.showToast({
  1743. title: '视频功能开发中',
  1744. icon: 'none'
  1745. });
  1746. },
  1747. chooseFile() {
  1748. uni.showToast({
  1749. title: '文件功能开发中',
  1750. icon: 'none'
  1751. });
  1752. },
  1753. /**
  1754. * 切换语音播放/暂停
  1755. */
  1756. toggleVoicePlay(msg) {
  1757. // 如果正在播放这条语音,则暂停
  1758. if (this.playingVoiceId === msg.messageId) {
  1759. this.pauseVoice(msg);
  1760. } else {
  1761. // 否则开始播放
  1762. this.playVoice(msg);
  1763. }
  1764. },
  1765. /**
  1766. * 播放语音
  1767. */
  1768. playVoice(msg) {
  1769. console.log('📢 [播放语音] 开始 - messageId:', msg.messageId);
  1770. if (!msg.mediaUrl) {
  1771. // 如果是TIM消息,从payload中获取URL
  1772. const audioUrl = msg.payload?.url || msg.payload?.remoteAudioUrl;
  1773. if (!audioUrl) {
  1774. uni.showToast({
  1775. title: '语音文件不存在',
  1776. icon: 'none'
  1777. });
  1778. return;
  1779. }
  1780. msg.mediaUrl = audioUrl;
  1781. }
  1782. // 如果有其他语音正在播放,先停止
  1783. if (this.currentAudioContext) {
  1784. console.log('⏹️ 停止之前的语音');
  1785. this.currentAudioContext.stop();
  1786. this.currentAudioContext.destroy();
  1787. this.currentAudioContext = null;
  1788. }
  1789. // 清除暂停状态
  1790. this.pausedVoiceId = null;
  1791. // 设置当前播放的语音ID,触发动画
  1792. this.playingVoiceId = msg.messageId;
  1793. console.log('🎬 [动画开始] playingVoiceId =', this.playingVoiceId);
  1794. // 创建音频上下文
  1795. const innerAudioContext = uni.createInnerAudioContext();
  1796. innerAudioContext.src = msg.mediaUrl;
  1797. innerAudioContext.loop = false; // 不循环播放
  1798. this.currentAudioContext = innerAudioContext;
  1799. innerAudioContext.onPlay(() => {
  1800. console.log('🔊 开始播放语音');
  1801. });
  1802. innerAudioContext.onEnded(() => {
  1803. console.log('✅ 语音播放完成');
  1804. this.playingVoiceId = null; // 停止动画
  1805. this.pausedVoiceId = null;
  1806. this.currentAudioContext = null;
  1807. console.log('🛑 [动画停止] playingVoiceId =', this.playingVoiceId);
  1808. innerAudioContext.destroy();
  1809. });
  1810. innerAudioContext.onError((err) => {
  1811. console.error('❌ 语音播放失败:', err);
  1812. this.playingVoiceId = null; // 停止动画
  1813. this.pausedVoiceId = null;
  1814. this.currentAudioContext = null;
  1815. console.log('🛑 [动画停止-错误] playingVoiceId =', this.playingVoiceId);
  1816. uni.showToast({
  1817. title: '播放失败',
  1818. icon: 'none'
  1819. });
  1820. innerAudioContext.destroy();
  1821. });
  1822. innerAudioContext.play();
  1823. },
  1824. /**
  1825. * 暂停语音
  1826. */
  1827. pauseVoice(msg) {
  1828. if (this.currentAudioContext) {
  1829. this.currentAudioContext.pause();
  1830. this.playingVoiceId = null; // 停止动画
  1831. this.pausedVoiceId = msg.messageId; // 设置暂停状态
  1832. console.log('⏸️ [暂停] playingVoiceId =', this.playingVoiceId, ', pausedVoiceId =', this.pausedVoiceId);
  1833. }
  1834. },
  1835. /**
  1836. * 继续播放语音
  1837. */
  1838. resumeVoice() {
  1839. if (this.currentAudioContext && this.pausedVoiceId) {
  1840. this.currentAudioContext.play();
  1841. this.playingVoiceId = this.pausedVoiceId; // 恢复动画
  1842. const resumedId = this.pausedVoiceId;
  1843. this.pausedVoiceId = null; // 清除暂停状态
  1844. console.log('▶️ [继续播放] playingVoiceId =', this.playingVoiceId, ', pausedVoiceId =', this.pausedVoiceId);
  1845. }
  1846. },
  1847. showMoreOptions() {
  1848. this.showMoreOptionsModal = true;
  1849. },
  1850. closeMoreOptions() {
  1851. this.showMoreOptionsModal = false;
  1852. },
  1853. /**
  1854. * 查看用户资料(跳转到原有more页面)
  1855. */
  1856. goToUserProfile() {
  1857. this.closeMoreOptions();
  1858. uni.navigateTo({
  1859. url: `/pages/message/more?userid=${this.targetUserId}`,
  1860. fail: (err) => {
  1861. console.error('跳转失败:', err);
  1862. uni.showToast({
  1863. title: '页面不存在',
  1864. icon: 'none'
  1865. });
  1866. }
  1867. });
  1868. },
  1869. /**
  1870. * 显示拉黑确认弹窗
  1871. */
  1872. blockFriend() {
  1873. this.closeMoreOptions();
  1874. this.showBlockConfirmModal = true;
  1875. },
  1876. /**
  1877. * 关闭拉黑确认弹窗
  1878. */
  1879. closeBlockConfirm() {
  1880. this.showBlockConfirmModal = false;
  1881. },
  1882. /**
  1883. * 从后端获取VIP状态和今日剩余发送次数
  1884. */
  1885. async getUserMessageLimit() {
  1886. try {
  1887. const [err, res] = await uni.request({
  1888. url: 'http://localhost:1004/api/chat/getUserMessageLimit',
  1889. method: 'GET',
  1890. data: {
  1891. userId: this.userId ,// 已在onLoad中初始化的当前用户ID
  1892. targetUserId: this.targetUserId
  1893. },
  1894. header: {
  1895. 'Content-Type': 'application/json'
  1896. }
  1897. });
  1898. if (err) throw new Error('网络请求失败');
  1899. if (res.data.code !== 200) throw new Error(res.data.message || '获取限制信息失败');
  1900. const { isVip, remainingCount, hasMessageLimit } = res.data.data;
  1901. this.isVip = isVip;
  1902. this.remainingCount = remainingCount;
  1903. this.hasMessageLimit = hasMessageLimit;
  1904. console.log('✅ 用户消息限制信息:', { isVip, remainingCount, hasMessageLimit });
  1905. } catch (error) {
  1906. console.error('❌ 获取消息限制失败:', error);
  1907. // 异常降级:默认非VIP,剩余5次
  1908. this.isVip = false;
  1909. this.remainingCount = 5;
  1910. this.hasMessageLimit = true;
  1911. }
  1912. },
  1913. /**
  1914. * 发送成功后,更新后端计数并同步前端剩余次数
  1915. */
  1916. async updateMessageCount() {
  1917. try {
  1918. const [err, res] = await uni.request({
  1919. url: 'http://localhost:8083/api/chat/updateMessageCount',
  1920. method: 'get',
  1921. data: {
  1922. userId: this.userId ,// 已在onLoad中初始化的当前用户ID
  1923. targetUserId: this.targetUserId
  1924. },
  1925. header: {
  1926. 'Content-Type': 'application/json'
  1927. }
  1928. });
  1929. if (err) throw new Error('更新计数失败');
  1930. if (res.data.code === 200) {
  1931. this.remainingCount = res.data.data.remainingCount; // 同步后端返回的剩余次数
  1932. }
  1933. } catch (error) {
  1934. console.error('❌ 更新发送次数失败:', error);
  1935. // 前端本地降级:避免影响用户体验,本地暂减1(刷新页面后同步真实数据)
  1936. if (this.remainingCount > 0) {
  1937. this.remainingCount--;
  1938. }
  1939. }
  1940. },
  1941. /**
  1942. * 确认拉黑好友
  1943. */
  1944. async confirmBlockFriend() {
  1945. try {
  1946. uni.showLoading({
  1947. title: '处理中...'
  1948. });
  1949. // 调用后端拉黑接口(根据实际接口调整)
  1950. const [err, res] = await uni.request({
  1951. url: 'http://localhost:8083/api/chatfriend/block',
  1952. method: 'POST',
  1953. data: {
  1954. userId: this.userId,
  1955. targetUserId: this.targetUserId,
  1956. targetUserName: this.targetUserName,
  1957. targetUserAvatar: this.targetUserAvatar
  1958. },
  1959. header: {
  1960. 'Content-Type': 'application/json',
  1961. // 'Authorization': 'Bearer ' + uni.getStorageSync('token')
  1962. }
  1963. });
  1964. uni.hideLoading();
  1965. if (err) throw new Error('网络请求失败');
  1966. if (res.data && res.data.code === 200) {
  1967. uni.showToast({ title: '拉黑成功', icon: 'success' });
  1968. this.closeBlockConfirm();
  1969. // 触发拉黑列表更新事件,通知消息页面实时刷新
  1970. uni.$emit('blacklistUpdated');
  1971. // 拉黑成功后立即返回消息列表页面(优化体验)
  1972. setTimeout(() => {
  1973. uni.navigateBack({
  1974. delta: 1,
  1975. success: () => {
  1976. // 返回成功后再次触发一次刷新,确保万无一失
  1977. uni.$emit('blacklistUpdated');
  1978. }
  1979. });
  1980. }, 1500);
  1981. } else {
  1982. throw new Error(res.data?.message || '拉黑失败');
  1983. }
  1984. } catch (error) {
  1985. console.error('拉黑失败:', error);
  1986. uni.showToast({ title: error.message || '拉黑失败', icon: 'none' });
  1987. }
  1988. },
  1989. }
  1990. };
  1991. </script>
  1992. <style scoped>
  1993. /* 弹窗遮罩 */
  1994. .modal-mask {
  1995. position: fixed;
  1996. top: 0;
  1997. left: 0;
  1998. right: 0;
  1999. bottom: 0;
  2000. background-color: rgba(0, 0, 0, 0.5);
  2001. z-index: 10000;
  2002. display: flex;
  2003. align-items: center;
  2004. justify-content: center;
  2005. }
  2006. /* 更多选项弹窗内容 */
  2007. .modal-content {
  2008. width: 70%;
  2009. background-color: #fff;
  2010. border-radius: 20rpx;
  2011. overflow: hidden;
  2012. }
  2013. .modal-header {
  2014. padding: 30rpx;
  2015. text-align: center;
  2016. border-bottom: 1px solid #eee;
  2017. }
  2018. .modal-title {
  2019. font-size: 32rpx;
  2020. font-weight: bold;
  2021. display: block;
  2022. }
  2023. .modal-subtitle {
  2024. font-size: 24rpx;
  2025. color: #999;
  2026. display: block;
  2027. margin-top: 10rpx;
  2028. }
  2029. .modal-body {
  2030. padding: 20rpx 0;
  2031. }
  2032. .modal-item {
  2033. display: flex;
  2034. align-items: center;
  2035. padding: 25rpx 40rpx;
  2036. font-size: 30rpx;
  2037. }
  2038. .modal-item.danger {
  2039. color: #fa5151;
  2040. }
  2041. .item-icon {
  2042. font-size: 32rpx;
  2043. margin-right: 20rpx;
  2044. }
  2045. .modal-footer {
  2046. padding: 20rpx;
  2047. border-top: 1px solid #eee;
  2048. }
  2049. .modal-close-btn {
  2050. width: 94%;
  2051. background-color: #f5f5f5;
  2052. border: none;
  2053. border-radius: 10rpx;
  2054. padding: 20rpx;
  2055. font-size: 30rpx;
  2056. }
  2057. /* 确认弹窗样式 */
  2058. .confirm-modal {
  2059. width: 60%;
  2060. background-color: #fff;
  2061. border-radius: 20rpx;
  2062. padding: 40rpx;
  2063. text-align: center;
  2064. }
  2065. .confirm-title {
  2066. font-size: 32rpx;
  2067. font-weight: bold;
  2068. margin-bottom: 30rpx;
  2069. }
  2070. .confirm-content {
  2071. font-size: 28rpx;
  2072. color: #666;
  2073. margin-bottom: 40rpx;
  2074. line-height: 1.5;
  2075. }
  2076. .confirm-buttons {
  2077. display: flex;
  2078. justify-content: space-between;
  2079. }
  2080. .confirm-btn {
  2081. flex: 1;
  2082. margin: 0 10rpx;
  2083. padding: 20rpx;
  2084. border-radius: 10rpx;
  2085. border: none;
  2086. font-size: 28rpx;
  2087. }
  2088. .confirm-btn.cancel {
  2089. background-color: #f5f5f5;
  2090. }
  2091. .confirm-btn.confirm {
  2092. background-color: #fa5151;
  2093. color: #fff;
  2094. }
  2095. .chat-page {
  2096. display: flex;
  2097. flex-direction: column;
  2098. height: 100vh;
  2099. background-color: #f5f5f5;
  2100. }
  2101. /* 顶部导航 */
  2102. .chat-header {
  2103. display: flex;
  2104. align-items: center;
  2105. justify-content: space-between;
  2106. padding: 20rpx 30rpx;
  2107. background-color: #fff;
  2108. border-bottom: 1px solid #e5e5e5;
  2109. }
  2110. .header-left, .header-right {
  2111. width: 80rpx;
  2112. }
  2113. .icon-back, .icon-more {
  2114. font-size: 40rpx;
  2115. }
  2116. .header-center {
  2117. flex: 1;
  2118. text-align: center;
  2119. }
  2120. .chat-title {
  2121. display: block;
  2122. font-size: 36rpx;
  2123. font-weight: bold;
  2124. }
  2125. .online-status {
  2126. display: block;
  2127. font-size: 24rpx;
  2128. color: #999;
  2129. margin-top: 5rpx;
  2130. }
  2131. .online-status.online {
  2132. color: #07c160;
  2133. }
  2134. /* 消息列表 */
  2135. .message-list {
  2136. flex: 1;
  2137. padding: 20rpx;
  2138. overflow-y: scroll;
  2139. }
  2140. .loading-tip {
  2141. text-align: center;
  2142. padding: 20rpx;
  2143. color: #999;
  2144. font-size: 28rpx;
  2145. }
  2146. .message-item {
  2147. display: flex;
  2148. margin-bottom: 30rpx;
  2149. }
  2150. .message-item.message-self {
  2151. flex-direction: row-reverse;
  2152. }
  2153. .avatar {
  2154. width: 80rpx;
  2155. height: 80rpx;
  2156. border-radius: 8rpx;
  2157. margin: 0 20rpx;
  2158. }
  2159. .message-content-wrapper {
  2160. max-width: 70%;
  2161. display: inline-block;
  2162. }
  2163. .message-item.message-self .message-content-wrapper {
  2164. text-align: right; /* 关键:让气泡和状态提示整体右对齐 */
  2165. }
  2166. .message-name {
  2167. display: block;
  2168. font-size: 24rpx;
  2169. color: #999;
  2170. margin-bottom: 10rpx;
  2171. }
  2172. .message-bubble {
  2173. padding: 20rpx;
  2174. border-radius: 8rpx;
  2175. background-color: #fff;
  2176. word-wrap: break-word;
  2177. display: inline-block; /* 关键:气泡宽度由内容决定 */
  2178. max-width: 100%; /* 防止内容过长超出容器 */
  2179. position: relative;
  2180. }
  2181. .message-self .message-bubble {
  2182. background-color: #95ec69;
  2183. border-top-right-radius: 4rpx;
  2184. }
  2185. .message-bubble.bubble-self {
  2186. background-color: #95ec69;
  2187. }
  2188. .message-text {
  2189. font-size: 30rpx;
  2190. line-height: 1.5;
  2191. }
  2192. .message-image {
  2193. max-width: 400rpx;
  2194. border-radius: 8rpx;
  2195. }
  2196. .message-voice {
  2197. display: flex;
  2198. align-items: center;
  2199. gap: 12rpx;
  2200. padding: 0rpx 0;
  2201. min-width: 30rpx;
  2202. max-width: 400rpx;
  2203. cursor: pointer;
  2204. -webkit-tap-highlight-color: transparent;
  2205. outline: none;
  2206. border: none;
  2207. position: relative;
  2208. }
  2209. .voice-duration {
  2210. font-size: 27rpx;
  2211. color: #333;
  2212. flex-shrink: 0;
  2213. line-height: 1;
  2214. }
  2215. .voice-icon-wrapper {
  2216. display: flex;
  2217. flex-shrink: 0;
  2218. line-height: 0;
  2219. position: relative;
  2220. top: 1rpx;
  2221. }
  2222. .voice-icon {
  2223. width: 22rpx;
  2224. height: 22rpx;
  2225. display: block;
  2226. transform: none;
  2227. animation: none;
  2228. }
  2229. .voice-icon-wrapper.playing .voice-icon {
  2230. animation: voice-bounce 0.6s ease-in-out infinite;
  2231. }
  2232. .voice-resume-btn {
  2233. position: absolute;
  2234. top: 50%;
  2235. transform: translateY(-50%);
  2236. width: 32rpx;
  2237. height: 32rpx;
  2238. background: #07c160;
  2239. border-radius: 50%;
  2240. display: flex;
  2241. align-items: center;
  2242. justify-content: center;
  2243. box-shadow: 0 2rpx 8rpx rgba(7, 193, 96, 0.3);
  2244. }
  2245. .voice-resume-btn.resume-btn-left {
  2246. left: -40rpx;
  2247. }
  2248. .voice-resume-btn.resume-btn-right {
  2249. right: -40rpx;
  2250. }
  2251. .resume-icon {
  2252. color: #fff;
  2253. font-size: 16rpx;
  2254. margin-left: 2rpx;
  2255. }
  2256. @keyframes voice-bounce {
  2257. 0%, 100% {
  2258. transform: scale(1);
  2259. }
  2260. 50% {
  2261. transform: scale(1.2);
  2262. }
  2263. }
  2264. .message-video {
  2265. width: 400rpx;
  2266. height: 300rpx;
  2267. }
  2268. .message-recalled {
  2269. color: #999;
  2270. font-size: 28rpx;
  2271. }
  2272. .message-status {
  2273. text-align: right;
  2274. font-size: 24rpx;
  2275. color: #999;
  2276. margin-top: 5rpx;
  2277. }
  2278. .message-status .read {
  2279. color: #07c160;
  2280. }
  2281. .message-status .failed {
  2282. color: #fa5151;
  2283. }
  2284. .message-time {
  2285. display: block;
  2286. text-align: right;
  2287. font-size: 22rpx;
  2288. color: #ccc;
  2289. margin-top: 5rpx;
  2290. }
  2291. /* 输入框 */
  2292. .input-bar {
  2293. display: flex;
  2294. align-items: center;
  2295. padding: 20rpx;
  2296. background-color: #fff;
  2297. border-top: 1px solid #e5e5e5;
  2298. }
  2299. .input-icon {
  2300. width: 80rpx;
  2301. height: 80rpx;
  2302. display: flex;
  2303. align-items: center;
  2304. justify-content: center;
  2305. font-size: 50rpx;
  2306. }
  2307. .send-button {
  2308. padding: 0 30rpx;
  2309. height: 70rpx;
  2310. line-height: 70rpx;
  2311. background-color: #07c160;
  2312. color: #fff;
  2313. border-radius: 8rpx;
  2314. text-align: center;
  2315. font-size: 28rpx;
  2316. margin-left: 10rpx;
  2317. transition: opacity 0.3s;
  2318. }
  2319. .send-button.disabled {
  2320. opacity: 0.5;
  2321. background-color: #95ec69;
  2322. }
  2323. .input-field {
  2324. flex: 1;
  2325. height: 70rpx;
  2326. padding: 0 20rpx;
  2327. background-color: #f5f5f5;
  2328. border-radius: 8rpx;
  2329. font-size: 30rpx;
  2330. }
  2331. .voice-button {
  2332. flex: 1;
  2333. height: 70rpx;
  2334. line-height: 70rpx;
  2335. background-color: #f5f5f5;
  2336. border-radius: 8rpx;
  2337. text-align: center;
  2338. font-size: 30rpx;
  2339. border: none;
  2340. }
  2341. /* 表情面板 */
  2342. .emoji-panel {
  2343. display: flex;
  2344. flex-wrap: wrap;
  2345. padding: 20rpx;
  2346. background-color: #fff;
  2347. border-top: 1px solid #e5e5e5;
  2348. }
  2349. .emoji-item {
  2350. width: 80rpx;
  2351. height: 80rpx;
  2352. display: flex;
  2353. align-items: center;
  2354. justify-content: center;
  2355. font-size: 60rpx;
  2356. }
  2357. /* 更多功能面板 */
  2358. .more-panel {
  2359. display: flex;
  2360. padding: 40rpx;
  2361. background-color: #fff;
  2362. border-top: 1px solid #e5e5e5;
  2363. }
  2364. .more-item {
  2365. display: flex;
  2366. flex-direction: column;
  2367. align-items: center;
  2368. margin: 0 40rpx;
  2369. }
  2370. .more-icon {
  2371. width: 100rpx;
  2372. height: 100rpx;
  2373. display: flex;
  2374. align-items: center;
  2375. justify-content: center;
  2376. font-size: 60rpx;
  2377. background-color: #f5f5f5;
  2378. border-radius: 16rpx;
  2379. margin-bottom: 10rpx;
  2380. }
  2381. .more-text {
  2382. font-size: 24rpx;
  2383. color: #666;
  2384. }
  2385. /* 时间分隔线 */
  2386. .time-divider {
  2387. text-align: center;
  2388. padding: 20rpx 0;
  2389. }
  2390. .time-text {
  2391. display: inline-block;
  2392. padding: 8rpx 20rpx;
  2393. background-color: rgba(0, 0, 0, 0.1);
  2394. border-radius: 8rpx;
  2395. font-size: 22rpx;
  2396. color: #999;
  2397. }
  2398. /* 消息气泡失败状态 */
  2399. .bubble-failed {
  2400. background-color: #95ec69;
  2401. opacity: 0.6;
  2402. border: 2rpx solid #fa5151;
  2403. }
  2404. /* 消息状态优化 */
  2405. .message-status .sending {
  2406. color: #576b95;
  2407. }
  2408. .message-status .failed-group {
  2409. display: flex;
  2410. align-items: center;
  2411. gap: 10rpx;
  2412. }
  2413. .message-status .retry-btn {
  2414. color: #576b95;
  2415. text-decoration: underline;
  2416. cursor: pointer;
  2417. }
  2418. /* 消息操作菜单遮罩 */
  2419. .message-action-mask {
  2420. position: fixed;
  2421. top: 0;
  2422. left: 0;
  2423. right: 0;
  2424. bottom: 0;
  2425. background-color: rgba(0, 0, 0, 0.4);
  2426. z-index: 9999;
  2427. display: flex;
  2428. align-items: center;
  2429. justify-content: center;
  2430. }
  2431. /* 消息操作菜单 */
  2432. .message-action-menu {
  2433. width: 600rpx;
  2434. background-color: #fff;
  2435. border-radius: 20rpx;
  2436. overflow: hidden;
  2437. }
  2438. .message-action-menu .menu-item {
  2439. display: flex;
  2440. align-items: center;
  2441. justify-content: center;
  2442. gap: 15rpx;
  2443. padding: 30rpx;
  2444. font-size: 32rpx;
  2445. color: #333;
  2446. border-bottom: 1rpx solid #f0f0f0;
  2447. transition: background-color 0.2s;
  2448. }
  2449. .message-action-menu .menu-item:active {
  2450. background-color: #f5f5f5;
  2451. }
  2452. .message-action-menu .menu-item.cancel {
  2453. color: #999;
  2454. border-bottom: none;
  2455. margin-top: 20rpx;
  2456. border-top: 10rpx solid #f5f5f5;
  2457. }
  2458. .message-action-menu .menu-icon {
  2459. font-size: 36rpx;
  2460. }
  2461. /* 消息发送限制提示 */
  2462. .message-limit-tip {
  2463. padding: 10rpx 20rpx;
  2464. font-size: 24rpx;
  2465. text-align: center;
  2466. background-color: #fff;
  2467. border-bottom: 1px solid #f5f5f5;
  2468. }
  2469. .vip-tip {
  2470. color: #ff9500; /* VIP橙色提示 */
  2471. }
  2472. .limit-tip {
  2473. color: #666; /* 普通灰色提示 */
  2474. }
  2475. .vip-link {
  2476. color: #2c9fff; /* 蓝色文字 */
  2477. text-decoration: underline; /* 下划线 */
  2478. cursor: pointer; /* 鼠标悬浮时显示手型 */
  2479. margin-left: 5rpx;
  2480. }
  2481. /* 点击时添加轻微反馈 */
  2482. .vip-link:active {
  2483. opacity: 0.7; /* 点击时透明度降低 */
  2484. }
  2485. /* 录音中提示遮罩 */
  2486. .voice-recording-mask {
  2487. position: fixed;
  2488. top: 0;
  2489. left: 0;
  2490. right: 0;
  2491. bottom: 0;
  2492. background-color: rgba(0, 0, 0, 0.6);
  2493. z-index: 10000;
  2494. display: flex;
  2495. align-items: center;
  2496. justify-content: center;
  2497. }
  2498. /* 录音提示框 */
  2499. .voice-recording-box {
  2500. width: 300rpx;
  2501. height: 300rpx;
  2502. background-color: rgba(0, 0, 0, 0.8);
  2503. border-radius: 20rpx;
  2504. display: flex;
  2505. flex-direction: column;
  2506. align-items: center;
  2507. justify-content: center;
  2508. color: #fff;
  2509. transition: background-color 0.3s;
  2510. }
  2511. .voice-recording-box.canceling {
  2512. background-color: rgba(220, 38, 38, 0.9);
  2513. }
  2514. .voice-wave-container {
  2515. display: flex;
  2516. align-items: center;
  2517. justify-content: center;
  2518. gap: 8rpx;
  2519. height: 100rpx;
  2520. margin-bottom: 20rpx;
  2521. }
  2522. .voice-wave-bar {
  2523. width: 6rpx;
  2524. background: #fff;
  2525. border-radius: 3rpx;
  2526. transition: transform 0.1s ease-out;
  2527. transform-origin: center;
  2528. }
  2529. .voice-wave-bar.bar1 {
  2530. height: 30rpx;
  2531. }
  2532. .voice-wave-bar.bar2 {
  2533. height: 45rpx;
  2534. }
  2535. .voice-wave-bar.bar3 {
  2536. height: 60rpx;
  2537. }
  2538. .voice-wave-bar.bar4 {
  2539. height: 50rpx;
  2540. }
  2541. .voice-wave-bar.bar5 {
  2542. height: 35rpx;
  2543. }
  2544. .voice-text {
  2545. font-size: 32rpx;
  2546. margin-bottom: 10rpx;
  2547. }
  2548. .voice-time {
  2549. font-size: 48rpx;
  2550. font-weight: bold;
  2551. color: #07c160;
  2552. margin: 10rpx 0;
  2553. }
  2554. .voice-tip {
  2555. font-size: 24rpx;
  2556. color: #ccc;
  2557. }
  2558. </style>