chat.vue 75 KB

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