chatBox.vue 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. return visiblePagesList.value.indexOf(index) > -1;
  210. };
  211. // 防抖
  212. function throttle(fnc, delay) {
  213. let timer;
  214. return function() {
  215. let _this = this;
  216. let args = arguments;
  217. if (!timer) {
  218. timer = setTimeout(() => {
  219. fnc.call(_this, args);
  220. timer = null;
  221. }, delay);
  222. }
  223. };
  224. }
  225. const isSendSuccess = ref(0); // 是否发送成功 -1=发送中|0=发送成功|1发送失败
  226. onLoad(() => {
  227. setPageHeight();
  228. observer(currentShowPage.value);
  229. });
  230. //======================= 工具函数 =======================
  231. /**
  232. * 是否显示时间
  233. * @param {*} item - 数据
  234. * @param {*} index - 索引
  235. */
  236. const showTime = (item, data, index) => {
  237. if (unref(data)[index + 1]) {
  238. let dateString = dayjs(unref(data)[index + 1].createTime).fromNow();
  239. return dateString !== dayjs(unref(item).createTime).fromNow();
  240. }
  241. return false;
  242. };
  243. // 处理表情
  244. function replaceEmoji(data) {
  245. let newData = data;
  246. if (typeof newData !== 'object') {
  247. let reg = /\[(.+?)\]/g; // [] 中括号
  248. let zhEmojiName = newData.match(reg);
  249. if (zhEmojiName) {
  250. zhEmojiName.forEach((item) => {
  251. let emojiFile = selEmojiFile(item);
  252. newData = newData.replace(
  253. item,
  254. `<img class="chat-img" style="width: 24px;height: 24px;margin: 0 3px;" src="${sheep.$url.cdn(
  255. '/static/img/chat/emoji/' + emojiFile,
  256. )}"/>`,
  257. );
  258. });
  259. }
  260. }
  261. return newData;
  262. }
  263. function selEmojiFile(name) {
  264. for (let index in emojiList) {
  265. if (emojiList[index].name === name) {
  266. return emojiList[index].file;
  267. }
  268. }
  269. return false;
  270. }
  271. </script>
  272. <style lang="scss" scoped>
  273. // scroll-view 倒置,也就是说顶部是底,底部才是顶,下拉加载旧数据,回到底部就是新数据
  274. .scroll {
  275. transform: rotate(180deg);
  276. & ::-webkit-scrollbar {
  277. display: none;
  278. width: 0;
  279. height: 0;
  280. color: transparent;
  281. }
  282. }
  283. // 内容区域也翻转一下
  284. .scroll-item {
  285. transform: rotate(180deg);
  286. }
  287. .go-back-btn {
  288. width: 100rpx;
  289. height: 60rpx;
  290. line-height: 60rpx;
  291. position: fixed;
  292. bottom: 100rpx;
  293. left: 80%;
  294. transform: translateX(-50%);
  295. text-align: center;
  296. background-color: lightblue;
  297. border-radius: 10rpx;
  298. }
  299. .chat-box {
  300. padding: 0 20rpx 0;
  301. .loadmore-btn {
  302. width: 98%;
  303. height: 40px;
  304. font-size: 12px;
  305. color: #8c8c8c;
  306. .loadmore-icon {
  307. transform: rotate(90deg);
  308. }
  309. }
  310. .message-item {
  311. margin-bottom: 33rpx;
  312. }
  313. .date-message,
  314. .system-message {
  315. width: fit-content;
  316. border-radius: 12rpx;
  317. padding: 8rpx 16rpx;
  318. margin-bottom: 16rpx;
  319. background-color: var(--ui-BG-3);
  320. color: #999;
  321. font-size: 24rpx;
  322. }
  323. .chat-avatar {
  324. width: 70rpx;
  325. height: 70rpx;
  326. border-radius: 50%;
  327. }
  328. .send-status {
  329. color: #333;
  330. height: 80rpx;
  331. margin-right: 8rpx;
  332. display: flex;
  333. align-items: center;
  334. .loading {
  335. width: 32rpx;
  336. height: 32rpx;
  337. -webkit-animation: rotating 2s linear infinite;
  338. animation: rotating 2s linear infinite;
  339. @-webkit-keyframes rotating {
  340. 0% {
  341. transform: rotateZ(0);
  342. }
  343. 100% {
  344. transform: rotateZ(360deg);
  345. }
  346. }
  347. @keyframes rotating {
  348. 0% {
  349. transform: rotateZ(0);
  350. }
  351. 100% {
  352. transform: rotateZ(360deg);
  353. }
  354. }
  355. }
  356. .warning {
  357. width: 32rpx;
  358. height: 32rpx;
  359. color: #ff3000;
  360. }
  361. }
  362. .message-box {
  363. max-width: 50%;
  364. font-size: 16px;
  365. line-height: 20px;
  366. // max-width: 500rpx;
  367. white-space: normal;
  368. word-break: break-all;
  369. word-wrap: break-word;
  370. padding: 20rpx;
  371. border-radius: 10rpx;
  372. color: #fff;
  373. background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
  374. &.admin {
  375. background: #fff;
  376. color: #333;
  377. }
  378. :deep() {
  379. .imgred {
  380. width: 100%;
  381. }
  382. .imgred,
  383. img {
  384. width: 100%;
  385. }
  386. }
  387. }
  388. :deep() {
  389. .goods,
  390. .order {
  391. max-width: 500rpx;
  392. }
  393. }
  394. .message-img {
  395. width: 100px;
  396. height: 100px;
  397. border-radius: 6rpx;
  398. }
  399. .template-wrap {
  400. // width: 100%;
  401. padding: 20rpx 24rpx;
  402. background: #fff;
  403. border-radius: 10rpx;
  404. .title {
  405. font-size: 26rpx;
  406. font-weight: 500;
  407. color: #333;
  408. margin-bottom: 29rpx;
  409. }
  410. .item {
  411. font-size: 24rpx;
  412. color: var(--ui-BG-Main);
  413. margin-bottom: 16rpx;
  414. &:last-of-type {
  415. margin-bottom: 0;
  416. }
  417. }
  418. }
  419. .error-img {
  420. width: 400rpx;
  421. height: 400rpx;
  422. }
  423. #scrollBottom {
  424. height: 120rpx;
  425. }
  426. }
  427. </style>