chatBox.vue 13 KB

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