chatBox.vue 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. <template>
  2. <view class="chat-box" :style="{ height: pageHeight + 'px' }">
  3. <scroll-view
  4. :style="{ height: pageHeight + 'px' }"
  5. class="scroll"
  6. :scroll-y="true"
  7. :scroll-top="currentTop"
  8. @scroll="handle_scroll"
  9. @scrolltolower="upper"
  10. >
  11. <view v-for="(data, index) in scrollData" :key="index" :id="'item-' + index">
  12. <template v-if="includePage(index)">
  13. <!-- 消息渲染 -->
  14. <view class="message-item ss-flex-col scroll-item" v-for="(item, index2) in data" :key="index">
  15. <view class="ss-flex ss-row-center ss-col-center">
  16. <!-- 日期 -->
  17. <view v-if="item.contentType !== KeFuMessageContentTypeEnum.SYSTEM && showTime(item,data, index2)"
  18. class="date-message">
  19. {{ formatDate(item.createTime) }}
  20. </view>
  21. <!-- 系统消息 -->
  22. <view v-if="item.contentType === KeFuMessageContentTypeEnum.SYSTEM" class="system-message">
  23. {{ item.content }}
  24. </view>
  25. </view>
  26. <!-- 消息体渲染管理员消息和用户消息并左右展示 -->
  27. <view
  28. v-if="item.contentType !== KeFuMessageContentTypeEnum.SYSTEM"
  29. class="ss-flex ss-col-top"
  30. :class="[
  31. item.senderType === UserTypeEnum.ADMIN
  32. ? `ss-row-left`
  33. : item.senderType === UserTypeEnum.MEMBER
  34. ? `ss-row-right`
  35. : '',
  36. ]"
  37. >
  38. <!-- 客服头像 -->
  39. <image
  40. v-show="item.senderType === UserTypeEnum.ADMIN"
  41. class="chat-avatar ss-m-r-24"
  42. :src="
  43. sheep.$url.cdn(item?.senderAvatar) ||
  44. sheep.$url.static('/static/img/shop/chat/default.png')
  45. "
  46. mode="aspectFill"
  47. ></image>
  48. <!-- 发送状态 -->
  49. <span
  50. v-if="
  51. item.senderType === UserTypeEnum.MEMBER &&
  52. index == data.length - 1 &&
  53. isSendSuccess !== 0
  54. "
  55. class="send-status"
  56. >
  57. <image
  58. v-if="isSendSuccess == -1"
  59. class="loading"
  60. :src="sheep.$url.static('/static/img/shop/chat/loading.png')"
  61. mode="aspectFill"
  62. ></image>
  63. <!-- <image
  64. v-if="chatData.isSendSuccess == 1"
  65. class="warning"
  66. :src="sheep.$url.static('/static/img/shop/chat/warning.png')"
  67. mode="aspectFill"
  68. @click="onAgainSendMessage(item)"
  69. ></image> -->
  70. </span>
  71. <!-- 内容 -->
  72. <template v-if="item.contentType === KeFuMessageContentTypeEnum.TEXT">
  73. <view class="message-box" :class="{'admin': item.senderType === UserTypeEnum.ADMIN}">
  74. <mp-html :content="replaceEmoji(item.content)" />
  75. </view>
  76. </template>
  77. <template v-if="item.contentType === KeFuMessageContentTypeEnum.IMAGE">
  78. <view class="message-box" :class="{'admin': item.senderType === UserTypeEnum.ADMIN}"
  79. :style="{ width: '200rpx' }">
  80. <su-image
  81. class="message-img"
  82. isPreview
  83. :previewList="[sheep.$url.cdn(item.content)]"
  84. :current="0"
  85. :src="sheep.$url.cdn(item.content)"
  86. :height="200"
  87. :width="200"
  88. mode="aspectFill"
  89. ></su-image>
  90. </view>
  91. </template>
  92. <!-- <template v-if="item.contentType === KeFuMessageContentTypeEnum.PRODUCT">-->
  93. <!-- <GoodsItem-->
  94. <!-- :goodsData="item.content.item"-->
  95. <!-- @tap="-->
  96. <!-- sheep.$router.go('/pages/goods/index', {-->
  97. <!-- id: item.content.item.id,-->
  98. <!-- })-->
  99. <!-- "-->
  100. <!-- />-->
  101. <!-- </template>-->
  102. <!-- <template v-if="item.contentType === KeFuMessageContentTypeEnum.ORDER">-->
  103. <!-- <OrderItem-->
  104. <!-- from="msg"-->
  105. <!-- :orderData="item.content.item"-->
  106. <!-- @tap="-->
  107. <!-- sheep.$router.go('/pages/order/detail', {-->
  108. <!-- id: item.content.item.id,-->
  109. <!-- })-->
  110. <!-- "-->
  111. <!-- />-->
  112. <!-- </template>-->
  113. <!-- user头像 -->
  114. <image
  115. v-if="item.senderType === UserTypeEnum.MEMBER"
  116. class="chat-avatar ss-m-l-24"
  117. :src="sheep.$url.cdn(item?.senderAvatar) ||
  118. sheep.$url.static('/static/img/shop/chat/default.png')"
  119. mode="aspectFill"
  120. >
  121. </image>
  122. </view>
  123. </view>
  124. </template>
  125. <view v-if="!includePage(index)" :style="{ height: pagesHeight[index] }"></view>
  126. </view>
  127. </scroll-view>
  128. <!-- TODO puhui999: 这里还有一点问题 -->
  129. <view v-show="showGoBottom" class="go-back-btn" @click="handle_goBottom">查看最新消息</view>
  130. </view>
  131. </template>
  132. <script setup>
  133. import { nextTick, onMounted,onBeforeUnmount, reactive, ref, unref } from 'vue';
  134. import { onLoad } from '@dcloudio/uni-app';
  135. import sheep from '@/sheep';
  136. import KeFuApi from '@/sheep/api/promotion/kefu';
  137. import { isEmpty } from '@/sheep/helper/utils';
  138. import { KeFuMessageContentTypeEnum, UserTypeEnum } from '@/pages/chat/components/constants';
  139. import { formatDate } from '@/sheep/util';
  140. import dayjs from 'dayjs';
  141. import { emojiList } from '@/pages/chat/emoji';
  142. const { safeArea } = sheep.$platform.device;
  143. const pageHeight = safeArea.height - 44 - 35 - 50;
  144. const currentShowPage = ref(0); // 当前展示的页码
  145. const pagesHeight = reactive([]); // 记录每个页面的高度
  146. const visiblePagesList = ref([-1, 0, 1]);
  147. const scrollData = ref([]);
  148. // 向上滚动
  149. const upper = async () => {
  150. // 页数据满十条后加载下一页
  151. if (currentShowPage.value === 0 || scrollData.value[currentShowPage.value - 1].length === 10) {
  152. currentShowPage.value += 1;
  153. }
  154. await getMessageList();
  155. await nextTick();
  156. setPageHeight();
  157. observer(currentShowPage.value);
  158. };
  159. // 获得消息分页列表
  160. const getMessageList = async (pageNo = undefined) => {
  161. const { data } = await KeFuApi.getKefuMessagePage({
  162. pageNo: pageNo || currentShowPage.value,
  163. });
  164. if (isEmpty(data.list)) {
  165. return;
  166. }
  167. scrollData.value[pageNo ? pageNo - 1 : currentShowPage.value - 1] = data.list;
  168. };
  169. defineExpose({ getMessageList });
  170. const poller = ref(null) // TODO puhui999: 轮训定时器,暂时模拟 websocket
  171. onMounted(() => {
  172. // TODO puhui999: 轮训相关,功能完善后移除
  173. if (!poller.value) {
  174. poller.value = setInterval(() => {
  175. getMessageList(1)
  176. }, 1000)
  177. }
  178. })
  179. // TODO puhui999: 轮训相关,功能完善后移除
  180. onBeforeUnmount(() => {
  181. if (!poller.value) {
  182. return
  183. }
  184. clearInterval(poller.value)
  185. })
  186. const scrollTop = ref(0); // 当前滚动区域距离顶部的距离
  187. const currentTop = ref(0);
  188. const showGoBottom = ref(false);
  189. // 滚动条滚动时触发
  190. const handle_scroll = throttle(event => {
  191. scrollTop.value = event[0].detail.scrollTop;
  192. if (scrollTop > 300) {
  193. showGoBottom.value = true;
  194. }
  195. }, 100);
  196. const handle_goBottom = () => {
  197. currentTop.value = scrollTop.value;
  198. nextTick(() => {
  199. currentTop.value = 0;
  200. });
  201. showGoBottom.value = false;
  202. };
  203. // 获取每页数据的页面高度
  204. const setPageHeight = () => {
  205. let query = uni.createSelectorQuery();
  206. query
  207. .select(`#item-${currentShowPage.value}`)
  208. .boundingClientRect(res => {
  209. console.log(res);
  210. pagesHeight[currentShowPage.value] = res && res.height;
  211. })
  212. .exec();
  213. };
  214. const observer = pageNum => {
  215. const observeView = wx
  216. .createIntersectionObserver()
  217. .relativeTo('#scroll', { top: 0, bottom: 0 });
  218. observeView.observe(`#item-${pageNum}`, res => {
  219. if (res.intersectionRatio > 0) visiblePagesList.value = [pageNum - 1, pageNum, pageNum + 1];
  220. });
  221. };
  222. // 虚拟列表展示可视区域的数据
  223. const includePage = index => {
  224. return visiblePagesList.value.indexOf(index) > -1;
  225. };
  226. // 防抖
  227. function throttle(fnc, delay) {
  228. let timer;
  229. return function() {
  230. let _this = this;
  231. let args = arguments;
  232. if (!timer) {
  233. timer = setTimeout(() => {
  234. fnc.call(_this, args);
  235. timer = null;
  236. }, delay);
  237. }
  238. };
  239. }
  240. const isSendSuccess = ref(0); // 是否发送成功 -1=发送中|0=发送成功|1发送失败
  241. onLoad(() => {
  242. setPageHeight();
  243. observer(currentShowPage.value);
  244. });
  245. //======================= 工具函数 =======================
  246. /**
  247. * 是否显示时间
  248. * @param {*} item - 数据
  249. * @param {*} index - 索引
  250. */
  251. const showTime = (item, data, index) => {
  252. if (unref(data)[index + 1]) {
  253. let dateString = dayjs(unref(data)[index + 1].createTime).fromNow();
  254. return dateString !== dayjs(unref(item).createTime).fromNow();
  255. }
  256. return false;
  257. };
  258. // 处理表情
  259. function replaceEmoji(data) {
  260. let newData = data;
  261. if (typeof newData !== 'object') {
  262. let reg = /\[(.+?)\]/g; // [] 中括号
  263. let zhEmojiName = newData.match(reg);
  264. if (zhEmojiName) {
  265. zhEmojiName.forEach((item) => {
  266. let emojiFile = selEmojiFile(item);
  267. newData = newData.replace(
  268. item,
  269. `<img class="chat-img" style="width: 24px;height: 24px;margin: 0 3px;" src="${sheep.$url.cdn(
  270. '/static/img/chat/emoji/' + emojiFile,
  271. )}"/>`,
  272. );
  273. });
  274. }
  275. }
  276. return newData;
  277. }
  278. function selEmojiFile(name) {
  279. for (let index in emojiList) {
  280. if (emojiList[index].name === name) {
  281. return emojiList[index].file;
  282. }
  283. }
  284. return false;
  285. }
  286. </script>
  287. <style lang="scss" scoped>
  288. // scroll-view 倒置,也就是说顶部是底,底部才是顶,下拉加载旧数据,回到底部就是新数据
  289. .scroll {
  290. transform: rotate(180deg);
  291. & ::-webkit-scrollbar {
  292. display: none;
  293. width: 0;
  294. height: 0;
  295. color: transparent;
  296. }
  297. }
  298. // 内容区域也翻转一下
  299. .scroll-item {
  300. transform: rotate(180deg);
  301. }
  302. .go-back-btn {
  303. width: 100rpx;
  304. height: 60rpx;
  305. line-height: 60rpx;
  306. position: fixed;
  307. bottom: 100rpx;
  308. left: 80%;
  309. transform: translateX(-50%);
  310. text-align: center;
  311. background-color: lightblue;
  312. border-radius: 10rpx;
  313. }
  314. .chat-box {
  315. padding: 0 20rpx 0;
  316. .loadmore-btn {
  317. width: 98%;
  318. height: 40px;
  319. font-size: 12px;
  320. color: #8c8c8c;
  321. .loadmore-icon {
  322. transform: rotate(90deg);
  323. }
  324. }
  325. .message-item {
  326. margin-bottom: 33rpx;
  327. }
  328. .date-message,
  329. .system-message {
  330. width: fit-content;
  331. border-radius: 12rpx;
  332. padding: 8rpx 16rpx;
  333. margin-bottom: 16rpx;
  334. background-color: var(--ui-BG-3);
  335. color: #999;
  336. font-size: 24rpx;
  337. }
  338. .chat-avatar {
  339. width: 70rpx;
  340. height: 70rpx;
  341. border-radius: 50%;
  342. }
  343. .send-status {
  344. color: #333;
  345. height: 80rpx;
  346. margin-right: 8rpx;
  347. display: flex;
  348. align-items: center;
  349. .loading {
  350. width: 32rpx;
  351. height: 32rpx;
  352. -webkit-animation: rotating 2s linear infinite;
  353. animation: rotating 2s linear infinite;
  354. @-webkit-keyframes rotating {
  355. 0% {
  356. transform: rotateZ(0);
  357. }
  358. 100% {
  359. transform: rotateZ(360deg);
  360. }
  361. }
  362. @keyframes rotating {
  363. 0% {
  364. transform: rotateZ(0);
  365. }
  366. 100% {
  367. transform: rotateZ(360deg);
  368. }
  369. }
  370. }
  371. .warning {
  372. width: 32rpx;
  373. height: 32rpx;
  374. color: #ff3000;
  375. }
  376. }
  377. .message-box {
  378. max-width: 50%;
  379. font-size: 16px;
  380. line-height: 20px;
  381. // max-width: 500rpx;
  382. white-space: normal;
  383. word-break: break-all;
  384. word-wrap: break-word;
  385. padding: 20rpx;
  386. border-radius: 10rpx;
  387. color: #fff;
  388. background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
  389. &.admin {
  390. background: #fff;
  391. color: #333;
  392. }
  393. :deep() {
  394. .imgred {
  395. width: 100%;
  396. }
  397. .imgred,
  398. img {
  399. width: 100%;
  400. }
  401. }
  402. }
  403. :deep() {
  404. .goods,
  405. .order {
  406. max-width: 500rpx;
  407. }
  408. }
  409. .message-img {
  410. width: 100px;
  411. height: 100px;
  412. border-radius: 6rpx;
  413. }
  414. .template-wrap {
  415. // width: 100%;
  416. padding: 20rpx 24rpx;
  417. background: #fff;
  418. border-radius: 10rpx;
  419. .title {
  420. font-size: 26rpx;
  421. font-weight: 500;
  422. color: #333;
  423. margin-bottom: 29rpx;
  424. }
  425. .item {
  426. font-size: 24rpx;
  427. color: var(--ui-BG-Main);
  428. margin-bottom: 16rpx;
  429. &:last-of-type {
  430. margin-bottom: 0;
  431. }
  432. }
  433. }
  434. .error-img {
  435. width: 400rpx;
  436. height: 400rpx;
  437. }
  438. #scrollBottom {
  439. height: 120rpx;
  440. }
  441. }
  442. </style>