chat-box.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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. // 防止滚动条定格在顶部,不能一直往上滚
  351. this.scrollToMsgIdx(this.showMinIdx);
  352. // 多展示10条信息
  353. this.showMinIdx = this.showMinIdx > 10 ? this.showMinIdx - 10 : 0;
  354. },
  355. onShowMore() {
  356. if (this.chat.type == "GROUP") {
  357. uni.navigateTo({
  358. url: "/pages/group/group-info?id=" + this.group.id
  359. })
  360. } else {
  361. uni.navigateTo({
  362. url: "/pages/common/user-info?id=" + this.friend.id
  363. })
  364. }
  365. },
  366. readedMessage() {
  367. if (this.chat.type == "GROUP") {
  368. var url = `/message/group/readed?groupId=${this.chat.targetId}`
  369. } else {
  370. url = `/message/private/readed?friendId=${this.chat.targetId}`
  371. }
  372. this.$http({
  373. url: url,
  374. method: 'PUT'
  375. }).then(() => {
  376. this.$store.commit("resetUnreadCount", this.chat)
  377. this.scrollToBottom();
  378. })
  379. },
  380. loadGroup(groupId) {
  381. this.$http({
  382. url: `/group/find/${groupId}`,
  383. method: 'GET'
  384. }).then((group) => {
  385. this.group = group;
  386. this.$store.commit("updateChatFromGroup", group);
  387. this.$store.commit("updateGroup", group);
  388. });
  389. this.$http({
  390. url: `/group/members/${groupId}`,
  391. method: 'get'
  392. }).then((groupMembers) => {
  393. this.groupMembers = groupMembers;
  394. });
  395. },
  396. loadFriend(friendId) {
  397. // 获取对方最新信息
  398. this.$http({
  399. url: `/user/find/${friendId}`,
  400. method: 'GET'
  401. }).then((friend) => {
  402. this.friend = friend;
  403. this.$store.commit("updateChatFromFriend", friend);
  404. this.$store.commit("updateFriend", friend);
  405. })
  406. },
  407. rpxTopx(rpx) {
  408. // px转换成rpx
  409. let info = uni.getSystemInfoSync()
  410. let px = info.windowWidth * rpx / 750;
  411. return Math.floor(rpx);
  412. }
  413. },
  414. computed: {
  415. mine() {
  416. return this.$store.state.userStore.userInfo;
  417. },
  418. title() {
  419. if (!this.chat) {
  420. return "";
  421. }
  422. let title = this.chat.showName;
  423. if (this.chat.type == "GROUP") {
  424. let size = this.groupMembers.filter(m => !m.quit).length;
  425. title += `(${size})`;
  426. }
  427. return title;
  428. },
  429. messageAction() {
  430. return `/message/${this.chat.type.toLowerCase()}/send`;
  431. },
  432. messageSize() {
  433. if (!this.chat || !this.chat.messages) {
  434. return 0;
  435. }
  436. return this.chat.messages.length;
  437. },
  438. unreadCount() {
  439. return this.chat.unreadCount;
  440. }
  441. },
  442. watch: {
  443. messageSize: function(newSize, oldSize) {
  444. // 接收到消息时滚动到底部
  445. if (newSize > oldSize) {
  446. this.scrollToBottom();
  447. }
  448. },
  449. unreadCount: {
  450. handler(newCount, oldCount) {
  451. if (newCount > 0) {
  452. // 消息已读
  453. this.readedMessage()
  454. }
  455. }
  456. }
  457. },
  458. onLoad(options) {
  459. // 聊天数据
  460. this.chat = this.$store.state.chatStore.chats[options.chatIdx];
  461. // 初始状态只显示30条消息
  462. let size = this.chat.messages.length;
  463. this.showMinIdx = size > 30 ? size - 30 : 0;
  464. // 激活当前会话
  465. this.$store.commit("activeChat", options.chatIdx);
  466. // 页面滚到底部
  467. this.scrollToBottom();
  468. // 消息已读
  469. this.readedMessage()
  470. // 加载好友或群聊信息
  471. if (this.chat.type == "GROUP") {
  472. this.loadGroup(this.chat.targetId);
  473. } else {
  474. this.loadFriend(this.chat.targetId);
  475. }
  476. },
  477. onUnload() {
  478. this.$store.commit("activeChat", -1);
  479. }
  480. }
  481. </script>
  482. <style lang="scss" scoped>
  483. .chat-box {
  484. position: relative;
  485. border: #dddddd solid 1px;
  486. display: flex;
  487. flex-direction: column;
  488. .header {
  489. display: flex;
  490. justify-content: center;
  491. align-items: center;
  492. height: 60rpx;
  493. padding: 5px;
  494. background-color: white;
  495. line-height: 50px;
  496. font-size: 40rpx;
  497. font-weight: 600;
  498. border: #dddddd solid 1px;
  499. .btn-side {
  500. position: absolute;
  501. line-height: 60rpx;
  502. font-size: 28rpx;
  503. cursor: pointer;
  504. &.left {
  505. left: 30rpx;
  506. }
  507. &.right {
  508. right: 30rpx;
  509. }
  510. }
  511. }
  512. .chat-msg {
  513. flex: 1;
  514. padding: 0;
  515. border: #dddddd solid 1px;
  516. overflow: hidden;
  517. position: relative;
  518. background-color: white;
  519. .scroll-box {
  520. height: 100%;
  521. }
  522. }
  523. .send-bar {
  524. display: flex;
  525. align-items: center;
  526. padding: 10rpx;
  527. margin-bottom: 10rpx;
  528. border: #dddddd solid 1px;
  529. background-color: white;
  530. .iconfont {
  531. font-size: 70rpx;
  532. margin: 3rpx;
  533. }
  534. .send-text {
  535. flex: 1;
  536. background-color: #f8f8f8 !important;
  537. overflow: auto;
  538. padding: 20rpx;
  539. background-color: #fff;
  540. border-radius: 20rpx;
  541. max-height: 300rpx;
  542. min-height: 85rpx;
  543. font-size: 30rpx;
  544. box-sizing: border-box;
  545. .send-text-area {
  546. width: 100%;
  547. }
  548. }
  549. .btn-send {
  550. margin: 5rpx;
  551. }
  552. }
  553. .chat-tab-bar {
  554. height: 500rpx;
  555. padding: 20rpx;
  556. background-color: whitesmoke;
  557. .chat-tools {
  558. display: flex;
  559. flex-wrap: wrap;
  560. justify-content: space-between;
  561. .chat-tools-item {
  562. width: 140rpx;
  563. padding: 15rpx;
  564. display: flex;
  565. flex-direction: column;
  566. align-items: center;
  567. .tool-icon {
  568. padding: 15rpx;
  569. font-size: 80rpx;
  570. background-color: white;
  571. border-radius: 20%;
  572. }
  573. .tool-name {
  574. height: 60rpx;
  575. line-height: 60rpx;
  576. font-size: 25rpx;
  577. }
  578. }
  579. }
  580. .chat-emotion {
  581. height: 100%;
  582. .emotion-item-list {
  583. display: flex;
  584. flex-wrap: wrap;
  585. .emotion-item {
  586. width: 40px;
  587. height: 40px;
  588. text-align: center;
  589. cursor: pointer;
  590. padding: 6px;
  591. }
  592. }
  593. }
  594. }
  595. }
  596. </style>