chat-box.vue 14 KB

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