KeFuMessageList.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. <template>
  2. <el-container v-if="showKeFuMessageList" class="kefu">
  3. <el-header class="kefu-header">
  4. <div class="kefu-title">{{ conversation.userNickname }}</div>
  5. </el-header>
  6. <el-main class="kefu-content overflow-visible">
  7. <el-scrollbar ref="scrollbarRef" always @scroll="handleScroll">
  8. <div v-if="refreshContent" ref="innerRef" class="w-[100%] px-10px">
  9. <!-- 消息列表 -->
  10. <div v-for="(item, index) in getMessageList0" :key="item.id" class="w-[100%]">
  11. <div class="flex justify-center items-center mb-20px">
  12. <!-- 日期 -->
  13. <div
  14. v-if="
  15. item.contentType !== KeFuMessageContentTypeEnum.SYSTEM && showTime(item, index)
  16. "
  17. class="date-message"
  18. >
  19. {{ formatDate(item.createTime) }}
  20. </div>
  21. <!-- 系统消息 -->
  22. <div
  23. v-if="item.contentType === KeFuMessageContentTypeEnum.SYSTEM"
  24. class="system-message"
  25. >
  26. {{ item.content }}
  27. </div>
  28. </div>
  29. <div
  30. :class="[
  31. item.senderType === UserTypeEnum.MEMBER
  32. ? `ss-row-left`
  33. : item.senderType === UserTypeEnum.ADMIN
  34. ? `ss-row-right`
  35. : ''
  36. ]"
  37. class="flex mb-20px w-[100%]"
  38. >
  39. <el-avatar
  40. v-if="item.senderType === UserTypeEnum.MEMBER"
  41. :src="conversation.userAvatar"
  42. alt="avatar"
  43. class="w-60px h-60px"
  44. />
  45. <div
  46. :class="{
  47. 'kefu-message': KeFuMessageContentTypeEnum.TEXT === item.contentType
  48. }"
  49. >
  50. <!-- 文本消息 -->
  51. <MessageItem :message="item">
  52. <template v-if="KeFuMessageContentTypeEnum.TEXT === item.contentType">
  53. <div
  54. v-dompurify-html="replaceEmoji(getMessageContent(item).text || item.content)"
  55. class="line-height-normal text-justify h-1/1 w-full"
  56. ></div>
  57. </template>
  58. </MessageItem>
  59. <!-- 图片消息 -->
  60. <MessageItem :message="item">
  61. <el-image
  62. v-if="KeFuMessageContentTypeEnum.IMAGE === item.contentType"
  63. :initial-index="0"
  64. :preview-src-list="[getMessageContent(item).picUrl || item.content]"
  65. :src="getMessageContent(item).picUrl || item.content"
  66. class="w-200px mx-10px"
  67. fit="contain"
  68. preview-teleported
  69. />
  70. </MessageItem>
  71. <!-- 商品消息 -->
  72. <MessageItem :message="item">
  73. <ProductItem
  74. v-if="KeFuMessageContentTypeEnum.PRODUCT === item.contentType"
  75. :picUrl="getMessageContent(item).picUrl"
  76. :price="getMessageContent(item).price"
  77. :sales-count="getMessageContent(item).salesCount"
  78. :spuId="getMessageContent(item).spuId"
  79. :stock="getMessageContent(item).stock"
  80. :title="getMessageContent(item).spuName"
  81. class="max-w-300px mx-10px"
  82. />
  83. </MessageItem>
  84. <!-- 订单消息 -->
  85. <MessageItem :message="item">
  86. <OrderItem
  87. v-if="KeFuMessageContentTypeEnum.ORDER === item.contentType"
  88. :message="item"
  89. class="max-w-100% mx-10px"
  90. />
  91. </MessageItem>
  92. </div>
  93. <el-avatar
  94. v-if="item.senderType === UserTypeEnum.ADMIN"
  95. :src="item.senderAvatar"
  96. alt="avatar"
  97. />
  98. </div>
  99. </div>
  100. </div>
  101. </el-scrollbar>
  102. <div
  103. v-show="showNewMessageTip"
  104. class="newMessageTip flex items-center cursor-pointer"
  105. @click="handleToNewMessage"
  106. >
  107. <span>有新消息</span>
  108. <Icon class="ml-5px" icon="ep:bottom" />
  109. </div>
  110. </el-main>
  111. <el-footer class="kefu-footer">
  112. <div class="chat-tools flex items-center">
  113. <EmojiSelectPopover @select-emoji="handleEmojiSelect" />
  114. <PictureSelectUpload
  115. class="ml-15px mt-3px cursor-pointer"
  116. @send-picture="handleSendPicture"
  117. />
  118. </div>
  119. <el-input
  120. v-model="message"
  121. :rows="6"
  122. placeholder="输入消息,Enter发送,Shift+Enter换行"
  123. style="border-style: none"
  124. type="textarea"
  125. @keyup.enter.prevent="handleSendMessage"
  126. />
  127. </el-footer>
  128. </el-container>
  129. <el-container v-else class="kefu">
  130. <el-main>
  131. <el-empty description="请选择左侧的一个会话后开始" />
  132. </el-main>
  133. </el-container>
  134. </template>
  135. <script lang="ts" setup>
  136. import { ElScrollbar as ElScrollbarType } from 'element-plus'
  137. import { KeFuMessageApi, KeFuMessageRespVO } from '@/api/mall/promotion/kefu/message'
  138. import { KeFuConversationRespVO } from '@/api/mall/promotion/kefu/conversation'
  139. import EmojiSelectPopover from './tools/EmojiSelectPopover.vue'
  140. import PictureSelectUpload from './tools/PictureSelectUpload.vue'
  141. import ProductItem from './message/ProductItem.vue'
  142. import OrderItem from './message/OrderItem.vue'
  143. import { Emoji, useEmoji } from './tools/emoji'
  144. import { KeFuMessageContentTypeEnum } from './tools/constants'
  145. import { isEmpty } from '@/utils/is'
  146. import { UserTypeEnum } from '@/utils/constants'
  147. import { formatDate } from '@/utils/formatTime'
  148. import dayjs from 'dayjs'
  149. import relativeTime from 'dayjs/plugin/relativeTime'
  150. import { debounce } from 'lodash-es'
  151. import { jsonParse } from '@/utils'
  152. import { useMallKefuStore } from '@/store/modules/mall/kefu'
  153. dayjs.extend(relativeTime)
  154. defineOptions({ name: 'KeFuMessageList' })
  155. const message = ref('') // 消息弹窗
  156. const { replaceEmoji } = useEmoji()
  157. const messageTool = useMessage()
  158. const messageList = ref<KeFuMessageRespVO[]>([]) // 消息列表
  159. const conversation = ref<KeFuConversationRespVO>({} as KeFuConversationRespVO) // 用户会话
  160. const showNewMessageTip = ref(false) // 显示有新消息提示
  161. const queryParams = reactive({
  162. conversationId: 0,
  163. createTime: undefined
  164. })
  165. const total = ref(0) // 消息总条数
  166. const refreshContent = ref(false) // 内容刷新,主要解决会话消息页面高度不一致导致的滚动功能精度失效
  167. const kefuStore = useMallKefuStore() // 客服缓存
  168. /** 获悉消息内容 */
  169. const getMessageContent = computed(() => (item: any) => jsonParse(item.content))
  170. /** 获得消息列表 */
  171. const getMessageList = async () => {
  172. const res = await KeFuMessageApi.getKeFuMessageList(queryParams)
  173. if (isEmpty(res)) {
  174. // 当返回的是空列表说明没有消息或者已经查询完了历史消息
  175. skipGetMessageList.value = true
  176. return
  177. }
  178. queryParams.createTime = formatDate(res.at(-1).createTime) as any
  179. // 情况一:加载最新消息
  180. if (!queryParams.createTime) {
  181. messageList.value = res
  182. } else {
  183. // 情况二:加载历史消息
  184. for (const item of res) {
  185. pushMessage(item)
  186. }
  187. }
  188. refreshContent.value = true
  189. }
  190. /** 添加消息 */
  191. const pushMessage = (message: any) => {
  192. if (messageList.value.some((val) => val.id === message.id)) {
  193. return
  194. }
  195. messageList.value.push(message)
  196. }
  197. /** 按照时间倒序,获取消息列表 */
  198. const getMessageList0 = computed(() => {
  199. messageList.value.sort((a: any, b: any) => a.createTime - b.createTime)
  200. return messageList.value
  201. })
  202. /** 刷新消息列表 */
  203. const refreshMessageList = async (message?: any) => {
  204. if (!conversation.value) {
  205. return
  206. }
  207. if (typeof message !== 'undefined') {
  208. // 当前查询会话与消息所属会话不一致则不做处理
  209. if (message.conversationId !== conversation.value.id) {
  210. return
  211. }
  212. pushMessage(message)
  213. } else {
  214. queryParams.createTime = undefined
  215. await getMessageList()
  216. }
  217. if (loadHistory.value) {
  218. // 右下角显示有新消息提示
  219. showNewMessageTip.value = true
  220. } else {
  221. // 滚动到最新消息处
  222. await handleToNewMessage()
  223. }
  224. }
  225. /** 获得新会话的消息列表, 点击切换时,读取缓存;然后异步获取新消息,merge 下; */
  226. const getNewMessageList = async (val: KeFuConversationRespVO) => {
  227. // 1. 缓存当前会话消息列表
  228. kefuStore.saveMessageList(conversation.value.id, messageList.value)
  229. // 2.1 会话切换,重置相关参数
  230. messageList.value = kefuStore.getConversationMessageList(val.id) || []
  231. total.value = messageList.value.length || 0
  232. loadHistory.value = false
  233. refreshContent.value = false
  234. skipGetMessageList.value = false
  235. // 2.2 设置会话相关属性
  236. conversation.value = val
  237. queryParams.conversationId = val.id
  238. queryParams.createTime = undefined
  239. // 3. 获取消息
  240. await refreshMessageList()
  241. }
  242. defineExpose({ getNewMessageList, refreshMessageList })
  243. const showKeFuMessageList = computed(() => !isEmpty(conversation.value)) // 是否显示聊天区域
  244. const skipGetMessageList = ref(false) // 跳过消息获取
  245. /** 处理表情选择 */
  246. const handleEmojiSelect = (item: Emoji) => {
  247. message.value += item.name
  248. }
  249. /** 处理图片发送 */
  250. const handleSendPicture = async (picUrl: string) => {
  251. // 组织发送消息
  252. const msg = {
  253. conversationId: conversation.value.id,
  254. contentType: KeFuMessageContentTypeEnum.IMAGE,
  255. content: JSON.stringify({ picUrl })
  256. }
  257. await sendMessage(msg)
  258. }
  259. /** 发送文本消息 */
  260. const handleSendMessage = async (event: any) => {
  261. // shift 不发送
  262. if (event.shiftKey) {
  263. return
  264. }
  265. // 1. 校验消息是否为空
  266. if (isEmpty(unref(message.value)?.trim())) {
  267. messageTool.notifyWarning('请输入消息后再发送哦!')
  268. message.value = ''
  269. return
  270. }
  271. // 2. 组织发送消息
  272. const msg = {
  273. conversationId: conversation.value.id,
  274. contentType: KeFuMessageContentTypeEnum.TEXT,
  275. content: JSON.stringify({ text: message.value })
  276. }
  277. await sendMessage(msg)
  278. }
  279. /** 真正发送消息 【共用】*/
  280. const sendMessage = async (msg: any) => {
  281. // 发送消息
  282. await KeFuMessageApi.sendKeFuMessage(msg)
  283. message.value = ''
  284. // 加载消息列表
  285. await refreshMessageList()
  286. // 更新会话缓存
  287. await kefuStore.updateConversation(conversation.value.id)
  288. }
  289. /** 滚动到底部 */
  290. const innerRef = ref<HTMLDivElement>()
  291. const scrollbarRef = ref<InstanceType<typeof ElScrollbarType>>()
  292. const scrollToBottom = async () => {
  293. // 1. 首次加载时滚动到最新消息,如果加载的是历史消息则不滚动
  294. if (loadHistory.value) {
  295. return
  296. }
  297. // 2.1 滚动到最新消息,关闭新消息提示
  298. await nextTick()
  299. scrollbarRef.value!.setScrollTop(innerRef.value!.clientHeight)
  300. showNewMessageTip.value = false
  301. // 2.2 消息已读
  302. await KeFuMessageApi.updateKeFuMessageReadStatus(conversation.value.id)
  303. }
  304. /** 查看新消息 */
  305. const handleToNewMessage = async () => {
  306. loadHistory.value = false
  307. await scrollToBottom()
  308. }
  309. const loadHistory = ref(false) // 加载历史消息
  310. /** 处理消息列表滚动事件(debounce 限流) */
  311. const handleScroll = debounce(({ scrollTop }) => {
  312. if (skipGetMessageList.value) {
  313. return
  314. }
  315. // 触顶自动加载下一页数据
  316. if (Math.floor(scrollTop) === 0) {
  317. handleOldMessage()
  318. }
  319. const wrap = scrollbarRef.value?.wrapRef
  320. // 触底重置
  321. if (Math.abs(wrap!.scrollHeight - wrap!.clientHeight - wrap!.scrollTop) < 1) {
  322. loadHistory.value = false
  323. refreshMessageList()
  324. }
  325. }, 200)
  326. /** 加载历史消息 */
  327. const handleOldMessage = async () => {
  328. // 记录已有页面高度
  329. const oldPageHeight = innerRef.value?.clientHeight
  330. if (!oldPageHeight) {
  331. return
  332. }
  333. loadHistory.value = true
  334. await getMessageList()
  335. // 等页面加载完后,获得上一页最后一条消息的位置,控制滚动到它所在位置
  336. scrollbarRef.value!.setScrollTop(innerRef.value!.clientHeight - oldPageHeight)
  337. }
  338. /**
  339. * 是否显示时间
  340. *
  341. * @param {*} item - 数据
  342. * @param {*} index - 索引
  343. */
  344. const showTime = computed(() => (item: KeFuMessageRespVO, index: number) => {
  345. if (unref(messageList.value)[index + 1]) {
  346. let dateString = dayjs(unref(messageList.value)[index + 1].createTime).fromNow()
  347. return dateString !== dayjs(unref(item).createTime).fromNow()
  348. }
  349. return false
  350. })
  351. </script>
  352. <style lang="scss" scoped>
  353. .kefu {
  354. background-color: #f5f5f5;
  355. position: relative;
  356. width: calc(100% - 300px - 260px);
  357. &::after {
  358. content: '';
  359. position: absolute;
  360. top: 0;
  361. left: 0;
  362. width: 1px; /* 实际宽度 */
  363. height: 100%;
  364. background-color: var(--el-border-color);
  365. transform: scaleX(0.3); /* 缩小宽度 */
  366. }
  367. .kefu-header {
  368. background-color: #f5f5f5;
  369. position: relative;
  370. display: flex;
  371. align-items: center;
  372. justify-content: space-between;
  373. &::before {
  374. content: '';
  375. position: absolute;
  376. bottom: 0;
  377. left: 0;
  378. width: 100%;
  379. height: 1px; /* 初始宽度 */
  380. background-color: var(--el-border-color);
  381. transform: scaleY(0.3); /* 缩小视觉高度 */
  382. }
  383. &-title {
  384. font-size: 18px;
  385. font-weight: bold;
  386. }
  387. }
  388. &-content {
  389. margin: 0;
  390. padding: 10px;
  391. position: relative;
  392. height: 100%;
  393. width: 100%;
  394. .newMessageTip {
  395. position: absolute;
  396. bottom: 35px;
  397. right: 35px;
  398. background-color: var(--app-content-bg-color);
  399. padding: 10px;
  400. border-radius: 30px;
  401. font-size: 12px;
  402. box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  403. }
  404. .ss-row-left {
  405. justify-content: flex-start;
  406. .kefu-message {
  407. background-color: #fff;
  408. margin-left: 10px;
  409. margin-top: 3px;
  410. border-top-right-radius: 10px;
  411. border-bottom-right-radius: 10px;
  412. border-bottom-left-radius: 10px;
  413. }
  414. }
  415. .ss-row-right {
  416. justify-content: flex-end;
  417. .kefu-message {
  418. background-color: rgb(206, 223, 255);
  419. margin-right: 10px;
  420. margin-top: 3px;
  421. border-top-left-radius: 10px;
  422. border-bottom-right-radius: 10px;
  423. border-bottom-left-radius: 10px;
  424. }
  425. }
  426. // 消息气泡
  427. .kefu-message {
  428. color: #414141;
  429. font-weight: 500;
  430. padding: 5px 10px;
  431. width: auto;
  432. max-width: 50%;
  433. //text-align: left;
  434. //display: inline-block !important;
  435. //word-break: break-all;
  436. transition: all 0.2s;
  437. &:hover {
  438. transform: scale(1.03);
  439. }
  440. }
  441. .date-message,
  442. .system-message {
  443. width: fit-content;
  444. background-color: rgba(0, 0, 0, 0.1);
  445. border-radius: 8px;
  446. padding: 0 5px;
  447. color: #fff;
  448. font-size: 10px;
  449. }
  450. }
  451. .kefu-footer {
  452. position: relative;
  453. display: flex;
  454. flex-direction: column;
  455. height: auto;
  456. margin: 0;
  457. padding: 0;
  458. &::before {
  459. content: '';
  460. position: absolute;
  461. top: 0;
  462. left: 0;
  463. width: 100%;
  464. height: 1px; /* 初始宽度 */
  465. background-color: var(--el-border-color);
  466. transform: scaleY(0.3); /* 缩小视觉高度 */
  467. }
  468. .chat-tools {
  469. width: 100%;
  470. height: 44px;
  471. }
  472. }
  473. ::v-deep(textarea) {
  474. resize: none;
  475. background-color: #f5f5f5;
  476. }
  477. :deep(.el-input__wrapper) {
  478. box-shadow: none !important;
  479. border-radius: 0;
  480. }
  481. ::v-deep(.el-textarea__inner) {
  482. box-shadow: none !important;
  483. }
  484. }
  485. </style>