chat.vue 82 KB

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