chat.vue 94 KB

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