KeFuMessageList.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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))) {
  267. messageTool.notifyWarning('请输入消息后再发送哦!')
  268. return
  269. }
  270. // 2. 组织发送消息
  271. const msg = {
  272. conversationId: conversation.value.id,
  273. contentType: KeFuMessageContentTypeEnum.TEXT,
  274. content: JSON.stringify({ text: message.value })
  275. }
  276. await sendMessage(msg)
  277. }
  278. /** 真正发送消息 【共用】*/
  279. const sendMessage = async (msg: any) => {
  280. // 发送消息
  281. await KeFuMessageApi.sendKeFuMessage(msg)
  282. message.value = ''
  283. // 加载消息列表
  284. await refreshMessageList()
  285. // 更新会话缓存
  286. await kefuStore.updateConversation(conversation.value.id)
  287. }
  288. /** 滚动到底部 */
  289. const innerRef = ref<HTMLDivElement>()
  290. const scrollbarRef = ref<InstanceType<typeof ElScrollbarType>>()
  291. const scrollToBottom = async () => {
  292. // 1. 首次加载时滚动到最新消息,如果加载的是历史消息则不滚动
  293. if (loadHistory.value) {
  294. return
  295. }
  296. // 2.1 滚动到最新消息,关闭新消息提示
  297. await nextTick()
  298. scrollbarRef.value!.setScrollTop(innerRef.value!.clientHeight)
  299. showNewMessageTip.value = false
  300. // 2.2 消息已读
  301. await KeFuMessageApi.updateKeFuMessageReadStatus(conversation.value.id)
  302. }
  303. /** 查看新消息 */
  304. const handleToNewMessage = async () => {
  305. loadHistory.value = false
  306. await scrollToBottom()
  307. }
  308. const loadHistory = ref(false) // 加载历史消息
  309. /** 处理消息列表滚动事件(debounce 限流) */
  310. const handleScroll = debounce(({ scrollTop }) => {
  311. if (skipGetMessageList.value) {
  312. return
  313. }
  314. // 触顶自动加载下一页数据
  315. if (Math.floor(scrollTop) === 0) {
  316. handleOldMessage()
  317. }
  318. const wrap = scrollbarRef.value?.wrapRef
  319. // 触底重置
  320. if (Math.abs(wrap!.scrollHeight - wrap!.clientHeight - wrap!.scrollTop) < 1) {
  321. loadHistory.value = false
  322. refreshMessageList()
  323. }
  324. }, 200)
  325. /** 加载历史消息 */
  326. const handleOldMessage = async () => {
  327. // 记录已有页面高度
  328. const oldPageHeight = innerRef.value?.clientHeight
  329. if (!oldPageHeight) {
  330. return
  331. }
  332. loadHistory.value = true
  333. await getMessageList()
  334. // 等页面加载完后,获得上一页最后一条消息的位置,控制滚动到它所在位置
  335. scrollbarRef.value!.setScrollTop(innerRef.value!.clientHeight - oldPageHeight)
  336. }
  337. /**
  338. * 是否显示时间
  339. *
  340. * @param {*} item - 数据
  341. * @param {*} index - 索引
  342. */
  343. const showTime = computed(() => (item: KeFuMessageRespVO, index: number) => {
  344. if (unref(messageList.value)[index + 1]) {
  345. let dateString = dayjs(unref(messageList.value)[index + 1].createTime).fromNow()
  346. return dateString !== dayjs(unref(item).createTime).fromNow()
  347. }
  348. return false
  349. })
  350. </script>
  351. <style lang="scss" scoped>
  352. .kefu {
  353. background-color: #f5f5f5;
  354. position: relative;
  355. width: calc(100% - 300px - 260px);
  356. &::after {
  357. content: '';
  358. position: absolute;
  359. top: 0;
  360. left: 0;
  361. width: 1px; /* 实际宽度 */
  362. height: 100%;
  363. background-color: var(--el-border-color);
  364. transform: scaleX(0.3); /* 缩小宽度 */
  365. }
  366. .kefu-header {
  367. background-color: #f5f5f5;
  368. position: relative;
  369. display: flex;
  370. align-items: center;
  371. justify-content: space-between;
  372. &::before {
  373. content: '';
  374. position: absolute;
  375. bottom: 0;
  376. left: 0;
  377. width: 100%;
  378. height: 1px; /* 初始宽度 */
  379. background-color: var(--el-border-color);
  380. transform: scaleY(0.3); /* 缩小视觉高度 */
  381. }
  382. &-title {
  383. font-size: 18px;
  384. font-weight: bold;
  385. }
  386. }
  387. &-content {
  388. margin: 0;
  389. padding: 10px;
  390. position: relative;
  391. height: 100%;
  392. width: 100%;
  393. .newMessageTip {
  394. position: absolute;
  395. bottom: 35px;
  396. right: 35px;
  397. background-color: var(--app-content-bg-color);
  398. padding: 10px;
  399. border-radius: 30px;
  400. font-size: 12px;
  401. box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  402. }
  403. .ss-row-left {
  404. justify-content: flex-start;
  405. .kefu-message {
  406. background-color: #fff;
  407. margin-left: 10px;
  408. margin-top: 3px;
  409. border-top-right-radius: 10px;
  410. border-bottom-right-radius: 10px;
  411. border-bottom-left-radius: 10px;
  412. }
  413. }
  414. .ss-row-right {
  415. justify-content: flex-end;
  416. .kefu-message {
  417. background-color: rgb(206, 223, 255);
  418. margin-right: 10px;
  419. margin-top: 3px;
  420. border-top-left-radius: 10px;
  421. border-bottom-right-radius: 10px;
  422. border-bottom-left-radius: 10px;
  423. }
  424. }
  425. // 消息气泡
  426. .kefu-message {
  427. color: #414141;
  428. font-weight: 500;
  429. padding: 5px 10px;
  430. width: auto;
  431. max-width: 50%;
  432. //text-align: left;
  433. //display: inline-block !important;
  434. //word-break: break-all;
  435. transition: all 0.2s;
  436. &:hover {
  437. transform: scale(1.03);
  438. }
  439. }
  440. .date-message,
  441. .system-message {
  442. width: fit-content;
  443. background-color: rgba(0, 0, 0, 0.1);
  444. border-radius: 8px;
  445. padding: 0 5px;
  446. color: #fff;
  447. font-size: 10px;
  448. }
  449. }
  450. .kefu-footer {
  451. position: relative;
  452. display: flex;
  453. flex-direction: column;
  454. height: auto;
  455. margin: 0;
  456. padding: 0;
  457. &::before {
  458. content: '';
  459. position: absolute;
  460. top: 0;
  461. left: 0;
  462. width: 100%;
  463. height: 1px; /* 初始宽度 */
  464. background-color: var(--el-border-color);
  465. transform: scaleY(0.3); /* 缩小视觉高度 */
  466. }
  467. .chat-tools {
  468. width: 100%;
  469. height: 44px;
  470. }
  471. }
  472. ::v-deep(textarea) {
  473. resize: none;
  474. background-color: #f5f5f5;
  475. }
  476. :deep(.el-input__wrapper) {
  477. box-shadow: none !important;
  478. border-radius: 0;
  479. }
  480. ::v-deep(.el-textarea__inner) {
  481. box-shadow: none !important;
  482. }
  483. }
  484. </style>