chat.vue 92 KB

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