chat.vue 93 KB

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