chat.vue 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156
  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. // 构建同步参数
  1129. const syncData = {
  1130. messageId: timMessage.ID,
  1131. fromUserId: timMessage.from,
  1132. toUserId: timMessage.to,
  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. // 调用后端同步接口
  1163. const res = await uni.request({
  1164. url: 'http://localhost:8083/api/chat/syncTIMMessage',
  1165. method: 'POST',
  1166. data: syncData,
  1167. header: {
  1168. 'Content-Type': 'application/json'
  1169. }
  1170. });
  1171. if (res[1].data.code === 200) {
  1172. console.log('✅ 消息已同步到MySQL:', timMessage.ID);
  1173. } else {
  1174. console.warn('⚠️ 消息同步失败:', res[1].data.message);
  1175. }
  1176. } catch (error) {
  1177. console.error('❌ 同步消息到MySQL失败:', error);
  1178. // 同步失败不影响聊天功能,只记录日志
  1179. }
  1180. },
  1181. /**
  1182. * 获取消息类型
  1183. */
  1184. getMessageType(timMessage) {
  1185. const typeMap = {
  1186. 'TIMTextElem': 1, // 文本
  1187. 'TIMImageElem': 2, // 图片
  1188. 'TIMSoundElem': 3, // 语音
  1189. 'TIMVideoFileElem': 4, // 视频
  1190. 'TIMFileElem': 5 // 文件
  1191. };
  1192. // 处理自定义消息(我们的语音消息)
  1193. if (timMessage.type === 'TIMCustomElem' && timMessage.payload) {
  1194. try {
  1195. const customData = JSON.parse(timMessage.payload.data);
  1196. if (customData.type === 'voice') {
  1197. return 3; // 语音消息
  1198. }
  1199. } catch (e) {
  1200. console.error('解析自定义消息类型失败:', e);
  1201. }
  1202. }
  1203. return typeMap[timMessage.type] || 1;
  1204. },
  1205. /**
  1206. * 获取消息内容
  1207. */
  1208. getMessageContent(timMessage) {
  1209. switch (timMessage.type) {
  1210. case 'TIMTextElem':
  1211. return timMessage.payload.text || '';
  1212. case 'TIMImageElem':
  1213. return '[图片]';
  1214. case 'TIMSoundElem':
  1215. return '[语音]';
  1216. case 'TIMVideoFileElem':
  1217. return '[视频]';
  1218. case 'TIMFileElem':
  1219. return '[文件]';
  1220. case 'TIMCustomElem':
  1221. // 处理自定义消息(我们的语音消息)
  1222. try {
  1223. const customData = JSON.parse(timMessage.payload.data);
  1224. if (customData.type === 'voice') {
  1225. return '[语音]';
  1226. }
  1227. } catch (e) {
  1228. console.error('解析自定义消息内容失败:', e);
  1229. }
  1230. return '[未知消息]';
  1231. default:
  1232. return '[未知消息]';
  1233. }
  1234. },
  1235. /**
  1236. * 滚动到底部
  1237. */
  1238. scrollToBottom() {
  1239. this.$nextTick(() => {
  1240. const lastIndex = this.messages.length - 1;
  1241. this.scrollToView = 'msg-' + lastIndex;
  1242. });
  1243. },
  1244. /**
  1245. * 判断是否显示时间分隔线
  1246. */
  1247. shouldShowTime(msg, index) {
  1248. if (index === 0) return true;
  1249. const prevMsg = this.messages[index - 1];
  1250. const timeDiff = new Date(msg.sendTime) - new Date(prevMsg.sendTime);
  1251. // 超过5分钟显示时间
  1252. return timeDiff > 5 * 60 * 1000;
  1253. },
  1254. /**
  1255. * 格式化消息时间(用于时间分隔线)
  1256. */
  1257. formatMessageTime(time) {
  1258. const date = new Date(time);
  1259. const now = new Date();
  1260. const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  1261. const yesterday = new Date(today - 86400000);
  1262. // 今天
  1263. if (date >= today) {
  1264. return date.toLocaleTimeString('zh-CN', {
  1265. hour: '2-digit',
  1266. minute: '2-digit'
  1267. });
  1268. }
  1269. // 昨天
  1270. if (date >= yesterday) {
  1271. return '昨天 ' + date.toLocaleTimeString('zh-CN', {
  1272. hour: '2-digit',
  1273. minute: '2-digit'
  1274. });
  1275. }
  1276. // 本周
  1277. if (date > new Date(now - 7 * 86400000)) {
  1278. const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  1279. return days[date.getDay()] + ' ' + date.toLocaleTimeString('zh-CN', {
  1280. hour: '2-digit',
  1281. minute: '2-digit'
  1282. });
  1283. }
  1284. // 更早
  1285. return date.toLocaleString('zh-CN', {
  1286. month: '2-digit',
  1287. day: '2-digit',
  1288. hour: '2-digit',
  1289. minute: '2-digit'
  1290. });
  1291. },
  1292. /**
  1293. * 格式化时间(消息状态用)
  1294. */
  1295. formatTime(time) {
  1296. const date = new Date(time);
  1297. const now = new Date();
  1298. const diff = now - date;
  1299. if (diff < 60000) {
  1300. return '刚刚';
  1301. } else if (diff < 3600000) {
  1302. return Math.floor(diff / 60000) + '分钟前';
  1303. } else if (diff < 86400000) {
  1304. return Math.floor(diff / 3600000) + '小时前';
  1305. } else {
  1306. return date.toLocaleString('zh-CN', {
  1307. month: '2-digit',
  1308. day: '2-digit',
  1309. hour: '2-digit',
  1310. minute: '2-digit'
  1311. });
  1312. }
  1313. },
  1314. /**
  1315. * 预览图片
  1316. */
  1317. previewImage(url) {
  1318. uni.previewImage({
  1319. urls: [url],
  1320. current: url
  1321. });
  1322. },
  1323. /**
  1324. * 返回
  1325. */
  1326. goBack() {
  1327. uni.navigateBack({
  1328. success: () => {
  1329. // 通知消息列表页面刷新
  1330. uni.$emit('refreshConversations');
  1331. }
  1332. });
  1333. },
  1334. /**
  1335. * 显示消息操作菜单
  1336. */
  1337. showMessageMenu(msg, index) {
  1338. this.selectedMessage = msg;
  1339. this.selectedMessageIndex = index;
  1340. this.showMessageAction = true;
  1341. // 计算菜单位置
  1342. uni.createSelectorQuery().select('.message-item').boundingClientRect(rect => {
  1343. if (rect) {
  1344. this.menuTop = rect.top + rect.height;
  1345. }
  1346. }).exec();
  1347. },
  1348. /**
  1349. * 隐藏消息操作菜单
  1350. */
  1351. hideMessageMenu() {
  1352. this.showMessageAction = false;
  1353. this.selectedMessage = null;
  1354. this.selectedMessageIndex = -1;
  1355. },
  1356. /**
  1357. * 复制消息
  1358. */
  1359. copyMessage() {
  1360. if (!this.selectedMessage || this.selectedMessage.messageType !== 1) {
  1361. return;
  1362. }
  1363. uni.setClipboardData({
  1364. data: this.selectedMessage.content,
  1365. success: () => {
  1366. uni.showToast({
  1367. title: '已复制',
  1368. icon: 'success'
  1369. });
  1370. }
  1371. });
  1372. this.hideMessageMenu();
  1373. },
  1374. /**
  1375. * 判断是否可以撤回
  1376. */
  1377. canRecall(msg) {
  1378. const diff = Date.now() - new Date(msg.sendTime).getTime();
  1379. return diff < 2 * 60 * 1000; // 2分钟内可撤回
  1380. },
  1381. /**
  1382. * 撤回消息
  1383. */
  1384. async recallMessage() {
  1385. if (!this.selectedMessage) {
  1386. return;
  1387. }
  1388. try {
  1389. // 查找TIM消息对象
  1390. const timMessage = await timManager.tim.findMessage(this.selectedMessage.messageId);
  1391. if (timMessage) {
  1392. await timManager.revokeMessage(timMessage);
  1393. // 更新本地消息状态
  1394. this.selectedMessage.isRecalled = true;
  1395. this.selectedMessage.content = '你撤回了一条消息';
  1396. uni.showToast({
  1397. title: '已撤回',
  1398. icon: 'success'
  1399. });
  1400. }
  1401. } catch (error) {
  1402. console.error('撤回失败:', error);
  1403. uni.showToast({
  1404. title: '撤回失败',
  1405. icon: 'none'
  1406. });
  1407. }
  1408. this.hideMessageMenu();
  1409. },
  1410. /**
  1411. * 删除消息
  1412. */
  1413. deleteMessage() {
  1414. if (!this.selectedMessage) {
  1415. return;
  1416. }
  1417. uni.showModal({
  1418. title: '确认删除',
  1419. content: '确定要删除这条消息吗?',
  1420. success: (res) => {
  1421. if (res.confirm) {
  1422. // 从列表中删除
  1423. this.messages.splice(this.selectedMessageIndex, 1);
  1424. uni.showToast({
  1425. title: '已删除',
  1426. icon: 'success'
  1427. });
  1428. }
  1429. }
  1430. });
  1431. this.hideMessageMenu();
  1432. },
  1433. /**
  1434. * 处理消息点击
  1435. */
  1436. handleMessageClick(msg) {
  1437. // 如果是发送失败的消息,提示重试
  1438. if (msg.sendStatus === 4) {
  1439. // 检查失败原因
  1440. if (msg.failReason === 'audit_failed') {
  1441. // 审核失败的消息不允许重试
  1442. uni.showModal({
  1443. title: '无法重试',
  1444. content: '该消息包含敏感信息,无法发送',
  1445. showCancel: false,
  1446. confirmText: '知道了'
  1447. });
  1448. return;
  1449. }
  1450. // 其他原因失败的消息可以重试
  1451. uni.showModal({
  1452. title: '发送失败',
  1453. content: '消息发送失败,是否重试?',
  1454. success: (res) => {
  1455. if (res.confirm) {
  1456. this.retryMessage(msg);
  1457. }
  1458. }
  1459. });
  1460. }
  1461. },
  1462. /**
  1463. * 重试发送消息
  1464. */
  1465. async retryMessage(msg) {
  1466. if (msg.messageType !== 1) {
  1467. uni.showToast({ title: '暂不支持重发该类型消息', icon: 'none' });
  1468. return;
  1469. }
  1470. // 双重保护:检查是否是审核失败的消息
  1471. if (msg.failReason === 'audit_failed') {
  1472. uni.showToast({
  1473. title: '该消息包含敏感信息,无法重试',
  1474. icon: 'none',
  1475. duration: 2000
  1476. });
  1477. return;
  1478. }
  1479. const isBlocked = await this.checkIsBlockedByTarget();
  1480. if (isBlocked) {
  1481. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1482. if (index > -1) {
  1483. this.$set(this.messages[index], 'sendStatus', 4);
  1484. }
  1485. uni.showToast({ title: '对方已拉黑你,无法发送', icon: 'none' });
  1486. return;
  1487. }
  1488. try {
  1489. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1490. if (index > -1) {
  1491. this.$set(this.messages[index], 'sendStatus', 1); // 发送中
  1492. }
  1493. const message = await timManager.sendTextMessage(this.targetUserId, msg.content);
  1494. // 更新消息状态为已送达
  1495. if (index > -1) {
  1496. const convertedMsg = this.convertMessage(message);
  1497. convertedMsg.sendStatus = 2; // 强制已送达
  1498. convertedMsg.messageId = msg.messageId; // 保持原ID
  1499. this.$set(this.messages, index, convertedMsg);
  1500. }
  1501. console.log('✅ 消息重发成功');
  1502. this.syncMessageToMySQL(message);
  1503. } catch (error) {
  1504. console.error('❌ 消息重发失败:', error);
  1505. const index = this.messages.findIndex(m => m.messageId === msg.messageId);
  1506. if (index > -1) {
  1507. this.$set(this.messages[index], 'sendStatus', 4);
  1508. }
  1509. uni.showToast({ title: '发送失败', icon: 'none' });
  1510. }
  1511. },
  1512. // 其他功能方法
  1513. switchInputType() {
  1514. this.inputType = this.inputType === 'text' ? 'voice' : 'text';
  1515. },
  1516. /**
  1517. * 开始录音
  1518. */
  1519. startVoiceRecord(e) {
  1520. console.log('🎤 [按住说话] startVoiceRecord 方法被调用');
  1521. // 记录触摸起始位置
  1522. this.voiceTouchStartY = e.touches[0].clientY;
  1523. this.voiceCanceling = false;
  1524. // 检查是否被拉黑
  1525. if (this.isBlockedByTarget) {
  1526. uni.showToast({
  1527. title: '对方已将你拉黑',
  1528. icon: 'none'
  1529. });
  1530. return;
  1531. }
  1532. // 🔥 每次都重新获取录音管理器(确保状态干净)
  1533. console.log('📱 获取录音管理器');
  1534. this.recorderManager = uni.getRecorderManager();
  1535. // 🔥 每次录音前都重新注册回调(确保回调有效)
  1536. console.log('📝 注册录音回调');
  1537. // 录音开始回调(可能延迟或不触发,所以状态已在 start() 后立即设置)
  1538. this.recorderManager.onStart(() => {
  1539. console.log('✅ 录音开始回调触发(延迟触发)');
  1540. });
  1541. // 录音结束回调
  1542. this.recorderManager.onStop((res) => {
  1543. console.log('🎤 录音结束:', res, ', voiceCanceling:', this.voiceCanceling);
  1544. this.isRecording = false;
  1545. this.showVoiceRecording = false;
  1546. // 清除计时器
  1547. if (this.voiceRecordingTimer) {
  1548. clearInterval(this.voiceRecordingTimer);
  1549. this.voiceRecordingTimer = null;
  1550. }
  1551. // 如果是取消状态,不发送
  1552. if (this.voiceCanceling) {
  1553. console.log('❌ 录音已取消,不发送');
  1554. this.voiceCanceling = false;
  1555. return;
  1556. }
  1557. this.voiceTempPath = res.tempFilePath;
  1558. this.voiceDuration = Math.floor(res.duration / 1000); // 转换为秒
  1559. console.log(' - 文件路径:', this.voiceTempPath);
  1560. console.log(' - 时长:', this.voiceDuration, '秒');
  1561. // 时长验证
  1562. if (this.voiceDuration < 1) {
  1563. uni.showToast({
  1564. title: '录音时间太短',
  1565. icon: 'none'
  1566. });
  1567. return;
  1568. }
  1569. if (this.voiceDuration > 60) {
  1570. uni.showToast({
  1571. title: '录音时间不能超过60秒',
  1572. icon: 'none'
  1573. });
  1574. return;
  1575. }
  1576. // 发送语音消息
  1577. this.sendVoiceMessage();
  1578. });
  1579. // 录音错误回调
  1580. this.recorderManager.onError((err) => {
  1581. console.error('❌ 录音错误:', err);
  1582. // 立即清理录音状态和界面
  1583. this.isRecording = false;
  1584. this.showVoiceRecording = false;
  1585. this.voiceCanceling = true;
  1586. // 清除计时器
  1587. if (this.voiceRecordingTimer) {
  1588. clearInterval(this.voiceRecordingTimer);
  1589. this.voiceRecordingTimer = null;
  1590. }
  1591. // 如果是权限错误,不显示任何提示(用户会看到系统权限弹窗)
  1592. // 其他错误才显示提示
  1593. if (err.errCode !== 'authorize' && err.errMsg && !err.errMsg.includes('authorize')) {
  1594. uni.showToast({
  1595. title: '录音失败',
  1596. icon: 'none'
  1597. });
  1598. }
  1599. console.log('✅ 已清理录音状态,隐藏录音界面');
  1600. });
  1601. // 🔥 先检查录音权限
  1602. console.log('🔐 检查录音权限...');
  1603. uni.getSetting({
  1604. success: (res) => {
  1605. console.log('📋 权限设置:', res.authSetting);
  1606. if (res.authSetting['scope.record'] === false) {
  1607. console.warn('⚠️ 录音权限被拒绝');
  1608. uni.showModal({
  1609. title: '需要录音权限',
  1610. content: '请在设置中开启录音权限',
  1611. success: (modalRes) => {
  1612. if (modalRes.confirm) {
  1613. uni.openSetting();
  1614. }
  1615. }
  1616. });
  1617. return;
  1618. }
  1619. }
  1620. });
  1621. // 开始录音
  1622. console.log('🎙️ 调用 recorderManager.start()');
  1623. try {
  1624. this.recorderManager.start({
  1625. format: 'mp3',
  1626. sampleRate: 16000,
  1627. numberOfChannels: 1,
  1628. encodeBitRate: 48000
  1629. });
  1630. console.log('✅ recorderManager.start() 调用成功');
  1631. // 🔥 立即显示录音界面(不等待 onStart 回调)
  1632. // 因为微信小程序的 onStart 可能延迟或不触发
  1633. this.isRecording = true;
  1634. this.showVoiceRecording = true;
  1635. this.voiceStartTime = Date.now();
  1636. this.voiceRecordingTime = 0;
  1637. this.voiceVolume = 0.3;
  1638. console.log('🎬 立即显示录音界面');
  1639. console.log(' - isRecording:', this.isRecording);
  1640. console.log(' - showVoiceRecording:', this.showVoiceRecording);
  1641. // 启动计时器
  1642. let volumeDirection = 1;
  1643. let currentVolume = 0.3;
  1644. this.voiceRecordingTimer = setInterval(() => {
  1645. this.voiceRecordingTime = Math.floor((Date.now() - this.voiceStartTime) / 1000);
  1646. // 检查是否达到60秒,自动停止录音
  1647. if (this.voiceRecordingTime >= 60) {
  1648. console.log('⏰ 录音时长达到60秒,自动停止');
  1649. clearInterval(this.voiceRecordingTimer);
  1650. this.voiceRecordingTimer = null;
  1651. this.voiceCanceling = false;
  1652. if (this.recorderManager) {
  1653. this.recorderManager.stop();
  1654. }
  1655. return;
  1656. }
  1657. // 模拟音量波动
  1658. if (Math.random() > 0.2) {
  1659. currentVolume += volumeDirection * (0.1 + Math.random() * 0.2);
  1660. if (currentVolume > 1.0) {
  1661. currentVolume = 1.0;
  1662. volumeDirection = -1;
  1663. } else if (currentVolume < 0.4) {
  1664. currentVolume = 0.4;
  1665. volumeDirection = 1;
  1666. }
  1667. this.voiceVolume = currentVolume;
  1668. } else {
  1669. this.voiceVolume = Math.max(0.2, this.voiceVolume * 0.8);
  1670. }
  1671. }, 100);
  1672. } catch (err) {
  1673. console.error('❌ recorderManager.start() 调用失败:', err);
  1674. this.isRecording = false;
  1675. this.showVoiceRecording = false;
  1676. }
  1677. },
  1678. /**
  1679. * 停止录音
  1680. */
  1681. stopVoiceRecord() {
  1682. console.log('🎤 [松开] stopVoiceRecord 方法被调用, isRecording:', this.isRecording, ', voiceCanceling:', this.voiceCanceling);
  1683. // 清除计时器
  1684. if (this.voiceRecordingTimer) {
  1685. clearInterval(this.voiceRecordingTimer);
  1686. this.voiceRecordingTimer = null;
  1687. }
  1688. // 如果正在取消,则取消录音
  1689. if (this.voiceCanceling) {
  1690. console.log('🚫 检测到取消状态,调用 cancelVoiceRecord');
  1691. this.cancelVoiceRecord();
  1692. return;
  1693. }
  1694. if (this.isRecording && this.recorderManager) {
  1695. const duration = Date.now() - this.voiceStartTime;
  1696. // 录音时间太短
  1697. if (duration < 1000) {
  1698. this.recorderManager.stop();
  1699. this.isRecording = false;
  1700. this.showVoiceRecording = false;
  1701. uni.showToast({
  1702. title: '录音时间太短',
  1703. icon: 'none'
  1704. });
  1705. return;
  1706. }
  1707. this.recorderManager.stop();
  1708. }
  1709. },
  1710. /**
  1711. * 触摸移动 - 检测上滑取消
  1712. */
  1713. onVoiceTouchMove(e) {
  1714. if (!this.isRecording) return;
  1715. const currentY = e.touches[0].clientY;
  1716. const deltaY = this.voiceTouchStartY - currentY;
  1717. // 上滑超过100px,显示取消提示
  1718. if (deltaY > 100) {
  1719. this.voiceCanceling = true;
  1720. console.log('⬆️ 上滑取消录音');
  1721. } else {
  1722. this.voiceCanceling = false;
  1723. }
  1724. },
  1725. /**
  1726. * 取消录音
  1727. */
  1728. cancelVoiceRecord() {
  1729. console.log('❌ 取消录音, voiceCanceling:', this.voiceCanceling);
  1730. // 清除计时器
  1731. if (this.voiceRecordingTimer) {
  1732. clearInterval(this.voiceRecordingTimer);
  1733. this.voiceRecordingTimer = null;
  1734. }
  1735. // 先设置取消状态,再停止录音
  1736. // 这样onStop回调中能正确判断
  1737. if (!this.voiceCanceling) {
  1738. this.voiceCanceling = true;
  1739. }
  1740. if (this.recorderManager && this.isRecording) {
  1741. this.recorderManager.stop(); // 这会触发onStop回调
  1742. } else {
  1743. // 如果没有在录音,直接重置状态
  1744. this.isRecording = false;
  1745. this.showVoiceRecording = false;
  1746. this.voiceCanceling = false;
  1747. }
  1748. uni.showToast({
  1749. title: '已取消录音',
  1750. icon: 'none'
  1751. });
  1752. },
  1753. /**
  1754. * 发送语音消息
  1755. */
  1756. async sendVoiceMessage() {
  1757. // 检查是否被拉黑
  1758. const isBlocked = await this.checkIsBlockedByTarget();
  1759. if (isBlocked) {
  1760. uni.showToast({
  1761. title: '你已被对方拉黑,无法发送消息',
  1762. icon: 'none'
  1763. });
  1764. return;
  1765. }
  1766. try {
  1767. uni.showLoading({ title: '上传中...' });
  1768. // 第一步:上传语音文件到MinIO
  1769. const uploadResult = await this.uploadVoiceToMinIO();
  1770. if (!uploadResult.success) {
  1771. throw new Error(uploadResult.message || '上传失败');
  1772. }
  1773. console.log('✅ 语音文件上传成功:', uploadResult.fileUrl);
  1774. uni.showLoading({ title: '发送中...' });
  1775. // 第二步:通过腾讯IM发送语音消息(携带MinIO URL)
  1776. const message = await timManager.sendVoiceMessage(
  1777. this.targetUserId,
  1778. uploadResult.fileUrl,
  1779. this.voiceDuration,
  1780. uploadResult.fileSize
  1781. );
  1782. // 添加到消息列表
  1783. this.messages.push(this.convertMessage(message));
  1784. this.scrollToBottom();
  1785. uni.hideLoading();
  1786. console.log('✅ 语音消息发送成功');
  1787. // 同步到MySQL
  1788. this.syncMessageToMySQL(message);
  1789. // 更新消息计数
  1790. if (!this.isVip) {
  1791. await this.updateMessageCount();
  1792. }
  1793. } catch (error) {
  1794. uni.hideLoading();
  1795. console.error('❌ 语音消息发送失败:', error);
  1796. uni.showToast({
  1797. title: '发送失败: ' + error.message,
  1798. icon: 'none'
  1799. });
  1800. }
  1801. },
  1802. /**
  1803. * 上传语音文件到MinIO
  1804. */
  1805. async uploadVoiceToMinIO() {
  1806. try {
  1807. console.log('📤 开始上传语音文件到MinIO...');
  1808. console.log(' - 文件路径:', this.voiceTempPath);
  1809. console.log(' - 时长:', this.voiceDuration, '秒');
  1810. // 使用uni.uploadFile上传到后端MinIO接口
  1811. const [err, res] = await uni.uploadFile({
  1812. url: 'http://localhost:8083/api/voice/upload',
  1813. filePath: this.voiceTempPath,
  1814. name: 'file',
  1815. header: {
  1816. 'Content-Type': 'multipart/form-data'
  1817. }
  1818. });
  1819. if (err) {
  1820. console.error('❌ 上传请求失败:', err);
  1821. return {
  1822. success: false,
  1823. message: '网络请求失败'
  1824. };
  1825. }
  1826. // 解析响应
  1827. const result = JSON.parse(res.data);
  1828. console.log('📥 MinIO上传响应:', result);
  1829. if (result.success) {
  1830. return {
  1831. success: true,
  1832. fileUrl: result.fileUrl,
  1833. fileSize: result.fileSize
  1834. };
  1835. } else {
  1836. return {
  1837. success: false,
  1838. message: result.message || '上传失败'
  1839. };
  1840. }
  1841. } catch (error) {
  1842. console.error('❌ 上传语音文件失败:', error);
  1843. return {
  1844. success: false,
  1845. message: error.message || '上传异常'
  1846. };
  1847. }
  1848. },
  1849. insertEmoji(emoji) {
  1850. this.inputText += emoji;
  1851. this.showEmojiPanel = false;
  1852. },
  1853. chooseVideo() {
  1854. uni.showToast({
  1855. title: '视频功能开发中',
  1856. icon: 'none'
  1857. });
  1858. },
  1859. chooseFile() {
  1860. uni.showToast({
  1861. title: '文件功能开发中',
  1862. icon: 'none'
  1863. });
  1864. },
  1865. /**
  1866. * 切换语音播放/暂停
  1867. */
  1868. toggleVoicePlay(msg) {
  1869. // 如果正在播放这条语音,则暂停
  1870. if (this.playingVoiceId === msg.messageId) {
  1871. this.pauseVoice(msg);
  1872. } else {
  1873. // 否则开始播放
  1874. this.playVoice(msg);
  1875. }
  1876. },
  1877. /**
  1878. * 播放语音
  1879. */
  1880. playVoice(msg) {
  1881. console.log('📢 [播放语音] 开始 - messageId:', msg.messageId);
  1882. if (!msg.mediaUrl) {
  1883. // 如果是TIM消息,从payload中获取URL
  1884. const audioUrl = msg.payload?.url || msg.payload?.remoteAudioUrl;
  1885. if (!audioUrl) {
  1886. uni.showToast({
  1887. title: '语音文件不存在',
  1888. icon: 'none'
  1889. });
  1890. return;
  1891. }
  1892. msg.mediaUrl = audioUrl;
  1893. }
  1894. // 如果有其他语音正在播放,先停止
  1895. if (this.currentAudioContext) {
  1896. console.log('⏹️ 停止之前的语音');
  1897. this.currentAudioContext.stop();
  1898. this.currentAudioContext.destroy();
  1899. this.currentAudioContext = null;
  1900. }
  1901. // 清除暂停状态
  1902. this.pausedVoiceId = null;
  1903. // 设置当前播放的语音ID,触发动画
  1904. this.playingVoiceId = msg.messageId;
  1905. console.log('🎬 [动画开始] playingVoiceId =', this.playingVoiceId);
  1906. // 创建音频上下文
  1907. const innerAudioContext = uni.createInnerAudioContext();
  1908. innerAudioContext.src = msg.mediaUrl;
  1909. innerAudioContext.loop = false; // 不循环播放
  1910. this.currentAudioContext = innerAudioContext;
  1911. innerAudioContext.onPlay(() => {
  1912. console.log('🔊 开始播放语音');
  1913. });
  1914. innerAudioContext.onEnded(() => {
  1915. console.log('✅ 语音播放完成');
  1916. this.playingVoiceId = null; // 停止动画
  1917. this.pausedVoiceId = null;
  1918. this.currentAudioContext = null;
  1919. console.log('🛑 [动画停止] playingVoiceId =', this.playingVoiceId);
  1920. innerAudioContext.destroy();
  1921. });
  1922. innerAudioContext.onError((err) => {
  1923. console.error('❌ 语音播放失败:', err);
  1924. this.playingVoiceId = null; // 停止动画
  1925. this.pausedVoiceId = null;
  1926. this.currentAudioContext = null;
  1927. console.log('🛑 [动画停止-错误] playingVoiceId =', this.playingVoiceId);
  1928. uni.showToast({
  1929. title: '播放失败',
  1930. icon: 'none'
  1931. });
  1932. innerAudioContext.destroy();
  1933. });
  1934. innerAudioContext.play();
  1935. },
  1936. /**
  1937. * 暂停语音
  1938. */
  1939. pauseVoice(msg) {
  1940. if (this.currentAudioContext) {
  1941. this.currentAudioContext.pause();
  1942. this.playingVoiceId = null; // 停止动画
  1943. this.pausedVoiceId = msg.messageId; // 设置暂停状态
  1944. console.log('⏸️ [暂停] playingVoiceId =', this.playingVoiceId, ', pausedVoiceId =', this.pausedVoiceId);
  1945. }
  1946. },
  1947. /**
  1948. * 继续播放语音
  1949. */
  1950. resumeVoice() {
  1951. if (this.currentAudioContext && this.pausedVoiceId) {
  1952. this.currentAudioContext.play();
  1953. this.playingVoiceId = this.pausedVoiceId; // 恢复动画
  1954. const resumedId = this.pausedVoiceId;
  1955. this.pausedVoiceId = null; // 清除暂停状态
  1956. console.log('▶️ [继续播放] playingVoiceId =', this.playingVoiceId, ', pausedVoiceId =', this.pausedVoiceId);
  1957. }
  1958. },
  1959. showMoreOptions() {
  1960. this.showMoreOptionsModal = true;
  1961. },
  1962. closeMoreOptions() {
  1963. this.showMoreOptionsModal = false;
  1964. },
  1965. /**
  1966. * 查看用户资料(跳转到原有more页面)
  1967. */
  1968. goToUserProfile() {
  1969. this.closeMoreOptions();
  1970. uni.navigateTo({
  1971. url: `/pages/message/more?userid=${this.targetUserId}`,
  1972. fail: (err) => {
  1973. console.error('跳转失败:', err);
  1974. uni.showToast({
  1975. title: '页面不存在',
  1976. icon: 'none'
  1977. });
  1978. }
  1979. });
  1980. },
  1981. /**
  1982. * 显示拉黑确认弹窗
  1983. */
  1984. blockFriend() {
  1985. this.closeMoreOptions();
  1986. this.showBlockConfirmModal = true;
  1987. },
  1988. /**
  1989. * 关闭拉黑确认弹窗
  1990. */
  1991. closeBlockConfirm() {
  1992. this.showBlockConfirmModal = false;
  1993. },
  1994. /**
  1995. * 从后端获取VIP状态和今日剩余发送次数
  1996. */
  1997. async getUserMessageLimit() {
  1998. // 只要一方是红娘(ID 以 m_ 开头),就不做每日5条限制,直接视为无限制
  1999. const isMatchmakerChat = String(this.userId).startsWith('m_') || String(this.targetUserId).startsWith('m_');
  2000. if (isMatchmakerChat || this.fromMatchmaker) {
  2001. this.hasMessageLimit = false;
  2002. this.isVip = true;
  2003. this.remainingCount = 999;
  2004. console.log('✅ 红娘聊天模式:无消息限制(跳过 getUserMessageLimit 接口)');
  2005. return;
  2006. }
  2007. try {
  2008. const [err, res] = await uni.request({
  2009. url: 'http://localhost:1004/api/chat/getUserMessageLimit',
  2010. method: 'GET',
  2011. data: {
  2012. userId: this.userId ,// 已在onLoad中初始化的当前用户ID
  2013. targetUserId: this.targetUserId
  2014. },
  2015. header: {
  2016. 'Content-Type': 'application/json'
  2017. }
  2018. });
  2019. if (err) throw new Error('网络请求失败');
  2020. if (res.data.code !== 200) throw new Error(res.data.message || '获取限制信息失败');
  2021. const { isVip, remainingCount, hasMessageLimit } = res.data.data;
  2022. this.isVip = isVip;
  2023. this.remainingCount = remainingCount;
  2024. this.hasMessageLimit = hasMessageLimit;
  2025. console.log('✅ 用户消息限制信息:', { isVip, remainingCount, hasMessageLimit });
  2026. } catch (error) {
  2027. console.error('❌ 获取消息限制失败:', error);
  2028. // 异常降级:默认非VIP,剩余5次
  2029. this.isVip = false;
  2030. this.remainingCount = 5;
  2031. this.hasMessageLimit = true;
  2032. }
  2033. },
  2034. /**
  2035. * 发送成功后,更新后端计数并同步前端剩余次数
  2036. */
  2037. async updateMessageCount() {
  2038. try {
  2039. const [err, res] = await uni.request({
  2040. url: 'http://localhost:8083/api/chat/updateMessageCount',
  2041. method: 'get',
  2042. data: {
  2043. userId: this.userId ,// 已在onLoad中初始化的当前用户ID
  2044. targetUserId: this.targetUserId
  2045. },
  2046. header: {
  2047. 'Content-Type': 'application/json'
  2048. }
  2049. });
  2050. if (err) throw new Error('更新计数失败');
  2051. if (res.data.code === 200) {
  2052. this.remainingCount = res.data.data.remainingCount; // 同步后端返回的剩余次数
  2053. }
  2054. } catch (error) {
  2055. console.error('❌ 更新发送次数失败:', error);
  2056. // 前端本地降级:避免影响用户体验,本地暂减1(刷新页面后同步真实数据)
  2057. if (this.remainingCount > 0) {
  2058. this.remainingCount--;
  2059. }
  2060. }
  2061. },
  2062. /**
  2063. * 确认拉黑好友
  2064. */
  2065. async confirmBlockFriend() {
  2066. try {
  2067. uni.showLoading({
  2068. title: '处理中...'
  2069. });
  2070. // 调用后端拉黑接口(根据实际接口调整)
  2071. const [err, res] = await uni.request({
  2072. url: 'http://localhost:8083/api/chatfriend/block',
  2073. method: 'POST',
  2074. data: {
  2075. userId: this.userId,
  2076. targetUserId: this.targetUserId,
  2077. targetUserName: this.targetUserName,
  2078. targetUserAvatar: this.targetUserAvatar
  2079. },
  2080. header: {
  2081. 'Content-Type': 'application/json',
  2082. // 'Authorization': 'Bearer ' + uni.getStorageSync('token')
  2083. }
  2084. });
  2085. uni.hideLoading();
  2086. if (err) throw new Error('网络请求失败');
  2087. if (res.data && res.data.code === 200) {
  2088. uni.showToast({ title: '拉黑成功', icon: 'success' });
  2089. this.closeBlockConfirm();
  2090. // 触发拉黑列表更新事件,通知消息页面实时刷新
  2091. uni.$emit('blacklistUpdated');
  2092. // 拉黑成功后立即返回消息列表页面(优化体验)
  2093. setTimeout(() => {
  2094. uni.navigateBack({
  2095. delta: 1,
  2096. success: () => {
  2097. // 返回成功后再次触发一次刷新,确保万无一失
  2098. uni.$emit('blacklistUpdated');
  2099. }
  2100. });
  2101. }, 1500);
  2102. } else {
  2103. throw new Error(res.data?.message || '拉黑失败');
  2104. }
  2105. } catch (error) {
  2106. console.error('拉黑失败:', error);
  2107. uni.showToast({ title: error.message || '拉黑失败', icon: 'none' });
  2108. }
  2109. },
  2110. /**
  2111. * 初始化在线状态监听(WebSocket 实时推送 + HTTP 轮询)
  2112. */
  2113. async initOnlineStatusPolling() {
  2114. console.log('🔄 初始化在线状态监听(WebSocket + HTTP)');
  2115. const timPresenceManager = require('@/utils/tim-presence-manager.js').default;
  2116. // 1. 立即查询一次
  2117. await this.checkOnlineStatus();
  2118. // 2. 监听 WebSocket 实时推送(实时性强)
  2119. this.onlineStatusCallback = (status) => {
  2120. console.log(`⚡ 实时收到用户 ${this.targetUserId} 状态变更: ${status}`);
  2121. this.isTargetOnline = (status === 'online');
  2122. };
  2123. timPresenceManager.onStatusChange(this.targetUserId, this.onlineStatusCallback);
  2124. // 3. 启动 HTTP 轮询作为补充(30秒间隔)
  2125. this.onlineStatusTimer = setInterval(() => {
  2126. this.checkOnlineStatus();
  2127. }, 30000);
  2128. console.log('✅ 在线状态监听已启动(WebSocket 实时 + HTTP 轮询)');
  2129. },
  2130. /**
  2131. * 查询在线状态
  2132. */
  2133. async checkOnlineStatus() {
  2134. try {
  2135. const [err, res] = await uni.request({
  2136. url: 'http://localhost:8083/api/online/checkStatus',
  2137. method: 'GET',
  2138. data: {
  2139. userId: this.targetUserId
  2140. }
  2141. });
  2142. if (!err && res.data && res.data.code === 200) {
  2143. this.isTargetOnline = res.data.data.online || false;
  2144. console.log(`� 用户 ${this.targetUserId} 在线状态:`, this.isTargetOnline);
  2145. }
  2146. } catch (error) {
  2147. console.error('❌ 查询在线状态失败:', error);
  2148. }
  2149. }
  2150. },
  2151. /**
  2152. * 页面卸载时清理
  2153. */
  2154. onUnload() {
  2155. console.log('=== 聊天页面卸载 ===');
  2156. // 清理在线状态轮询
  2157. if (this.onlineStatusTimer) {
  2158. clearInterval(this.onlineStatusTimer);
  2159. this.onlineStatusTimer = null;
  2160. console.log('✅ 已停止在线状态轮询');
  2161. }
  2162. // 清理 WebSocket 监听
  2163. if (this.onlineStatusCallback) {
  2164. const timPresenceManager = require('@/utils/tim-presence-manager.js').default;
  2165. timPresenceManager.offStatusChange(this.targetUserId, this.onlineStatusCallback);
  2166. console.log('✅ 已清理 WebSocket 监听');
  2167. }
  2168. // 清理已读回执监听
  2169. if (this.handleMessageReadByPeer) {
  2170. timManager.offMessageRead(this.handleMessageReadByPeer);
  2171. console.log('✅ 已通过 timManager 清理已读回执监听');
  2172. }
  2173. // 清理新消息监听
  2174. if (this.handleNewMessage) {
  2175. timManager.offMessage(this.handleNewMessage);
  2176. console.log('✅ 已清理新消息监听');
  2177. }
  2178. }
  2179. };
  2180. </script>
  2181. <style scoped>
  2182. /* 弹窗遮罩 */
  2183. .modal-mask {
  2184. position: fixed;
  2185. top: 0;
  2186. left: 0;
  2187. right: 0;
  2188. bottom: 0;
  2189. background-color: rgba(0, 0, 0, 0.5);
  2190. z-index: 10000;
  2191. display: flex;
  2192. align-items: center;
  2193. justify-content: center;
  2194. }
  2195. /* 更多选项弹窗内容 */
  2196. .modal-content {
  2197. width: 70%;
  2198. background-color: #fff;
  2199. border-radius: 20rpx;
  2200. overflow: hidden;
  2201. }
  2202. .modal-header {
  2203. padding: 30rpx;
  2204. text-align: center;
  2205. border-bottom: 1px solid #eee;
  2206. }
  2207. .modal-title {
  2208. font-size: 32rpx;
  2209. font-weight: bold;
  2210. display: block;
  2211. }
  2212. .modal-subtitle {
  2213. font-size: 24rpx;
  2214. color: #999;
  2215. display: block;
  2216. margin-top: 10rpx;
  2217. }
  2218. .modal-body {
  2219. padding: 20rpx 0;
  2220. }
  2221. .modal-item {
  2222. display: flex;
  2223. align-items: center;
  2224. padding: 25rpx 40rpx;
  2225. font-size: 30rpx;
  2226. }
  2227. .modal-item.danger {
  2228. color: #fa5151;
  2229. }
  2230. .item-icon {
  2231. font-size: 32rpx;
  2232. margin-right: 20rpx;
  2233. }
  2234. .modal-footer {
  2235. padding: 20rpx;
  2236. border-top: 1px solid #eee;
  2237. }
  2238. .modal-close-btn {
  2239. width: 94%;
  2240. background-color: #f5f5f5;
  2241. border: none;
  2242. border-radius: 10rpx;
  2243. padding: 20rpx;
  2244. font-size: 30rpx;
  2245. }
  2246. /* 确认弹窗样式 */
  2247. .confirm-modal {
  2248. width: 60%;
  2249. background-color: #fff;
  2250. border-radius: 20rpx;
  2251. padding: 40rpx;
  2252. text-align: center;
  2253. }
  2254. .confirm-title {
  2255. font-size: 32rpx;
  2256. font-weight: bold;
  2257. margin-bottom: 30rpx;
  2258. }
  2259. .confirm-content {
  2260. font-size: 28rpx;
  2261. color: #666;
  2262. margin-bottom: 40rpx;
  2263. line-height: 1.5;
  2264. }
  2265. .confirm-buttons {
  2266. display: flex;
  2267. justify-content: space-between;
  2268. }
  2269. .confirm-btn {
  2270. flex: 1;
  2271. margin: 0 10rpx;
  2272. padding: 20rpx;
  2273. border-radius: 10rpx;
  2274. border: none;
  2275. font-size: 28rpx;
  2276. }
  2277. .confirm-btn.cancel {
  2278. background-color: #f5f5f5;
  2279. }
  2280. .confirm-btn.confirm {
  2281. background-color: #fa5151;
  2282. color: #fff;
  2283. }
  2284. .chat-page {
  2285. display: flex;
  2286. flex-direction: column;
  2287. height: 100vh;
  2288. background-color: #f5f5f5;
  2289. }
  2290. /* 顶部导航 */
  2291. .chat-header {
  2292. display: flex;
  2293. align-items: center;
  2294. justify-content: space-between;
  2295. padding: 20rpx 30rpx;
  2296. background-color: #fff;
  2297. border-bottom: 1px solid #e5e5e5;
  2298. }
  2299. .header-left, .header-right {
  2300. width: 80rpx;
  2301. }
  2302. .icon-back, .icon-more {
  2303. font-size: 40rpx;
  2304. }
  2305. .header-center {
  2306. flex: 1;
  2307. text-align: center;
  2308. }
  2309. .chat-title {
  2310. display: block;
  2311. font-size: 36rpx;
  2312. font-weight: bold;
  2313. }
  2314. .online-status {
  2315. display: block;
  2316. font-size: 24rpx;
  2317. color: #999;
  2318. margin-top: 5rpx;
  2319. }
  2320. .online-status.online {
  2321. color: #07c160;
  2322. }
  2323. /* 消息列表 */
  2324. .message-list {
  2325. flex: 1;
  2326. padding: 20rpx;
  2327. overflow-y: scroll;
  2328. }
  2329. .loading-tip {
  2330. text-align: center;
  2331. padding: 20rpx;
  2332. color: #999;
  2333. font-size: 28rpx;
  2334. }
  2335. .message-item {
  2336. display: flex;
  2337. margin-bottom: 30rpx;
  2338. }
  2339. .message-item.message-self {
  2340. flex-direction: row-reverse;
  2341. }
  2342. .avatar {
  2343. width: 80rpx;
  2344. height: 80rpx;
  2345. border-radius: 8rpx;
  2346. margin: 0 20rpx;
  2347. }
  2348. .message-content-wrapper {
  2349. max-width: 70%;
  2350. display: inline-block;
  2351. }
  2352. .message-item.message-self .message-content-wrapper {
  2353. text-align: right; /* 关键:让气泡和状态提示整体右对齐 */
  2354. }
  2355. .message-name {
  2356. display: block;
  2357. font-size: 24rpx;
  2358. color: #999;
  2359. margin-bottom: 10rpx;
  2360. }
  2361. .message-bubble {
  2362. padding: 20rpx;
  2363. border-radius: 8rpx;
  2364. background-color: #fff;
  2365. word-wrap: break-word;
  2366. display: inline-block; /* 关键:气泡宽度由内容决定 */
  2367. max-width: 100%; /* 防止内容过长超出容器 */
  2368. position: relative;
  2369. }
  2370. .message-self .message-bubble {
  2371. background-color: #95ec69;
  2372. border-top-right-radius: 4rpx;
  2373. }
  2374. .message-bubble.bubble-self {
  2375. background-color: #95ec69;
  2376. }
  2377. .message-text {
  2378. font-size: 30rpx;
  2379. line-height: 1.5;
  2380. }
  2381. .message-image {
  2382. max-width: 400rpx;
  2383. border-radius: 8rpx;
  2384. }
  2385. .message-voice {
  2386. display: flex;
  2387. align-items: center;
  2388. gap: 12rpx;
  2389. padding: 0rpx 0;
  2390. min-width: 30rpx;
  2391. max-width: 400rpx;
  2392. cursor: pointer;
  2393. -webkit-tap-highlight-color: transparent;
  2394. outline: none;
  2395. border: none;
  2396. position: relative;
  2397. }
  2398. .voice-duration {
  2399. font-size: 27rpx;
  2400. color: #333;
  2401. flex-shrink: 0;
  2402. line-height: 1;
  2403. }
  2404. .voice-icon-wrapper {
  2405. display: flex;
  2406. flex-shrink: 0;
  2407. line-height: 0;
  2408. position: relative;
  2409. top: 1rpx;
  2410. }
  2411. .voice-icon {
  2412. width: 22rpx;
  2413. height: 22rpx;
  2414. display: block;
  2415. transform: none;
  2416. animation: none;
  2417. }
  2418. .voice-icon-wrapper.playing .voice-icon {
  2419. animation: voice-bounce 0.6s ease-in-out infinite;
  2420. }
  2421. .voice-resume-btn {
  2422. position: absolute;
  2423. top: 50%;
  2424. transform: translateY(-50%);
  2425. width: 32rpx;
  2426. height: 32rpx;
  2427. background: #07c160;
  2428. border-radius: 50%;
  2429. display: flex;
  2430. align-items: center;
  2431. justify-content: center;
  2432. box-shadow: 0 2rpx 8rpx rgba(7, 193, 96, 0.3);
  2433. }
  2434. .voice-resume-btn.resume-btn-left {
  2435. left: -40rpx;
  2436. }
  2437. .voice-resume-btn.resume-btn-right {
  2438. right: -40rpx;
  2439. }
  2440. .resume-icon {
  2441. color: #fff;
  2442. font-size: 16rpx;
  2443. margin-left: 2rpx;
  2444. }
  2445. @keyframes voice-bounce {
  2446. 0%, 100% {
  2447. transform: scale(1);
  2448. }
  2449. 50% {
  2450. transform: scale(1.2);
  2451. }
  2452. }
  2453. .message-video {
  2454. width: 400rpx;
  2455. height: 300rpx;
  2456. }
  2457. .message-recalled {
  2458. color: #999;
  2459. font-size: 28rpx;
  2460. }
  2461. .message-status {
  2462. text-align: right;
  2463. font-size: 22rpx;
  2464. color: #999;
  2465. margin-top: 8rpx;
  2466. }
  2467. .message-status .status-unread {
  2468. color: #999;
  2469. }
  2470. .message-status .status-read {
  2471. color: #07c160;
  2472. }
  2473. .message-status .status-failed {
  2474. color: #fa5151;
  2475. }
  2476. .message-time {
  2477. display: block;
  2478. text-align: right;
  2479. font-size: 22rpx;
  2480. color: #ccc;
  2481. margin-top: 5rpx;
  2482. }
  2483. /* 输入框 */
  2484. .input-bar {
  2485. display: flex;
  2486. align-items: center;
  2487. padding: 20rpx;
  2488. background-color: #fff;
  2489. border-top: 1px solid #e5e5e5;
  2490. }
  2491. .input-icon {
  2492. width: 80rpx;
  2493. height: 80rpx;
  2494. display: flex;
  2495. align-items: center;
  2496. justify-content: center;
  2497. font-size: 50rpx;
  2498. }
  2499. .input-icon .icon-image {
  2500. width: 50rpx;
  2501. height: 50rpx;
  2502. }
  2503. .send-button {
  2504. padding: 0 30rpx;
  2505. height: 70rpx;
  2506. line-height: 70rpx;
  2507. background-color: #07c160;
  2508. color: #fff;
  2509. border-radius: 8rpx;
  2510. text-align: center;
  2511. font-size: 28rpx;
  2512. margin-left: 10rpx;
  2513. transition: opacity 0.3s;
  2514. }
  2515. .send-button.disabled {
  2516. opacity: 0.5;
  2517. background-color: #95ec69;
  2518. }
  2519. .input-field {
  2520. flex: 1;
  2521. height: 70rpx;
  2522. padding: 0 20rpx;
  2523. background-color: #f5f5f5;
  2524. border-radius: 8rpx;
  2525. font-size: 30rpx;
  2526. }
  2527. .voice-button {
  2528. flex: 1;
  2529. height: 70rpx;
  2530. line-height: 70rpx;
  2531. background-color: #f5f5f5;
  2532. border-radius: 8rpx;
  2533. text-align: center;
  2534. font-size: 30rpx;
  2535. border: none;
  2536. }
  2537. /* 表情面板 */
  2538. .emoji-panel {
  2539. display: flex;
  2540. flex-wrap: wrap;
  2541. padding: 20rpx;
  2542. background-color: #fff;
  2543. border-top: 1px solid #e5e5e5;
  2544. }
  2545. .emoji-item {
  2546. width: 80rpx;
  2547. height: 80rpx;
  2548. display: flex;
  2549. align-items: center;
  2550. justify-content: center;
  2551. font-size: 60rpx;
  2552. }
  2553. /* 更多功能面板 */
  2554. .more-panel {
  2555. display: flex;
  2556. padding: 40rpx;
  2557. background-color: #fff;
  2558. border-top: 1px solid #e5e5e5;
  2559. }
  2560. .more-item {
  2561. display: flex;
  2562. flex-direction: column;
  2563. align-items: center;
  2564. margin: 0 40rpx;
  2565. }
  2566. .more-icon {
  2567. width: 100rpx;
  2568. height: 100rpx;
  2569. display: flex;
  2570. align-items: center;
  2571. justify-content: center;
  2572. font-size: 60rpx;
  2573. background-color: #f5f5f5;
  2574. border-radius: 16rpx;
  2575. margin-bottom: 10rpx;
  2576. }
  2577. .more-text {
  2578. font-size: 24rpx;
  2579. color: #666;
  2580. }
  2581. /* 时间分隔线 */
  2582. .time-divider {
  2583. text-align: center;
  2584. padding: 20rpx 0;
  2585. }
  2586. .time-text {
  2587. display: inline-block;
  2588. padding: 8rpx 20rpx;
  2589. background-color: rgba(0, 0, 0, 0.1);
  2590. border-radius: 8rpx;
  2591. font-size: 22rpx;
  2592. color: #999;
  2593. }
  2594. /* 消息气泡失败状态 */
  2595. .bubble-failed {
  2596. background-color: #95ec69;
  2597. opacity: 0.6;
  2598. border: 2rpx solid #fa5151;
  2599. }
  2600. /* 消息状态优化 */
  2601. .message-status .sending {
  2602. color: #576b95;
  2603. }
  2604. .message-status .failed-group {
  2605. display: flex;
  2606. align-items: center;
  2607. gap: 10rpx;
  2608. }
  2609. .message-status .retry-btn {
  2610. color: #576b95;
  2611. text-decoration: underline;
  2612. cursor: pointer;
  2613. }
  2614. /* 消息操作菜单遮罩 */
  2615. .message-action-mask {
  2616. position: fixed;
  2617. top: 0;
  2618. left: 0;
  2619. right: 0;
  2620. bottom: 0;
  2621. background-color: rgba(0, 0, 0, 0.4);
  2622. z-index: 9999;
  2623. display: flex;
  2624. align-items: center;
  2625. justify-content: center;
  2626. }
  2627. /* 消息操作菜单 */
  2628. .message-action-menu {
  2629. width: 600rpx;
  2630. background-color: #fff;
  2631. border-radius: 20rpx;
  2632. overflow: hidden;
  2633. }
  2634. .message-action-menu .menu-item {
  2635. display: flex;
  2636. align-items: center;
  2637. justify-content: center;
  2638. gap: 15rpx;
  2639. padding: 30rpx;
  2640. font-size: 32rpx;
  2641. color: #333;
  2642. border-bottom: 1rpx solid #f0f0f0;
  2643. transition: background-color 0.2s;
  2644. }
  2645. .message-action-menu .menu-item:active {
  2646. background-color: #f5f5f5;
  2647. }
  2648. .message-action-menu .menu-item.cancel {
  2649. color: #999;
  2650. border-bottom: none;
  2651. margin-top: 20rpx;
  2652. border-top: 10rpx solid #f5f5f5;
  2653. }
  2654. .message-action-menu .menu-icon {
  2655. font-size: 36rpx;
  2656. }
  2657. /* 消息发送限制提示 */
  2658. .message-limit-tip {
  2659. padding: 10rpx 20rpx;
  2660. font-size: 24rpx;
  2661. text-align: center;
  2662. background-color: #fff;
  2663. border-bottom: 1px solid #f5f5f5;
  2664. }
  2665. .vip-tip {
  2666. color: #ff9500; /* VIP橙色提示 */
  2667. }
  2668. .limit-tip {
  2669. color: #666; /* 普通灰色提示 */
  2670. }
  2671. .vip-link {
  2672. color: #2c9fff; /* 蓝色文字 */
  2673. text-decoration: underline; /* 下划线 */
  2674. cursor: pointer; /* 鼠标悬浮时显示手型 */
  2675. margin-left: 5rpx;
  2676. }
  2677. /* 点击时添加轻微反馈 */
  2678. .vip-link:active {
  2679. opacity: 0.7; /* 点击时透明度降低 */
  2680. }
  2681. /* 录音中提示遮罩 */
  2682. .voice-recording-mask {
  2683. position: fixed;
  2684. top: 0;
  2685. left: 0;
  2686. right: 0;
  2687. bottom: 0;
  2688. background-color: rgba(0, 0, 0, 0.6);
  2689. z-index: 10000;
  2690. display: flex;
  2691. align-items: center;
  2692. justify-content: center;
  2693. }
  2694. /* 录音提示框 */
  2695. .voice-recording-box {
  2696. width: 300rpx;
  2697. height: 300rpx;
  2698. background-color: rgba(0, 0, 0, 0.8);
  2699. border-radius: 20rpx;
  2700. display: flex;
  2701. flex-direction: column;
  2702. align-items: center;
  2703. justify-content: center;
  2704. color: #fff;
  2705. transition: background-color 0.3s;
  2706. }
  2707. .voice-recording-box.canceling {
  2708. background-color: rgba(220, 38, 38, 0.9);
  2709. }
  2710. .voice-wave-container {
  2711. display: flex;
  2712. align-items: center;
  2713. justify-content: center;
  2714. gap: 8rpx;
  2715. height: 100rpx;
  2716. margin-bottom: 20rpx;
  2717. }
  2718. .voice-wave-bar {
  2719. width: 6rpx;
  2720. background: #fff;
  2721. border-radius: 3rpx;
  2722. transition: transform 0.1s ease-out;
  2723. transform-origin: center;
  2724. }
  2725. .voice-wave-bar.bar1 {
  2726. height: 30rpx;
  2727. }
  2728. .voice-wave-bar.bar2 {
  2729. height: 45rpx;
  2730. }
  2731. .voice-wave-bar.bar3 {
  2732. height: 60rpx;
  2733. }
  2734. .voice-wave-bar.bar4 {
  2735. height: 50rpx;
  2736. }
  2737. .voice-wave-bar.bar5 {
  2738. height: 35rpx;
  2739. }
  2740. .voice-text {
  2741. font-size: 32rpx;
  2742. margin-bottom: 10rpx;
  2743. }
  2744. .voice-time {
  2745. font-size: 48rpx;
  2746. font-weight: bold;
  2747. color: #07c160;
  2748. margin: 10rpx 0;
  2749. }
  2750. .voice-tip {
  2751. font-size: 24rpx;
  2752. color: #ccc;
  2753. }
  2754. </style>