index.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. <template>
  2. <view class="chat-page">
  3. <view class="chat-header">
  4. <view class="chat-header-main">
  5. <view class="back" @click="goBack">
  6. <image class="header-icon-img" src="/static/icons/back.svg" mode="aspectFit" />
  7. </view>
  8. <view class="chat-title-wrap" @click="onTitleClick">
  9. <view class="chat-title-texts">
  10. <text class="chat-title">{{ contactTitle }}</text>
  11. </view>
  12. </view>
  13. <view class="header-actions">
  14. <view class="header-icon" @click="onMore">
  15. <image class="header-icon-img" src="/static/icons/more.svg" mode="aspectFit" />
  16. </view>
  17. </view>
  18. </view>
  19. </view>
  20. <scroll-view
  21. class="message-list"
  22. scroll-y
  23. :scroll-into-view="scrollIntoView"
  24. scroll-with-animation
  25. @scrolltoupper="onLoadMore"
  26. >
  27. <view v-if="loadingMoreForContact" class="load-more">加载更多...</view>
  28. <view v-else-if="!messageList.length" class="empty-messages">
  29. <text class="empty-text">暂无消息,发一句打个招呼吧</text>
  30. </view>
  31. <view
  32. v-for="(msg, index) in messageList"
  33. :key="msg.id || msg.tempId || index"
  34. :id="'msg-' + (msg.id || msg.tempId)"
  35. >
  36. <PrivateMessageBubble
  37. v-if="msg.type === 'MESSAGE' || msg.type === 'PRIVATE' || !msg.type"
  38. :msg="msg"
  39. :sender-name="getSenderName(msg)"
  40. :sender-id="otherUserId"
  41. :sender-avatar="contactAvatar"
  42. :me-name="currentUserName"
  43. :me-id="currentUserId"
  44. :me-avatar="currentUserAvatar"
  45. :show-date-label="shouldShowDateLabel(index)"
  46. :remind-loading="remindingNotificationId === String(msg.id)"
  47. @preview-image="previewImage"
  48. @open-notification-url="openNotificationUrl"
  49. @retry="onRetry"
  50. @remind-user-notification="onRemindUserNotification"
  51. />
  52. <NotificationBubble
  53. v-else
  54. :msg="msg"
  55. :sender-name="getSenderName(msg)"
  56. :show-date-label="shouldShowDateLabel(index)"
  57. @open-notification-url="openNotificationUrl"
  58. />
  59. </view>
  60. </scroll-view>
  61. <view class="input-bar">
  62. <view class="input-row">
  63. <view class="input-wrap">
  64. <input
  65. v-model="inputValue"
  66. class="input"
  67. :placeholder="'发送给 ' + contactTitle"
  68. confirm-type="send"
  69. @confirm="onSend"
  70. @focus="onInputFocus"
  71. />
  72. </view>
  73. <view class="input-icon input-icon-plus" @click="onPlus">
  74. <image class="input-plus-img" src="/static/icons/add.svg" mode="aspectFit" />
  75. </view>
  76. </view>
  77. <view v-if="showPlusPanel" class="plus-panel">
  78. <view class="plus-item" @click="onChooseImage">
  79. <view class="plus-icon">
  80. <image class="plus-inner-icon" src="/static/icons/image.svg" mode="aspectFit" />
  81. </view>
  82. <text class="plus-label-title">图片</text>
  83. </view>
  84. <view class="plus-item" @click="onChooseVideo">
  85. <view class="plus-icon">
  86. <image class="plus-inner-icon" src="/static/icons/video.svg" mode="aspectFit" />
  87. </view>
  88. <text class="plus-label-title">视频</text>
  89. </view>
  90. <view class="plus-item" @click="onChooseFile">
  91. <view class="plus-icon">
  92. <image class="plus-inner-icon" src="/static/icons/file.svg" mode="aspectFit" />
  93. </view>
  94. <text class="plus-label-title">文件</text>
  95. </view>
  96. </view>
  97. </view>
  98. </view>
  99. </template>
  100. <script setup>
  101. import { ref, computed, watch, nextTick } from 'vue'
  102. import { onLoad, onUnload, onShow } from '@dcloudio/uni-app'
  103. import PrivateMessageBubble from '../../components/chat/PrivateMessageBubble.vue'
  104. import NotificationBubble from '../../components/chat/NotificationBubble.vue'
  105. import { useMessages } from '../../composables/useMessages'
  106. import { useContacts } from '../../composables/useContacts'
  107. import { chatStore } from '../../store/chat'
  108. import { getMessageCallbackUrl, getToken, markHistoryReadAll } from '../../utils/api'
  109. import { fetchUnreadCountAndUpdateTabBar } from '../../composables/useUnreadBadge'
  110. const otherUserId = ref('')
  111. const contactTitle = ref('会话')
  112. const fallbackContactName = ref('')
  113. const inputValue = ref('')
  114. const scrollIntoView = ref('')
  115. /** 从消息搜索进入时滚动到指定消息 id,定位后清空 */
  116. const scrollToMessageId = ref('')
  117. /** 用于区分「底部最后一条是否变化」:加载更多只 prepend 时不变,避免误滚到底 */
  118. const lastBottomMsgKey = ref('')
  119. const showPlusPanel = ref(false)
  120. /** 正在对哪条 USER_NOTIFICATION 执行「再次提醒」(用于按钮 loading,并防并发连点) */
  121. const remindingNotificationId = ref('')
  122. const { messages, loadingMore, fetchMessages, fetchMoreMessages, sendMessage, retrySendMessage, sendFileMessage, retrySendFileMessage, remindUserNotification } = useMessages()
  123. const { fetchContacts } = useContacts()
  124. function syncContactTitle() {
  125. const contact = (chatStore.contacts || []).find((c) => String(c.user_id || c.id) === String(otherUserId.value))
  126. if (contact) {
  127. contactTitle.value = (contact.app_name || contact.title || '会话')
  128. return
  129. }
  130. // 若会话列表未命中(例如从联系人详情进入,此时 chatStore.contacts 未包含该用户)
  131. contactTitle.value = fallbackContactName.value || '会话'
  132. }
  133. const messageList = computed(() => {
  134. const id = String(otherUserId.value)
  135. return (messages[id] || [])
  136. })
  137. const loadingMoreForContact = computed(() => !!loadingMore[String(otherUserId.value)])
  138. /** 滚到列表底部;先清空 scroll-into-view 再设锚点,避免同 id 时不滚动 */
  139. function scrollToBottom() {
  140. if (scrollToMessageId.value) return
  141. const list = messageList.value
  142. if (!list.length) return
  143. const last = list[list.length - 1]
  144. const anchor = 'msg-' + (last.id || last.tempId)
  145. scrollIntoView.value = ''
  146. nextTick(() => {
  147. scrollIntoView.value = anchor
  148. setTimeout(() => {
  149. scrollIntoView.value = anchor
  150. }, 50)
  151. })
  152. }
  153. onLoad(async (options) => {
  154. lastBottomMsgKey.value = ''
  155. otherUserId.value = String(
  156. (options && (options.otherUserId || options.userId || options.contactId)) || '0'
  157. )
  158. // 用联系人详情传参兜底:保证从联系人详情进来仍能显示名字
  159. try {
  160. const raw = options && options.contactName != null ? String(options.contactName) : ''
  161. const s = raw
  162. // 若未自动解码,可能是 %E5...,这里做一次安全解码
  163. if (/%[0-9A-Fa-f]{2}/.test(s)) fallbackContactName.value = decodeURIComponent(s)
  164. else fallbackContactName.value = s
  165. } catch (e) {
  166. fallbackContactName.value = ''
  167. }
  168. try {
  169. const mid = options && (options.scrollToMessageId || options.messageId)
  170. if (mid != null && String(mid).trim() !== '') scrollToMessageId.value = String(mid).trim()
  171. } catch (e) {
  172. scrollToMessageId.value = ''
  173. }
  174. chatStore.setActiveContact(otherUserId.value)
  175. syncContactTitle()
  176. try {
  177. const token = getToken()
  178. if (token) {
  179. await markHistoryReadAll(token, otherUserId.value)
  180. await fetchUnreadCountAndUpdateTabBar()
  181. }
  182. } catch (e) {
  183. // read-all 失败仍允许查看历史
  184. }
  185. try {
  186. const u = uni.getStorageSync('current_user')
  187. if (u && typeof u === 'object') {
  188. if (u.name) currentUserName.value = u.name
  189. currentUserId.value = String(u.id ?? u.user_id ?? '')
  190. currentUserAvatar.value = u.avatar || u.avatar_url || ''
  191. }
  192. } catch (e) {}
  193. // 进入聊天时,确保会话列表已就绪:联系人详情页跳转时可能还没加载 chatStore.contacts
  194. if (!chatStore.contacts || !chatStore.contacts.length) {
  195. Promise.resolve()
  196. .then(() => fetchContacts())
  197. .then(() => syncContactTitle())
  198. .catch(() => {})
  199. } else {
  200. // contacts 已有数据时也做一次兜底(例如 otherUserId 刚好没命中但后续会更新)
  201. syncContactTitle()
  202. }
  203. })
  204. /** 每次显示页面都拉最新一页(含从子页返回),并在数据就绪后滚到底 */
  205. onShow(async () => {
  206. const id = otherUserId.value
  207. if (!id || id === '0') return
  208. await fetchMessages(id)
  209. scrollToBottom()
  210. })
  211. onUnload(() => {
  212. chatStore.setActiveContact('')
  213. })
  214. watch(messageList, (list) => {
  215. if (!list.length) return
  216. const target = scrollToMessageId.value
  217. if (target) {
  218. const hit = list.find((m) => String(m.id) === String(target) || String(m.tempId) === String(target))
  219. if (hit) {
  220. const anchor = 'msg-' + (hit.id || hit.tempId)
  221. scrollIntoView.value = ''
  222. nextTick(() => {
  223. scrollIntoView.value = anchor
  224. })
  225. scrollToMessageId.value = ''
  226. return
  227. }
  228. return
  229. }
  230. const last = list[list.length - 1]
  231. const key = String(last.id || last.tempId)
  232. if (lastBottomMsgKey.value === key) return
  233. lastBottomMsgKey.value = key
  234. scrollToBottom()
  235. }, { deep: true })
  236. // contacts 更新后同步聊天标题(避免从联系人详情进入仍显示“会话”)
  237. watch(
  238. () => chatStore.contacts,
  239. () => {
  240. if (otherUserId.value) syncContactTitle()
  241. },
  242. { deep: true }
  243. )
  244. function goBack() {
  245. uni.navigateBack()
  246. }
  247. function onSend() {
  248. const text = inputValue.value.trim()
  249. if (!text) return
  250. sendMessage(otherUserId.value, text)
  251. inputValue.value = ''
  252. showPlusPanel.value = false
  253. }
  254. function onLoadMore() {
  255. fetchMoreMessages(otherUserId.value)
  256. }
  257. function basenameFromPath(p) {
  258. if (!p) return ''
  259. const s = String(p).replace(/\\/g, '/')
  260. const i = s.lastIndexOf('/')
  261. return i >= 0 ? s.slice(i + 1) : s
  262. }
  263. function onRetry(msg) {
  264. if (!msg || msg.status !== 'failed') return
  265. if (msg.contentType === 'TEXT') {
  266. retrySendMessage(otherUserId.value, msg)
  267. return
  268. }
  269. retrySendFileMessage(otherUserId.value, msg)
  270. }
  271. async function onRemindUserNotification(msg) {
  272. if (remindingNotificationId.value) return
  273. if (!msg || msg.tempId) return
  274. remindingNotificationId.value = String(msg.id)
  275. try {
  276. await remindUserNotification(otherUserId.value, msg)
  277. } finally {
  278. remindingNotificationId.value = ''
  279. }
  280. }
  281. function getSenderName(msg) {
  282. return msg.isMe ? (currentUserName.value || '我') : contactTitle.value
  283. }
  284. function shouldShowDateLabel(index) {
  285. const list = messageList.value
  286. if (index <= 0) return true
  287. const prev = list[index - 1]
  288. const curr = list[index]
  289. if (!prev || !curr || !prev.createdAt || !curr.createdAt) return true
  290. const prevDay = new Date(prev.createdAt).toDateString()
  291. const currDay = new Date(curr.createdAt).toDateString()
  292. return prevDay !== currDay
  293. }
  294. const currentUserName = ref('')
  295. const currentUserId = ref('')
  296. const currentUserAvatar = ref('')
  297. const contactAvatar = computed(() => {
  298. const contact = (chatStore.contacts || []).find((c) => String(c.user_id || c.id) === String(otherUserId.value))
  299. return (contact && contact.avatar) ? contact.avatar : ''
  300. })
  301. function previewImage(url) {
  302. if (!url) return
  303. uni.previewImage({ urls: [url] })
  304. }
  305. async function openNotificationUrl(msg) {
  306. const token = getToken()
  307. try {
  308. const res = await getMessageCallbackUrl(token, msg.id)
  309. const url = res.callback_url || res.callbackUrl || msg.actionUrl
  310. if (url) {
  311. const pageUrl =
  312. '/pages/webview/index?url=' +
  313. encodeURIComponent(url) +
  314. '&title=' +
  315. encodeURIComponent(msg.title || '详情')
  316. uni.navigateTo({ url: pageUrl })
  317. }
  318. } catch (e) {
  319. if (msg.actionUrl) {
  320. const pageUrl =
  321. '/pages/webview/index?url=' +
  322. encodeURIComponent(msg.actionUrl) +
  323. '&title=' +
  324. encodeURIComponent(msg.title || '详情')
  325. uni.navigateTo({ url: pageUrl })
  326. } else {
  327. uni.showToast({ title: '打开失败', icon: 'none' })
  328. }
  329. }
  330. }
  331. function onTitleClick() {
  332. // 可扩展:进入联系人详情或下拉菜单
  333. }
  334. function onMore() {
  335. uni.showActionSheet({
  336. itemList: ['聊天信息', '查找聊天内容', '清空聊天记录'],
  337. success: (res) => {}
  338. })
  339. }
  340. function onInputFocus() {
  341. showPlusPanel.value = false
  342. }
  343. function onChooseImage() {
  344. uni.hideKeyboard()
  345. uni.chooseImage({
  346. count: 1,
  347. success: (res) => {
  348. const path = res.tempFilePaths[0]
  349. const name = basenameFromPath(path) || 'image.jpg'
  350. sendFileMessage(otherUserId.value, path, 'IMAGE', name)
  351. }
  352. })
  353. }
  354. function onChooseVideo() {
  355. uni.hideKeyboard()
  356. uni.chooseVideo({
  357. sourceType: ['album', 'camera'],
  358. success: (res) => {
  359. const path = res.tempFilePath || (res.tempFilePaths && res.tempFilePaths[0])
  360. if (path) {
  361. const name = basenameFromPath(path) || 'video.mp4'
  362. sendFileMessage(otherUserId.value, path, 'VIDEO', name)
  363. }
  364. }
  365. })
  366. }
  367. function onChooseFile() {
  368. uni.hideKeyboard()
  369. const pick = (path, name) => {
  370. const n = (name && String(name).trim()) || basenameFromPath(path) || '文件'
  371. sendFileMessage(otherUserId.value, path, 'FILE', n)
  372. }
  373. if (typeof uni.chooseMessageFile === 'function') {
  374. uni.chooseMessageFile({
  375. count: 1,
  376. type: 'file',
  377. success: (res) => {
  378. const file = res.tempFiles && res.tempFiles[0]
  379. if (file && file.path) pick(file.path, file.name)
  380. }
  381. })
  382. } else if (typeof uni.chooseFile === 'function') {
  383. uni.chooseFile({
  384. count: 1,
  385. success: (res) => {
  386. const path = (res.tempFilePaths && res.tempFilePaths[0]) || ''
  387. if (path) pick(path)
  388. }
  389. })
  390. } else {
  391. uni.showToast({ title: '当前端暂不支持选文件', icon: 'none' })
  392. }
  393. }
  394. function onPlus() {
  395. uni.hideKeyboard()
  396. showPlusPanel.value = !showPlusPanel.value
  397. }
  398. </script>
  399. <style scoped>
  400. .chat-page {
  401. height: 100vh;
  402. display: flex;
  403. flex-direction: column;
  404. background: #f3f4f6;
  405. overflow-x: hidden;
  406. /* 顶部安全区由 header 自己处理 */
  407. padding-bottom: constant(safe-area-inset-bottom);
  408. padding-bottom: env(safe-area-inset-bottom);
  409. }
  410. .chat-header {
  411. /* 只负责安全区和背景,与会话列表页 custom-header 对齐 */
  412. padding: 0 24rpx 24rpx 32rpx;
  413. padding-top: 88rpx;
  414. padding-top: max(88rpx, calc(24rpx + constant(safe-area-inset-top)));
  415. padding-top: max(88rpx, calc(24rpx + env(safe-area-inset-top)));
  416. background: #ffffff;
  417. box-shadow: 0 1px 0 rgba(15, 23, 42, 0.06);
  418. }
  419. .chat-header-main {
  420. height: 88rpx;
  421. display: flex;
  422. align-items: center;
  423. justify-content: space-between;
  424. position: relative;
  425. }
  426. .back {
  427. width: 64rpx;
  428. height: 64rpx;
  429. display: flex;
  430. align-items: center;
  431. justify-content: center;
  432. margin-right: 8rpx;
  433. }
  434. .header-icon-img {
  435. width: 44rpx;
  436. height: 44rpx;
  437. opacity: 0.9;
  438. }
  439. .chat-title-wrap {
  440. position: absolute;
  441. left: 50%;
  442. transform: translateX(-50%);
  443. display: flex;
  444. align-items: center;
  445. justify-content: center;
  446. }
  447. .chat-title-texts {
  448. display: flex;
  449. flex-direction: column;
  450. justify-content: center;
  451. }
  452. .chat-title {
  453. font-size: 34rpx;
  454. font-weight: 600;
  455. color: #111827;
  456. }
  457. .header-actions {
  458. display: flex;
  459. align-items: center;
  460. gap: 16rpx;
  461. }
  462. .header-icon {
  463. width: 56rpx;
  464. height: 56rpx;
  465. display: flex;
  466. align-items: center;
  467. justify-content: center;
  468. }
  469. .message-list {
  470. flex: 1;
  471. min-height: 0;
  472. height: 0;
  473. /* 去掉顶部内边距,使第一条消息与列表页首行对齐 */
  474. padding: 0 24rpx 16rpx;
  475. }
  476. .load-more {
  477. text-align: center;
  478. padding: 16rpx;
  479. font-size: 24rpx;
  480. color: #999;
  481. }
  482. .empty-messages {
  483. flex: 1;
  484. display: flex;
  485. align-items: center;
  486. justify-content: center;
  487. min-height: 200rpx;
  488. padding: 48rpx;
  489. }
  490. .empty-text {
  491. font-size: 28rpx;
  492. color: #999;
  493. }
  494. .input-bar {
  495. display: flex;
  496. flex-direction: column;
  497. gap: 16rpx;
  498. padding: 10rpx 16rpx;
  499. background: #f5f5f7;
  500. border-top: 1rpx solid #e5e7eb;
  501. padding-bottom: max(10rpx, constant(safe-area-inset-bottom));
  502. padding-bottom: max(10rpx, env(safe-area-inset-bottom));
  503. }
  504. .input-row {
  505. display: flex;
  506. align-items: center;
  507. }
  508. .input-wrap {
  509. position: relative;
  510. min-height: 60rpx;
  511. max-height: 140rpx;
  512. padding: 6rpx 18rpx;
  513. background: #ffffff;
  514. border-radius: 999rpx;
  515. flex: 1;
  516. display: flex;
  517. align-items: center;
  518. }
  519. .input {
  520. min-height: 40rpx;
  521. font-size: 26rpx;
  522. height: 44rpx;
  523. line-height: 44rpx;
  524. padding: 0;
  525. width: 100%;
  526. box-sizing: border-box;
  527. }
  528. .input-icons {
  529. display: flex;
  530. align-items: center;
  531. justify-content: flex-start;
  532. gap: 24rpx;
  533. }
  534. .input-icon {
  535. width: 64rpx;
  536. height: 64rpx;
  537. display: flex;
  538. align-items: center;
  539. justify-content: center;
  540. }
  541. .input-icon .icon-emoji,
  542. .input-icon .icon-at,
  543. .input-icon .icon-mic,
  544. .input-icon .icon-pic,
  545. .input-icon .icon-aa {
  546. font-size: 40rpx;
  547. color: #6b7280;
  548. }
  549. .input-icon-plus {
  550. margin-left: 12rpx;
  551. border-radius: 999rpx;
  552. border: 2rpx solid #111827;
  553. background: #ffffff;
  554. }
  555. .input-plus-img {
  556. width: 36rpx;
  557. height: 36rpx;
  558. opacity: 0.9;
  559. }
  560. .plus-panel {
  561. margin-top: 12rpx;
  562. padding: 24rpx 16rpx 12rpx;
  563. background: #f5f5f7;
  564. border-radius: 24rpx;
  565. display: flex;
  566. justify-content: space-between;
  567. }
  568. .plus-item {
  569. flex: 1;
  570. display: flex;
  571. flex-direction: column;
  572. align-items: center;
  573. justify-content: flex-start;
  574. }
  575. .plus-icon {
  576. width: 120rpx;
  577. height: 120rpx;
  578. border-radius: 32rpx;
  579. background: #ffffff;
  580. display: flex;
  581. align-items: center;
  582. justify-content: center;
  583. margin-bottom: 8rpx;
  584. }
  585. .plus-inner-icon {
  586. width: 56rpx;
  587. height: 56rpx;
  588. }
  589. .plus-label-title {
  590. font-size: 26rpx;
  591. color: #111111;
  592. }
  593. .plus-label-desc {
  594. margin-top: 2rpx;
  595. font-size: 22rpx;
  596. color: #999999;
  597. }
  598. </style>