chatBox.vue 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. /**
  134. * uniapp 实现虚拟列表
  135. *
  136. * see https://juejin.cn/post/7105280477141041183
  137. */
  138. import { nextTick, reactive, ref, unref } from 'vue';
  139. import { onLoad } from '@dcloudio/uni-app';
  140. import sheep from '@/sheep';
  141. import KeFuApi from '@/sheep/api/promotion/kefu';
  142. import { isEmpty } from '@/sheep/helper/utils';
  143. import { KeFuMessageContentTypeEnum, UserTypeEnum } from '@/pages/chat/components/constants';
  144. import { formatDate } from '@/sheep/util';
  145. import dayjs from 'dayjs';
  146. import { emojiList } from '@/pages/chat/emoji';
  147. const { safeArea } = sheep.$platform.device;
  148. const pageHeight = safeArea.height - 44 - 35 - 50;
  149. const currentShowPage = ref(0); // 当前展示的页码
  150. const pagesHeight = reactive([]); // 记录每个页面的高度
  151. const visiblePagesList = ref([-1, 0, 1]);
  152. const scrollData = ref([]);
  153. // 向上滚动
  154. const upper = async () => {
  155. // 页数据满十条后加载下一页
  156. if (currentShowPage.value === 0 || scrollData.value[currentShowPage.value - 1].length === 10) {
  157. currentShowPage.value += 1;
  158. }
  159. await getMessageList();
  160. await nextTick();
  161. setPageHeight();
  162. observer(currentShowPage.value);
  163. };
  164. // 获得消息分页列表
  165. const getMessageList = async (pageNo = undefined) => {
  166. const { data } = await KeFuApi.getMessageListPage({
  167. pageNo: pageNo || currentShowPage.value,
  168. });
  169. if (isEmpty(data.list)) {
  170. return;
  171. }
  172. scrollData.value[pageNo ? pageNo - 1 : currentShowPage.value - 1] = data.list;
  173. };
  174. defineExpose({ getMessageList });
  175. const scrollTop = ref(0); // 当前滚动区域距离顶部的距离
  176. const currentTop = ref(0);
  177. const showGoBottom = ref(false);
  178. // 滚动条滚动时触发
  179. const handle_scroll = throttle(event => {
  180. scrollTop.value = event[0].detail.scrollTop;
  181. if (scrollTop > 300) {
  182. showGoBottom.value = true;
  183. }
  184. }, 100);
  185. const handle_goBottom = () => {
  186. currentTop.value = scrollTop.value;
  187. nextTick(() => {
  188. currentTop.value = 0;
  189. });
  190. showGoBottom.value = false;
  191. };
  192. // 获取每页数据的页面高度
  193. const setPageHeight = () => {
  194. let query = uni.createSelectorQuery();
  195. query
  196. .select(`#item-${currentShowPage.value}`)
  197. .boundingClientRect(res => {
  198. console.log(res);
  199. pagesHeight[currentShowPage.value] = res && res.height;
  200. })
  201. .exec();
  202. };
  203. const observer = pageNum => {
  204. const observeView = wx
  205. .createIntersectionObserver()
  206. .relativeTo('#scroll', { top: 0, bottom: 0 });
  207. observeView.observe(`#item-${pageNum}`, res => {
  208. if (res.intersectionRatio > 0) visiblePagesList.value = [pageNum - 1, pageNum, pageNum + 1];
  209. });
  210. };
  211. // 虚拟列表展示可视区域的数据
  212. const includePage = index => {
  213. return visiblePagesList.value.indexOf(index) > -1;
  214. };
  215. // 防抖
  216. function throttle(fnc, delay) {
  217. let timer;
  218. return function() {
  219. let _this = this;
  220. let args = arguments;
  221. if (!timer) {
  222. timer = setTimeout(() => {
  223. fnc.call(_this, args);
  224. timer = null;
  225. }, delay);
  226. }
  227. };
  228. }
  229. const isSendSuccess = ref(0); // 是否发送成功 -1=发送中|0=发送成功|1发送失败
  230. onLoad(() => {
  231. setPageHeight();
  232. observer(currentShowPage.value);
  233. });
  234. //======================= 工具函数 =======================
  235. /**
  236. * 是否显示时间
  237. * @param {*} item - 数据
  238. * @param {*} index - 索引
  239. */
  240. const showTime = (item, data, index) => {
  241. if (unref(data)[index + 1]) {
  242. let dateString = dayjs(unref(data)[index + 1].createTime).fromNow();
  243. return dateString !== dayjs(unref(item).createTime).fromNow();
  244. }
  245. return false;
  246. };
  247. // 处理表情
  248. function replaceEmoji(data) {
  249. let newData = data;
  250. if (typeof newData !== 'object') {
  251. let reg = /\[(.+?)\]/g; // [] 中括号
  252. let zhEmojiName = newData.match(reg);
  253. if (zhEmojiName) {
  254. zhEmojiName.forEach((item) => {
  255. let emojiFile = selEmojiFile(item);
  256. newData = newData.replace(
  257. item,
  258. `<img class="chat-img" style="width: 24px;height: 24px;margin: 0 3px;" src="${sheep.$url.cdn(
  259. '/static/img/chat/emoji/' + emojiFile,
  260. )}"/>`,
  261. );
  262. });
  263. }
  264. }
  265. return newData;
  266. }
  267. function selEmojiFile(name) {
  268. for (let index in emojiList) {
  269. if (emojiList[index].name === name) {
  270. return emojiList[index].file;
  271. }
  272. }
  273. return false;
  274. }
  275. </script>
  276. <style lang="scss" scoped>
  277. // scroll-view 倒置,也就是说顶部是底,底部才是顶,下拉加载旧数据,回到底部就是新数据
  278. .scroll {
  279. transform: rotate(180deg);
  280. & ::-webkit-scrollbar {
  281. display: none;
  282. width: 0;
  283. height: 0;
  284. color: transparent;
  285. }
  286. }
  287. // 内容区域也翻转一下
  288. .scroll-item {
  289. transform: rotate(180deg);
  290. }
  291. .go-back-btn {
  292. width: 100rpx;
  293. height: 60rpx;
  294. line-height: 60rpx;
  295. position: fixed;
  296. bottom: 100rpx;
  297. left: 80%;
  298. transform: translateX(-50%);
  299. text-align: center;
  300. background-color: lightblue;
  301. border-radius: 10rpx;
  302. }
  303. .chat-box {
  304. padding: 0 20rpx 0;
  305. .loadmore-btn {
  306. width: 98%;
  307. height: 40px;
  308. font-size: 12px;
  309. color: #8c8c8c;
  310. .loadmore-icon {
  311. transform: rotate(90deg);
  312. }
  313. }
  314. .message-item {
  315. margin-bottom: 33rpx;
  316. }
  317. .date-message,
  318. .system-message {
  319. width: fit-content;
  320. border-radius: 12rpx;
  321. padding: 8rpx 16rpx;
  322. margin-bottom: 16rpx;
  323. background-color: var(--ui-BG-3);
  324. color: #999;
  325. font-size: 24rpx;
  326. }
  327. .chat-avatar {
  328. width: 70rpx;
  329. height: 70rpx;
  330. border-radius: 50%;
  331. }
  332. .send-status {
  333. color: #333;
  334. height: 80rpx;
  335. margin-right: 8rpx;
  336. display: flex;
  337. align-items: center;
  338. .loading {
  339. width: 32rpx;
  340. height: 32rpx;
  341. -webkit-animation: rotating 2s linear infinite;
  342. animation: rotating 2s linear infinite;
  343. @-webkit-keyframes rotating {
  344. 0% {
  345. transform: rotateZ(0);
  346. }
  347. 100% {
  348. transform: rotateZ(360deg);
  349. }
  350. }
  351. @keyframes rotating {
  352. 0% {
  353. transform: rotateZ(0);
  354. }
  355. 100% {
  356. transform: rotateZ(360deg);
  357. }
  358. }
  359. }
  360. .warning {
  361. width: 32rpx;
  362. height: 32rpx;
  363. color: #ff3000;
  364. }
  365. }
  366. .message-box {
  367. max-width: 50%;
  368. font-size: 16px;
  369. line-height: 20px;
  370. // max-width: 500rpx;
  371. white-space: normal;
  372. word-break: break-all;
  373. word-wrap: break-word;
  374. padding: 20rpx;
  375. border-radius: 10rpx;
  376. color: #fff;
  377. background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
  378. &.admin {
  379. background: #fff;
  380. color: #333;
  381. }
  382. :deep() {
  383. .imgred {
  384. width: 100%;
  385. }
  386. .imgred,
  387. img {
  388. width: 100%;
  389. }
  390. }
  391. }
  392. :deep() {
  393. .goods,
  394. .order {
  395. max-width: 500rpx;
  396. }
  397. }
  398. .message-img {
  399. width: 100px;
  400. height: 100px;
  401. border-radius: 6rpx;
  402. }
  403. .template-wrap {
  404. // width: 100%;
  405. padding: 20rpx 24rpx;
  406. background: #fff;
  407. border-radius: 10rpx;
  408. .title {
  409. font-size: 26rpx;
  410. font-weight: 500;
  411. color: #333;
  412. margin-bottom: 29rpx;
  413. }
  414. .item {
  415. font-size: 24rpx;
  416. color: var(--ui-BG-Main);
  417. margin-bottom: 16rpx;
  418. &:last-of-type {
  419. margin-bottom: 0;
  420. }
  421. }
  422. }
  423. .error-img {
  424. width: 400rpx;
  425. height: 400rpx;
  426. }
  427. #scrollBottom {
  428. height: 120rpx;
  429. }
  430. }
  431. </style>