chat.vue 90 KB

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