chat.vue 92 KB

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