index.vue 17 KB

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