chat-box.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. <template>
  2. <view class=" page chat-box">
  3. <view class="header">
  4. <uni-icons class="btn-side left" type="back" size="30" @click="onNavBack()"></uni-icons>
  5. <text class="title">{{title}}</text>
  6. <uni-icons class="btn-side right" type="more-filled" size="30" @click="onShowMore()"></uni-icons>
  7. </view>
  8. <view class="chat-msg" @click="switchChatTabBox('none',true)">
  9. <scroll-view class="scroll-box" scroll-y="true" @scrolltoupper="onScrollToTop"
  10. :scroll-into-view="'chat-item-'+scrollMsgIdx">
  11. <view v-for="(msgInfo,idx) in chat.messages" :key="idx">
  12. <chat-message-item v-if="idx>=showMinIdx" :headImage="headImage(msgInfo)" :showName="showName(msgInfo)"
  13. @recall="onRecallMessage" @delete="onDeleteMessage" @download="onDownloadFile"
  14. :id="'chat-item-'+idx" :msgInfo="msgInfo">
  15. </chat-message-item>
  16. </view>
  17. </scroll-view>
  18. </view>
  19. <view class="send-bar">
  20. <view class="iconfont icon-voice-circle" @click="showTip()"></view>
  21. <view class="send-text">
  22. <textarea class="send-text-area" v-model="sendText" auto-height :show-confirm-bar="false"
  23. :adjust-position="false" @confirm="sendTextMessage()" @keyboardheightchange="onKeyboardheightchange"
  24. confirm-type="send" confirm-hold :hold-keyboard="true"></textarea>
  25. </view>
  26. <view class="iconfont icon-icon_emoji" @click="switchChatTabBox('emo',true)"></view>
  27. <view v-show="sendText==''" class="iconfont icon-add" @click="switchChatTabBox('tools',true)">
  28. </view>
  29. <button v-show="sendText!=''" class="btn-send" type="primary" @touchend.prevent="sendTextMessage()"
  30. size="mini">发送</button>
  31. </view>
  32. <view class="chat-tab-bar" v-show="chatTabBox!='none' ||showKeyBoard " :style="{height:`${keyboardHeight}px`}">
  33. <view v-if="chatTabBox == 'tools'" class="chat-tools">
  34. <view class="chat-tools-item">
  35. <image-upload :maxCount="9" sourceType="album" :onBefore="onUploadImageBefore"
  36. :onSuccess="onUploadImageSuccess" :onError="onUploadImageFail">
  37. <view class="tool-icon iconfont icon-picture"></view>
  38. </image-upload>
  39. <view class="tool-name">相册</view>
  40. </view>
  41. <view class="chat-tools-item">
  42. <image-upload sourceType="camera" :onBefore="onUploadImageBefore" :onSuccess="onUploadImageSuccess"
  43. :onError="onUploadImageFail">
  44. <view class="tool-icon iconfont icon-camera"></view>
  45. </image-upload>
  46. <view class="tool-name">拍摄</view>
  47. </view>
  48. <view class="chat-tools-item">
  49. <file-upload :onBefore="onUploadFileBefore" :onSuccess="onUploadFileSuccess"
  50. :onError="onUploadFileFail">
  51. <view class="tool-icon iconfont icon-folder"></view>
  52. </file-upload>
  53. <view class="tool-name">文件</view>
  54. </view>
  55. <view class="chat-tools-item" @click="showTip()">
  56. <view class="tool-icon iconfont icon-microphone"></view>
  57. <view class="tool-name">语音输入</view>
  58. </view>
  59. <view class="chat-tools-item" @click="showTip()">
  60. <view class="tool-icon iconfont icon-call"></view>
  61. <view class="tool-name">呼叫</view>
  62. </view>
  63. </view>
  64. <scroll-view v-if="chatTabBox==='emo'" class="chat-emotion" scroll-y="true">
  65. <view class="emotion-item-list">
  66. <image class="emotion-item" :title="emoText" :src="$emo.textToPath(emoText)"
  67. v-for="(emoText, i) in $emo.emoTextList" :key="i" @click="selectEmoji(emoText)" mode="aspectFit"
  68. lazy-load="true"></image>
  69. </view>
  70. </scroll-view>
  71. <view v-if="showKeyBoard"></view>
  72. </view>
  73. </view>
  74. </template>
  75. <script>
  76. export default {
  77. data() {
  78. return {
  79. chat: {},
  80. friend: {},
  81. group: {},
  82. groupMembers: [],
  83. sendText: "",
  84. showVoice: false, // 是否显示语音录制弹窗
  85. scrollMsgIdx: 0, // 滚动条定位为到哪条消息
  86. chatTabBox: 'none',
  87. showKeyBoard: false,
  88. keyboardHeight: 322,
  89. showMinIdx: 0 // 下标小于showMinIdx的消息不显示,否则可能很卡
  90. }
  91. },
  92. methods: {
  93. showTip() {
  94. uni.showToast({
  95. title: "加班开发中...",
  96. icon: "none"
  97. })
  98. },
  99. headImage(msgInfo) {
  100. if (this.chat.type == 'GROUP') {
  101. let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
  102. return member ? member.headImage : "";
  103. } else {
  104. return msgInfo.selfSend ? this.mine.headImageThumb : this.chat.headImage
  105. }
  106. },
  107. showName(msgInfo) {
  108. if (this.chat.type == 'GROUP') {
  109. let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
  110. return member ? member.aliasName : "";
  111. } else {
  112. return msgInfo.selfSend ? this.mine.nickName : this.chat.showName
  113. }
  114. },
  115. sendTextMessage() {
  116. if (!this.sendText.trim()) {
  117. return uni.showToast({
  118. title: "不能发送空白信息",
  119. icon: "none"
  120. });
  121. }
  122. let msgInfo = {
  123. content: this.sendText,
  124. type: 0
  125. }
  126. // 填充对方id
  127. this.fillTargetId(msgInfo, this.chat.targetId);
  128. this.sendText = "";
  129. this.$http({
  130. url: this.messageAction,
  131. method: 'POST',
  132. data: msgInfo
  133. }).then((id) => {
  134. msgInfo.id = id;
  135. msgInfo.sendTime = new Date().getTime();
  136. msgInfo.sendId = this.$store.state.userStore.userInfo.id;
  137. msgInfo.selfSend = true;
  138. msgInfo.status = this.$enums.MESSAGE_STATUS.UNSEND;
  139. this.$store.commit("insertMessage", msgInfo);
  140. this.sendText = "";
  141. }).finally(() => {
  142. // 滚动到底部
  143. this.scrollToBottom();
  144. });
  145. },
  146. fillTargetId(msgInfo, targetId) {
  147. if (this.chat.type == "GROUP") {
  148. msgInfo.groupId = targetId;
  149. } else {
  150. msgInfo.recvId = targetId;
  151. }
  152. },
  153. scrollToBottom() {
  154. let size = this.chat.messages.length;
  155. if (size > 0) {
  156. this.scrollToMsgIdx(size - 1);
  157. }
  158. },
  159. scrollToMsgIdx(idx) {
  160. // 如果scrollMsgIdx值没变化,滚动条不会移动
  161. if (idx == this.scrollMsgIdx && idx > 0) {
  162. this.$nextTick(() => {
  163. // 先滚动到上一条
  164. this.scrollMsgIdx = idx - 1;
  165. // 再滚动目标位置
  166. this.scrollToMsgIdx(idx);
  167. });
  168. return;
  169. }
  170. this.$nextTick(() => {
  171. console.log("scrollToMsgIdx",this.scrollMsgIdx)
  172. this.scrollMsgIdx = idx;
  173. });
  174. },
  175. switchChatTabBox(chatTabBox, hideKeyBoard) {
  176. this.chatTabBox = chatTabBox;
  177. if (hideKeyBoard) {
  178. uni.hideKeyboard();
  179. }
  180. },
  181. selectEmoji(emoText) {
  182. this.sendText += `#${emoText};`;
  183. },
  184. onNavBack() {
  185. uni.switchTab({
  186. url: "/pages/chat/chat"
  187. })
  188. },
  189. onKeyboardheightchange(e) {
  190. if (e.detail.height > 0) {
  191. this.showKeyBoard = true;
  192. this.switchChatTabBox('none', false)
  193. this.keyboardHeight = this.rpxTopx(e.detail.height);
  194. } else {
  195. this.showKeyBoard = false;
  196. }
  197. },
  198. onUploadImageBefore(file) {
  199. let data = {
  200. originUrl: file.path,
  201. thumbUrl: file.path
  202. }
  203. let msgInfo = {
  204. id: 0,
  205. fileId: file.uid,
  206. sendId: this.mine.id,
  207. content: JSON.stringify(data),
  208. sendTime: new Date().getTime(),
  209. selfSend: true,
  210. type: this.$enums.MESSAGE_TYPE.IMAGE,
  211. loadStatus: "loading",
  212. status: this.$enums.MESSAGE_STATUS.UNSEND
  213. }
  214. // 填充对方id
  215. this.fillTargetId(msgInfo, this.chat.targetId);
  216. // 插入消息
  217. this.$store.commit("insertMessage", msgInfo);
  218. // 借助file对象保存
  219. file.msgInfo = msgInfo;
  220. // 滚到最低部
  221. this.scrollToBottom();
  222. return true;
  223. },
  224. onUploadImageSuccess(file, res) {
  225. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  226. msgInfo.content = JSON.stringify(res.data);
  227. this.$http({
  228. url: this.messageAction,
  229. method: 'POST',
  230. data: msgInfo
  231. }).then((id) => {
  232. msgInfo.loadStatus = 'ok';
  233. msgInfo.id = id;
  234. this.$store.commit("insertMessage", msgInfo);
  235. })
  236. },
  237. onUploadImageFail(file, err) {
  238. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  239. msgInfo.loadStatus = 'fail';
  240. this.$store.commit("insertMessage", msgInfo);
  241. },
  242. onUploadFileBefore(file) {
  243. let data = {
  244. name: file.name,
  245. size: file.size,
  246. url: file.path
  247. }
  248. let msgInfo = {
  249. id: 0,
  250. sendId: this.mine.id,
  251. content: JSON.stringify(data),
  252. sendTime: new Date().getTime(),
  253. selfSend: true,
  254. type: this.$enums.MESSAGE_TYPE.FILE,
  255. loadStatus: "loading",
  256. status: this.$enums.MESSAGE_STATUS.UNSEND
  257. }
  258. // 填充对方id
  259. this.fillTargetId(msgInfo, this.chat.targetId);
  260. // 插入消息
  261. this.$store.commit("insertMessage", msgInfo);
  262. // 借助file对象保存
  263. file.msgInfo = msgInfo;
  264. // 滚到最低部
  265. this.scrollToBottom();
  266. return true;
  267. },
  268. onUploadFileSuccess(file, res) {
  269. let data = {
  270. name: file.name,
  271. size: file.size,
  272. url: res.data
  273. }
  274. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  275. msgInfo.content = JSON.stringify(data);
  276. this.$http({
  277. url: this.messageAction,
  278. method: 'POST',
  279. data: msgInfo
  280. }).then((id) => {
  281. msgInfo.loadStatus = 'ok';
  282. msgInfo.id = id;
  283. this.$store.commit("insertMessage", msgInfo);
  284. })
  285. },
  286. onUploadFileFail(file, res) {
  287. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  288. msgInfo.loadStatus = 'fail';
  289. this.$store.commit("insertMessage", msgInfo);
  290. },
  291. onDeleteMessage(msgInfo) {
  292. uni.showModal({
  293. title: '删除消息',
  294. content: '确认删除消息?',
  295. success: (res) => {
  296. if (!res.cancel) {
  297. this.$store.commit("deleteMessage", msgInfo);
  298. uni.showToast({
  299. title: "删除成功",
  300. icon: "none"
  301. })
  302. }
  303. }
  304. })
  305. },
  306. onRecallMessage(msgInfo) {
  307. uni.showModal({
  308. title: '撤回消息',
  309. content: '确认撤回消息?',
  310. success: (res) => {
  311. if (!res.cancel) {
  312. let url = `/message/${this.chat.type.toLowerCase()}/recall/${msgInfo.id}`
  313. this.$http({
  314. url: url,
  315. method: 'DELETE'
  316. }).then(() => {
  317. msgInfo = JSON.parse(JSON.stringify(msgInfo));
  318. msgInfo.type = this.$enums.MESSAGE_TYPE.RECALL;
  319. msgInfo.content = '你撤回了一条消息';
  320. msgInfo.status = this.$enums.MESSAGE_STATUS.RECALL;
  321. this.$store.commit("insertMessage", msgInfo);
  322. })
  323. }
  324. }
  325. })
  326. },
  327. onDownloadFile(msgInfo) {
  328. let url = JSON.parse(msgInfo.content).url;
  329. uni.downloadFile({
  330. url: url,
  331. success(res) {
  332. if (res.statusCode === 200) {
  333. var filePath = encodeURI(res.tempFilePath);
  334. uni.openDocument({
  335. filePath: filePath,
  336. showMenu: true
  337. });
  338. }
  339. },
  340. fail(e) {
  341. console.log(e);
  342. uni.showToast({
  343. title: "文件下载失败",
  344. icon: "none"
  345. })
  346. }
  347. });
  348. },
  349. onScrollToTop() {
  350. // #ifdef MP
  351. // 防止滚动条定格在顶部,不能一直往上滚
  352. this.scrollToMsgIdx(this.showMinIdx);
  353. // #endif
  354. // 多展示10条信息
  355. this.showMinIdx = this.showMinIdx > 10 ? this.showMinIdx - 10 : 0;
  356. },
  357. onShowMore() {
  358. if (this.chat.type == "GROUP") {
  359. uni.navigateTo({
  360. url: "/pages/group/group-info?id=" + this.group.id
  361. })
  362. } else {
  363. uni.navigateTo({
  364. url: "/pages/common/user-info?id=" + this.friend.id
  365. })
  366. }
  367. },
  368. readedMessage() {
  369. if (this.chat.type == "GROUP") {
  370. var url = `/message/group/readed?groupId=${this.chat.targetId}`
  371. } else {
  372. url = `/message/private/readed?friendId=${this.chat.targetId}`
  373. }
  374. this.$http({
  375. url: url,
  376. method: 'PUT'
  377. }).then(() => {
  378. this.$store.commit("resetUnreadCount", this.chat)
  379. this.scrollToBottom();
  380. })
  381. },
  382. loadGroup(groupId) {
  383. this.$http({
  384. url: `/group/find/${groupId}`,
  385. method: 'GET'
  386. }).then((group) => {
  387. this.group = group;
  388. this.$store.commit("updateChatFromGroup", group);
  389. this.$store.commit("updateGroup", group);
  390. });
  391. this.$http({
  392. url: `/group/members/${groupId}`,
  393. method: 'get'
  394. }).then((groupMembers) => {
  395. this.groupMembers = groupMembers;
  396. });
  397. },
  398. loadFriend(friendId) {
  399. // 获取对方最新信息
  400. this.$http({
  401. url: `/user/find/${friendId}`,
  402. method: 'GET'
  403. }).then((friend) => {
  404. this.friend = friend;
  405. this.$store.commit("updateChatFromFriend", friend);
  406. this.$store.commit("updateFriend", friend);
  407. })
  408. },
  409. rpxTopx(rpx) {
  410. // px转换成rpx
  411. let info = uni.getSystemInfoSync()
  412. let px = info.windowWidth * rpx / 750;
  413. return Math.floor(rpx);
  414. }
  415. },
  416. computed: {
  417. mine() {
  418. return this.$store.state.userStore.userInfo;
  419. },
  420. title() {
  421. if (!this.chat) {
  422. return "";
  423. }
  424. let title = this.chat.showName;
  425. if (this.chat.type == "GROUP") {
  426. let size = this.groupMembers.filter(m => !m.quit).length;
  427. title += `(${size})`;
  428. }
  429. return title;
  430. },
  431. messageAction() {
  432. return `/message/${this.chat.type.toLowerCase()}/send`;
  433. },
  434. messageSize() {
  435. if (!this.chat || !this.chat.messages) {
  436. return 0;
  437. }
  438. return this.chat.messages.length;
  439. },
  440. unreadCount() {
  441. return this.chat.unreadCount;
  442. }
  443. },
  444. watch: {
  445. messageSize: function(newSize, oldSize) {
  446. // 接收到消息时滚动到底部
  447. if (newSize > oldSize) {
  448. this.scrollToBottom();
  449. }
  450. },
  451. unreadCount: {
  452. handler(newCount, oldCount) {
  453. if (newCount > 0) {
  454. // 消息已读
  455. this.readedMessage()
  456. }
  457. }
  458. }
  459. },
  460. onLoad(options) {
  461. // 聊天数据
  462. this.chat = this.$store.state.chatStore.chats[options.chatIdx];
  463. // 初始状态只显示30条消息
  464. let size = this.chat.messages.length;
  465. this.showMinIdx = size > 30 ? size - 30 : 0;
  466. // 激活当前会话
  467. this.$store.commit("activeChat", options.chatIdx);
  468. // 页面滚到底部
  469. this.scrollToBottom();
  470. // 消息已读
  471. this.readedMessage()
  472. // 加载好友或群聊信息
  473. if (this.chat.type == "GROUP") {
  474. this.loadGroup(this.chat.targetId);
  475. } else {
  476. this.loadFriend(this.chat.targetId);
  477. }
  478. },
  479. onUnload() {
  480. this.$store.commit("activeChat", -1);
  481. }
  482. }
  483. </script>
  484. <style lang="scss" scoped>
  485. .chat-box {
  486. position: relative;
  487. border: #dddddd solid 1px;
  488. display: flex;
  489. flex-direction: column;
  490. .header {
  491. display: flex;
  492. justify-content: center;
  493. align-items: center;
  494. height: 60rpx;
  495. padding: 5px;
  496. background-color: white;
  497. line-height: 50px;
  498. font-size: 40rpx;
  499. font-weight: 600;
  500. border: #dddddd solid 1px;
  501. .btn-side {
  502. position: absolute;
  503. line-height: 60rpx;
  504. font-size: 28rpx;
  505. cursor: pointer;
  506. &.left {
  507. left: 30rpx;
  508. }
  509. &.right {
  510. right: 30rpx;
  511. }
  512. }
  513. }
  514. .chat-msg {
  515. flex: 1;
  516. padding: 0;
  517. border: #dddddd solid 1px;
  518. overflow: hidden;
  519. position: relative;
  520. background-color: #f8f8f8;
  521. .scroll-box {
  522. height: 100%;
  523. }
  524. }
  525. .send-bar {
  526. display: flex;
  527. align-items: center;
  528. padding: 10rpx;
  529. margin-bottom: 10rpx;
  530. border: #dddddd solid 1px;
  531. background-color: white;
  532. .iconfont {
  533. font-size: 70rpx;
  534. margin: 3rpx;
  535. }
  536. .send-text {
  537. flex: 1;
  538. background-color: #f8f8f8 !important;
  539. overflow: auto;
  540. padding: 20rpx;
  541. background-color: #fff;
  542. border-radius: 20rpx;
  543. max-height: 300rpx;
  544. min-height: 85rpx;
  545. font-size: 30rpx;
  546. box-sizing: border-box;
  547. .send-text-area {
  548. width: 100%;
  549. }
  550. }
  551. .btn-send {
  552. margin: 5rpx;
  553. }
  554. }
  555. .chat-tab-bar {
  556. height: 500rpx;
  557. padding: 20rpx;
  558. background-color: whitesmoke;
  559. .chat-tools {
  560. display: flex;
  561. flex-wrap: wrap;
  562. justify-content: space-between;
  563. .chat-tools-item {
  564. width: 140rpx;
  565. padding: 15rpx;
  566. display: flex;
  567. flex-direction: column;
  568. align-items: center;
  569. .tool-icon {
  570. padding: 15rpx;
  571. font-size: 80rpx;
  572. background-color: white;
  573. border-radius: 20%;
  574. }
  575. .tool-name {
  576. height: 60rpx;
  577. line-height: 60rpx;
  578. font-size: 25rpx;
  579. }
  580. }
  581. }
  582. .chat-emotion {
  583. height: 100%;
  584. .emotion-item-list {
  585. display: flex;
  586. flex-wrap: wrap;
  587. .emotion-item {
  588. width: 40px;
  589. height: 40px;
  590. text-align: center;
  591. cursor: pointer;
  592. padding: 6px;
  593. }
  594. }
  595. }
  596. }
  597. }
  598. </style>