chat-box.vue 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  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" upper-threshold="200" @scrolltoupper="onScrollToTop"
  10. :scroll-into-view="'chat-item-'+scrollMsgIdx">
  11. <view v-if="chat" v-for="(msgInfo,idx) in chat.messages" :key="idx">
  12. <chat-message-item v-if="idx>=showMinIdx" :headImage="headImage(msgInfo)" @call="onRtCall(msgInfo)"
  13. :showName="showName(msgInfo)" @recall="onRecallMessage" @copy="onCopyMessage"
  14. @delete="onDeleteMessage" @longPressHead="onLongPressHead(msgInfo)" @download="onDownloadFile"
  15. :id="'chat-item-'+idx" :msgInfo="msgInfo" :groupMembers="groupMembers">
  16. </chat-message-item>
  17. </view>
  18. </scroll-view>
  19. </view>
  20. <view v-if="atUserIds.length>0" class="chat-at-bar" @click="openAtBox()">
  21. <view class="iconfont icon-at">:&nbsp;</view>
  22. <scroll-view v-if="atUserIds.length>0" class="chat-at-scroll-box" scroll-x="true" scroll-left="120">
  23. <view class="chat-at-items">
  24. <view v-for="m in atUserItems" class="chat-at-item">
  25. <head-image :name="m.showNickName" :url="m.headImage" :size="50"></head-image>
  26. </view>
  27. </view>
  28. </scroll-view>
  29. </view>
  30. <view class="send-bar">
  31. <view v-if="!showRecord" class="iconfont icon-voice-circle" @click="onRecorderInput()"></view>
  32. <view v-else class="iconfont icon-keyboard" @click="onKeyboardInput()"></view>
  33. <chat-record v-if="showRecord" class="chat-record" @send="onSendRecord"></chat-record>
  34. <view v-else class="send-text">
  35. <textarea class="send-text-area" v-model="sendText" auto-height :show-confirm-bar="false"
  36. :placeholder="isReceipt?'[回执消息]':''" :adjust-position="false" @confirm="sendTextMessage()"
  37. @keyboardheightchange="onKeyboardheightchange" @input="onTextInput" confirm-type="send" confirm-hold
  38. :hold-keyboard="true"></textarea>
  39. </view>
  40. <view v-if="chat && chat.type=='GROUP'" class="iconfont icon-at" @click="openAtBox()"></view>
  41. <view class="iconfont icon-icon_emoji" @click="onShowEmoChatTab()"></view>
  42. <view v-if="sendText==''" class="iconfont icon-add" @click="onShowToolsChatTab()">
  43. </view>
  44. <button v-if="sendText!=''||atUserIds.length>0" class="btn-send" type="primary"
  45. @touchend.prevent="sendTextMessage()" size="mini">发送</button>
  46. </view>
  47. <view class="chat-tab-bar" v-show="chatTabBox!='none' ||showKeyBoard " :style="{height:`${keyboardHeight}px`}">
  48. <view v-if="chatTabBox == 'tools'" class="chat-tools">
  49. <view class="chat-tools-item">
  50. <image-upload :maxCount="9" sourceType="album" :onBefore="onUploadImageBefore"
  51. :onSuccess="onUploadImageSuccess" :onError="onUploadImageFail">
  52. <view class="tool-icon iconfont icon-picture"></view>
  53. </image-upload>
  54. <view class="tool-name">相册</view>
  55. </view>
  56. <view class="chat-tools-item">
  57. <image-upload sourceType="camera" :onBefore="onUploadImageBefore" :onSuccess="onUploadImageSuccess"
  58. :onError="onUploadImageFail">
  59. <view class="tool-icon iconfont icon-camera"></view>
  60. </image-upload>
  61. <view class="tool-name">拍摄</view>
  62. </view>
  63. <view class="chat-tools-item">
  64. <file-upload :onBefore="onUploadFileBefore" :onSuccess="onUploadFileSuccess"
  65. :onError="onUploadFileFail">
  66. <view class="tool-icon iconfont icon-folder"></view>
  67. </file-upload>
  68. <view class="tool-name">文件</view>
  69. </view>
  70. <view class="chat-tools-item" @click="onRecorderInput()">
  71. <view class="tool-icon iconfont icon-microphone"></view>
  72. <view class="tool-name">语音消息</view>
  73. </view>
  74. <view v-if="chat.type == 'GROUP'" class="chat-tools-item" @click="switchReceipt()">
  75. <view class="tool-icon iconfont icon-receipt" :class="isReceipt?'active':''"></view>
  76. <view class="tool-name">回执消息</view>
  77. </view>
  78. <!-- #ifndef MP-WEIXIN -->
  79. <!-- 音视频不支持小程序 -->
  80. <view v-if="chat.type == 'PRIVATE'" class="chat-tools-item" @click="onPriviteVideo()">
  81. <view class="tool-icon iconfont icon-video"></view>
  82. <view class="tool-name">视频通话</view>
  83. </view>
  84. <view v-if="chat.type == 'PRIVATE'" class="chat-tools-item" @click="onPriviteVoice()">
  85. <view class="tool-icon iconfont icon-call"></view>
  86. <view class="tool-name">语音通话</view>
  87. </view>
  88. <view v-if="chat.type == 'GROUP'" class="chat-tools-item" @click="onGroupVideo()">
  89. <view class="tool-icon iconfont icon-call"></view>
  90. <view class="tool-name">语音通话</view>
  91. </view>
  92. <!-- #endif -->
  93. </view>
  94. <scroll-view v-if="chatTabBox==='emo'" class="chat-emotion" scroll-y="true">
  95. <view class="emotion-item-list">
  96. <image class="emotion-item" :title="emoText" :src="$emo.textToPath(emoText)"
  97. v-for="(emoText, i) in $emo.emoTextList" :key="i" @click="selectEmoji(emoText)" mode="aspectFit"
  98. lazy-load="true"></image>
  99. </view>
  100. </scroll-view>
  101. <view v-if="showKeyBoard"></view>
  102. </view>
  103. <!-- @用户时选择成员 -->
  104. <chat-at-box ref="atBox" :ownerId="group.ownerId" :members="groupMembers"
  105. @complete="onAtComplete"></chat-at-box>
  106. <!-- 群语音通话时选择成员 -->
  107. <!-- #ifndef MP-WEIXIN -->
  108. <group-member-selector ref="selBox" :members="groupMembers" :maxSize="configStore.webrtc.maxChannel"
  109. @complete="onInviteOk"></group-member-selector>
  110. <group-rtc-join ref="rtcJoin" :groupId="group.id"></group-rtc-join>
  111. <!-- #endif -->
  112. </view>
  113. </template>
  114. <script>
  115. import UNI_APP from '@/.env.js';
  116. export default {
  117. data() {
  118. return {
  119. chat: {},
  120. friend: {},
  121. group: {},
  122. groupMembers: [],
  123. sendText: "",
  124. isReceipt: false, // 是否回执消息
  125. scrollMsgIdx: 0, // 滚动条定位为到哪条消息
  126. chatTabBox: 'none',
  127. showKeyBoard: false,
  128. showRecord: false,
  129. keyboardHeight: 322,
  130. atUserIds: [],
  131. needScrollToBottom: false, // 需要滚动到底部
  132. showMinIdx: 0, // 下标小于showMinIdx的消息不显示,否则可能很卡
  133. reqQueue: [], // 请求队列
  134. isSending: false // 是否正在发送请求
  135. }
  136. },
  137. methods: {
  138. onRecorderInput() {
  139. this.showRecord = true;
  140. this.switchChatTabBox('none', true);
  141. },
  142. onKeyboardInput() {
  143. this.showRecord = false;
  144. this.switchChatTabBox('none', false);
  145. },
  146. onSendRecord(data) {
  147. let msgInfo = {
  148. content: JSON.stringify(data),
  149. type: this.$enums.MESSAGE_TYPE.AUDIO,
  150. receipt: this.isReceipt
  151. }
  152. // 填充对方id
  153. this.fillTargetId(msgInfo, this.chat.targetId);
  154. this.sendMessageRequest(msgInfo).then((m) => {
  155. m.selfSend = true;
  156. this.chatStore.insertMessage(m);
  157. // 会话置顶
  158. this.moveChatToTop();
  159. // 滚动到底部
  160. this.scrollToBottom();
  161. this.isReceipt = false;
  162. })
  163. },
  164. onRtCall(msgInfo) {
  165. if (msgInfo.type == this.$enums.MESSAGE_TYPE.ACT_RT_VOICE) {
  166. this.onPriviteVoice();
  167. } else if (msgInfo.type == this.$enums.MESSAGE_TYPE.ACT_RT_VIDEO) {
  168. this.onPriviteVideo();
  169. }
  170. },
  171. onPriviteVideo() {
  172. const friendInfo = encodeURIComponent(JSON.stringify(this.friend));
  173. uni.navigateTo({
  174. url: `/pages/chat/chat-private-video?mode=video&friend=${friendInfo}&isHost=true`
  175. })
  176. },
  177. onPriviteVoice() {
  178. const friendInfo = encodeURIComponent(JSON.stringify(this.friend));
  179. uni.navigateTo({
  180. url: `/pages/chat/chat-private-video?mode=voice&friend=${friendInfo}&isHost=true`
  181. })
  182. },
  183. onGroupVideo() {
  184. // 邀请成员发起通话
  185. let ids = [this.mine.id];
  186. this.$refs.selBox.init(ids, ids);
  187. this.$refs.selBox.open();
  188. },
  189. onInviteOk(ids) {
  190. if (ids.length < 2) {
  191. return;
  192. }
  193. let users = [];
  194. ids.forEach(id => {
  195. let m = this.groupMembers.find(m => m.userId == id);
  196. // 只取部分字段,压缩url长度
  197. users.push({
  198. id: m.userId,
  199. nickName: m.showNickName,
  200. headImage: m.headImage,
  201. isCamera: false,
  202. isMicroPhone: true
  203. })
  204. })
  205. const groupId = this.group.id;
  206. const inviterId = this.mine.id;
  207. const userInfos = encodeURIComponent(JSON.stringify(users));
  208. uni.navigateTo({
  209. url: `/pages/chat/chat-group-video?groupId=${groupId}&isHost=true
  210. &inviterId=${inviterId}&userInfos=${userInfos}`
  211. })
  212. },
  213. moveChatToTop() {
  214. let chatIdx = this.chatStore.findChatIdx(this.chat);
  215. this.chatStore.moveTop(chatIdx);
  216. },
  217. switchReceipt() {
  218. this.isReceipt = !this.isReceipt;
  219. },
  220. openAtBox() {
  221. this.$refs.atBox.init(this.atUserIds);
  222. this.$refs.atBox.open();
  223. },
  224. onAtComplete(atUserIds) {
  225. this.atUserIds = atUserIds;
  226. },
  227. onLongPressHead(msgInfo) {
  228. if (!msgInfo.selfSend && this.chat.type == "GROUP" && this.atUserIds.indexOf(msgInfo.sendId) < 0) {
  229. this.atUserIds.push(msgInfo.sendId);
  230. }
  231. },
  232. headImage(msgInfo) {
  233. if (this.chat.type == 'GROUP') {
  234. let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
  235. return member ? member.headImage : "";
  236. } else {
  237. return msgInfo.selfSend ? this.mine.headImageThumb : this.chat.headImage
  238. }
  239. },
  240. showName(msgInfo) {
  241. if (this.chat.type == 'GROUP') {
  242. let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
  243. return member ? member.showNickName : "";
  244. } else {
  245. return msgInfo.selfSend ? this.mine.nickName : this.chat.showName
  246. }
  247. },
  248. sendTextMessage() {
  249. if (!this.sendText.trim() && this.atUserIds.length == 0) {
  250. return uni.showToast({
  251. title: "不能发送空白信息",
  252. icon: "none"
  253. });
  254. }
  255. let receiptText = this.isReceipt ? "【回执消息】" : "";
  256. let atText = this.createAtText();
  257. let msgInfo = {
  258. content: receiptText + this.sendText + atText,
  259. atUserIds: this.atUserIds,
  260. receipt: this.isReceipt,
  261. type: 0
  262. }
  263. this.sendText = "";
  264. // 填充对方id
  265. this.fillTargetId(msgInfo, this.chat.targetId);
  266. this.sendMessageRequest(msgInfo).then((m) => {
  267. m.selfSend = true;
  268. this.chatStore.insertMessage(m);
  269. // 会话置顶
  270. this.moveChatToTop();
  271. }).finally(() => {
  272. // 滚动到底部
  273. this.scrollToBottom();
  274. // 清空@用户列表
  275. this.atUserIds = [];
  276. this.isReceipt = false;
  277. });
  278. },
  279. createAtText() {
  280. let atText = "";
  281. this.atUserIds.forEach((id) => {
  282. if (id == -1) {
  283. atText += ` @全体成员`;
  284. } else {
  285. let member = this.groupMembers.find((m) => m.userId == id);
  286. if (member) {
  287. atText += ` @${member.showNickName}`;
  288. }
  289. }
  290. })
  291. return atText;
  292. },
  293. fillTargetId(msgInfo, targetId) {
  294. if (this.chat.type == "GROUP") {
  295. msgInfo.groupId = targetId;
  296. } else {
  297. msgInfo.recvId = targetId;
  298. }
  299. },
  300. scrollToBottom() {
  301. let size = this.messageSize;
  302. if (size > 0) {
  303. this.scrollToMsgIdx(size - 1);
  304. }
  305. },
  306. scrollToMsgIdx(idx) {
  307. // 如果scrollMsgIdx值没变化,滚动条不会移动
  308. if (idx == this.scrollMsgIdx && idx > 0) {
  309. this.$nextTick(() => {
  310. // 先滚动到上一条
  311. this.scrollMsgIdx = idx - 1;
  312. // 再滚动目标位置
  313. this.scrollToMsgIdx(idx);
  314. });
  315. return;
  316. }
  317. this.$nextTick(() => {
  318. this.scrollMsgIdx = idx;
  319. });
  320. },
  321. onShowEmoChatTab() {
  322. this.showRecord = false;
  323. this.switchChatTabBox('emo', true)
  324. },
  325. onShowToolsChatTab() {
  326. this.showRecord = false;
  327. this.switchChatTabBox('tools', true)
  328. },
  329. switchChatTabBox(chatTabBox, hideKeyBoard) {
  330. this.chatTabBox = chatTabBox;
  331. if (hideKeyBoard) {
  332. uni.hideKeyboard();
  333. this.showKeyBoard = false;
  334. }
  335. },
  336. selectEmoji(emoText) {
  337. this.sendText += `#${emoText};`;
  338. },
  339. onNavBack() {
  340. uni.switchTab({
  341. url: "/pages/chat/chat"
  342. })
  343. },
  344. onKeyboardheightchange(e) {
  345. if (e.detail.height > 0) {
  346. this.showKeyBoard = true;
  347. this.switchChatTabBox('none', false)
  348. this.keyboardHeight = this.rpxTopx(e.detail.height);
  349. this.scrollToBottom();
  350. } else {
  351. this.showKeyBoard = false;
  352. }
  353. },
  354. onUploadImageBefore(file) {
  355. let data = {
  356. originUrl: file.path,
  357. thumbUrl: file.path
  358. }
  359. let msgInfo = {
  360. id: 0,
  361. tmpId: this.generateId(),
  362. fileId: file.uid,
  363. sendId: this.mine.id,
  364. content: JSON.stringify(data),
  365. sendTime: new Date().getTime(),
  366. selfSend: true,
  367. type: this.$enums.MESSAGE_TYPE.IMAGE,
  368. readedCount: 0,
  369. loadStatus: "loading",
  370. status: this.$enums.MESSAGE_STATUS.UNSEND
  371. }
  372. // 填充对方id
  373. this.fillTargetId(msgInfo, this.chat.targetId);
  374. // 插入消息
  375. this.chatStore.insertMessage(msgInfo);
  376. // 会话置顶
  377. this.moveChatToTop();
  378. // 借助file对象保存
  379. file.msgInfo = msgInfo;
  380. // 滚到最低部
  381. this.scrollToBottom();
  382. return true;
  383. },
  384. onUploadImageSuccess(file, res) {
  385. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  386. msgInfo.content = JSON.stringify(res.data);
  387. msgInfo.receipt = this.isReceipt
  388. this.sendMessageRequest(msgInfo).then((m) => {
  389. msgInfo.loadStatus = 'ok';
  390. msgInfo.id = m.id;
  391. this.isReceipt = false;
  392. this.chatStore.insertMessage(msgInfo);
  393. })
  394. },
  395. onUploadImageFail(file, err) {
  396. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  397. msgInfo.loadStatus = 'fail';
  398. this.chatStore.insertMessage(msgInfo);
  399. },
  400. onUploadFileBefore(file) {
  401. let data = {
  402. name: file.name,
  403. size: file.size,
  404. url: file.path
  405. }
  406. let msgInfo = {
  407. id: 0,
  408. tmpId: this.generateId(),
  409. sendId: this.mine.id,
  410. content: JSON.stringify(data),
  411. sendTime: new Date().getTime(),
  412. selfSend: true,
  413. type: this.$enums.MESSAGE_TYPE.FILE,
  414. readedCount: 0,
  415. loadStatus: "loading",
  416. status: this.$enums.MESSAGE_STATUS.UNSEND
  417. }
  418. // 填充对方id
  419. this.fillTargetId(msgInfo, this.chat.targetId);
  420. // 插入消息
  421. this.chatStore.insertMessage(msgInfo);
  422. // 会话置顶
  423. this.moveChatToTop();
  424. // 借助file对象保存
  425. file.msgInfo = msgInfo;
  426. // 滚到最低部
  427. this.scrollToBottom();
  428. return true;
  429. },
  430. onUploadFileSuccess(file, res) {
  431. let data = {
  432. name: file.name,
  433. size: file.size,
  434. url: res.data
  435. }
  436. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  437. msgInfo.content = JSON.stringify(data);
  438. msgInfo.receipt = this.isReceipt
  439. this.sendMessageRequest(msgInfo).then((m) => {
  440. msgInfo.loadStatus = 'ok';
  441. msgInfo.id = m.id;
  442. this.isReceipt = false;
  443. this.chatStore.insertMessage(msgInfo);
  444. })
  445. },
  446. onUploadFileFail(file, res) {
  447. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  448. msgInfo.loadStatus = 'fail';
  449. this.chatStore.insertMessage(msgInfo);
  450. },
  451. onDeleteMessage(msgInfo) {
  452. uni.showModal({
  453. title: '删除消息',
  454. content: '确认删除消息?',
  455. success: (res) => {
  456. if (!res.cancel) {
  457. this.chatStore.deleteMessage(msgInfo);
  458. uni.showToast({
  459. title: "删除成功",
  460. icon: "none"
  461. })
  462. }
  463. }
  464. })
  465. },
  466. onRecallMessage(msgInfo) {
  467. uni.showModal({
  468. title: '撤回消息',
  469. content: '确认撤回消息?',
  470. success: (res) => {
  471. if (!res.cancel) {
  472. let url = `/message/${this.chat.type.toLowerCase()}/recall/${msgInfo.id}`
  473. this.$http({
  474. url: url,
  475. method: 'DELETE'
  476. }).then(() => {
  477. msgInfo = JSON.parse(JSON.stringify(msgInfo));
  478. msgInfo.type = this.$enums.MESSAGE_TYPE.RECALL;
  479. msgInfo.content = '你撤回了一条消息';
  480. msgInfo.status = this.$enums.MESSAGE_STATUS.RECALL;
  481. this.chatStore.insertMessage(msgInfo);
  482. })
  483. }
  484. }
  485. })
  486. },
  487. onCopyMessage(msgInfo) {
  488. uni.setClipboardData({
  489. data: msgInfo.content,
  490. success: () => {
  491. uni.showToast({ title: '已复制', icon: 'none' });
  492. },
  493. fail: () => {
  494. uni.showToast({ title: '复制失败', icon: 'none' });
  495. }
  496. });
  497. },
  498. onDownloadFile(msgInfo) {
  499. let url = JSON.parse(msgInfo.content).url;
  500. uni.downloadFile({
  501. url: url,
  502. success(res) {
  503. if (res.statusCode === 200) {
  504. var filePath = encodeURI(res.tempFilePath);
  505. uni.openDocument({
  506. filePath: filePath,
  507. showMenu: true
  508. });
  509. }
  510. },
  511. fail(e) {
  512. uni.showToast({
  513. title: "文件下载失败",
  514. icon: "none"
  515. })
  516. }
  517. });
  518. },
  519. onScrollToTop() {
  520. if (this.showMinIdx == 0) {
  521. console.log("消息已滚动到顶部")
  522. return;
  523. }
  524. // #ifndef H5
  525. // 防止滚动条定格在顶部,不能一直往上滚
  526. this.scrollToMsgIdx(this.showMinIdx);
  527. // #endif
  528. // 多展示0条信息
  529. this.showMinIdx = this.showMinIdx > 20 ? this.showMinIdx - 20 : 0;
  530. },
  531. onShowMore() {
  532. if (this.chat.type == "GROUP") {
  533. uni.navigateTo({
  534. url: "/pages/group/group-info?id=" + this.group.id
  535. })
  536. } else {
  537. uni.navigateTo({
  538. url: "/pages/common/user-info?id=" + this.friend.id
  539. })
  540. }
  541. },
  542. onTextInput(e) {
  543. let idx = e.detail.cursor - 1;
  544. if (this.chat.type == 'GROUP' && e.detail.value[idx] == '@') {
  545. this.openAtBox();
  546. let sendText = e.detail.value.replace("@", '');
  547. this.$nextTick(() => {
  548. this.sendText = sendText;
  549. })
  550. }
  551. },
  552. loadReaded(fid) {
  553. this.$http({
  554. url: `/message/private/maxReadedId?friendId=${fid}`,
  555. method: 'get'
  556. }).then((id) => {
  557. this.chatStore.readedMessage({
  558. friendId: fid,
  559. maxId: id
  560. });
  561. });
  562. },
  563. readedMessage() {
  564. if (this.unreadCount == 0) {
  565. return;
  566. }
  567. let url = ""
  568. if (this.chat.type == "GROUP") {
  569. url = `/message/group/readed?groupId=${this.chat.targetId}`
  570. } else {
  571. url = `/message/private/readed?friendId=${this.chat.targetId}`
  572. }
  573. this.$http({
  574. url: url,
  575. method: 'PUT'
  576. }).then(() => {
  577. this.chatStore.resetUnreadCount(this.chat)
  578. this.scrollToBottom();
  579. })
  580. },
  581. loadGroup(groupId) {
  582. this.$http({
  583. url: `/group/find/${groupId}`,
  584. method: 'GET'
  585. }).then((group) => {
  586. this.group = group;
  587. this.chatStore.updateChatFromGroup(group);
  588. this.groupStore.updateGroup(group);
  589. });
  590. this.$http({
  591. url: `/group/members/${groupId}`,
  592. method: 'GET'
  593. }).then((groupMembers) => {
  594. this.groupMembers = groupMembers;
  595. });
  596. },
  597. loadFriend(friendId) {
  598. // 获取对方最新信息
  599. this.$http({
  600. url: `/user/find/${friendId}`,
  601. method: 'GET'
  602. }).then((friend) => {
  603. this.friend = friend;
  604. this.chatStore.updateChatFromFriend(friend);
  605. this.friendStore.updateFriend(friend);
  606. })
  607. },
  608. rpxTopx(rpx) {
  609. // px转换成rpx
  610. let info = uni.getSystemInfoSync()
  611. let px = info.windowWidth * rpx / 750;
  612. return Math.floor(rpx);
  613. },
  614. sendMessageRequest(msgInfo) {
  615. return new Promise((resolve, reject) => {
  616. // 请求入队列,防止请求"后发先至",导致消息错序
  617. this.reqQueue.push({ msgInfo, resolve, reject });
  618. this.processReqQueue();
  619. })
  620. },
  621. processReqQueue() {
  622. if (this.reqQueue.length && !this.isSending) {
  623. this.isSending = true;
  624. const reqData = this.reqQueue.shift();
  625. this.$http({
  626. url: this.messageAction,
  627. method: 'post',
  628. data: reqData.msgInfo
  629. }).then((res) => {
  630. reqData.resolve(res)
  631. }).catch((e) => {
  632. reqData.reject(e)
  633. }).finally(() => {
  634. this.isSending = false;
  635. // 发送下一条请求
  636. this.processReqQueue();
  637. })
  638. }
  639. },
  640. generateId() {
  641. // 生成临时id
  642. return String(new Date().getTime()) + String(Math.floor(Math.random() * 1000));
  643. }
  644. },
  645. computed: {
  646. mine() {
  647. return this.userStore.userInfo;
  648. },
  649. title() {
  650. if (!this.chat) {
  651. return "";
  652. }
  653. let title = this.chat.showName;
  654. if (this.chat.type == "GROUP") {
  655. let size = this.groupMembers.filter(m => !m.quit).length;
  656. title += `(${size})`;
  657. }
  658. return title;
  659. },
  660. messageAction() {
  661. return `/message/${this.chat.type.toLowerCase()}/send`;
  662. },
  663. messageSize() {
  664. if (!this.chat || !this.chat.messages) {
  665. return 0;
  666. }
  667. return this.chat.messages.length;
  668. },
  669. unreadCount() {
  670. if (!this.chat || !this.chat.unreadCount) {
  671. return 0;
  672. }
  673. return this.chat.unreadCount;
  674. },
  675. atUserItems() {
  676. let atUsers = [];
  677. this.atUserIds.forEach((id) => {
  678. if (id == -1) {
  679. atUsers.push({
  680. id: -1,
  681. showNickName: "全体成员"
  682. })
  683. return;
  684. }
  685. let member = this.groupMembers.find((m) => m.userId == id);
  686. if (member) {
  687. atUsers.push(member);
  688. }
  689. })
  690. return atUsers;
  691. }
  692. },
  693. watch: {
  694. messageSize: function(newSize, oldSize) {
  695. // 接收到消息时滚动到底部
  696. if (newSize > oldSize) {
  697. let pages = getCurrentPages();
  698. let curPage = pages[pages.length - 1].route;
  699. if (curPage == "pages/chat/chat-box") {
  700. this.scrollToBottom();
  701. } else {
  702. this.needScrollToBottom = true;
  703. }
  704. }
  705. },
  706. unreadCount: {
  707. handler(newCount, oldCount) {
  708. if (newCount > 0) {
  709. // 消息已读
  710. this.readedMessage()
  711. }
  712. }
  713. }
  714. },
  715. onLoad(options) {
  716. // 聊天数据
  717. this.chat = this.chatStore.chats[options.chatIdx];
  718. // 初始状态只显示20条消息
  719. let size = this.messageSize;
  720. this.showMinIdx = size > 20 ? size - 20 : 0;
  721. // 消息已读
  722. this.readedMessage()
  723. // 加载好友或群聊信息
  724. if (this.chat.type == "GROUP") {
  725. this.loadGroup(this.chat.targetId);
  726. } else {
  727. this.loadFriend(this.chat.targetId);
  728. this.loadReaded(this.chat.targetId)
  729. }
  730. // 激活当前会话
  731. this.chatStore.activeChat(options.chatIdx);
  732. // 复位回执消息
  733. this.isReceipt = false;
  734. },
  735. onShow() {
  736. if (this.needScrollToBottom) {
  737. // 页面滚到底部
  738. this.scrollToBottom();
  739. this.needScrollToBottom = false;
  740. }
  741. }
  742. }
  743. </script>
  744. <style lang="scss" scoped>
  745. .chat-box {
  746. position: relative;
  747. border: #dddddd solid 1px;
  748. display: flex;
  749. flex-direction: column;
  750. .header {
  751. display: flex;
  752. justify-content: center;
  753. align-items: center;
  754. height: 60rpx;
  755. padding: 5px;
  756. background-color: #f8f8f8;
  757. line-height: 50px;
  758. font-size: 40rpx;
  759. font-weight: 600;
  760. border: #dddddd solid 1px;
  761. .btn-side {
  762. position: absolute;
  763. line-height: 60rpx;
  764. font-size: 28rpx;
  765. cursor: pointer;
  766. &.left {
  767. left: 30rpx;
  768. }
  769. &.right {
  770. right: 30rpx;
  771. }
  772. }
  773. }
  774. .chat-msg {
  775. flex: 1;
  776. padding: 0;
  777. border: #dddddd solid 1px;
  778. overflow: hidden;
  779. position: relative;
  780. background-color: white;
  781. .scroll-box {
  782. height: 100%;
  783. }
  784. }
  785. .chat-at-bar {
  786. display: flex;
  787. align-items: center;
  788. padding: 0 10rpx;
  789. border: #dddddd solid 1px;
  790. .icon-at {
  791. font-size: 35rpx;
  792. color: darkblue;
  793. font-weight: 600;
  794. }
  795. .chat-at-scroll-box {
  796. flex: 1;
  797. width: 80%;
  798. .chat-at-items {
  799. display: flex;
  800. align-items: center;
  801. height: 70rpx;
  802. .chat-at-item {
  803. padding: 0 3rpx;
  804. }
  805. }
  806. }
  807. }
  808. .send-bar {
  809. display: flex;
  810. align-items: center;
  811. padding: 10rpx;
  812. margin-bottom: 10rpx;
  813. border: #dddddd solid 1px;
  814. background-color: #f7f8fd;
  815. height: 80rpx;
  816. .iconfont {
  817. font-size: 68rpx;
  818. margin: 6rpx;
  819. }
  820. .chat-record {
  821. flex: 1;
  822. }
  823. .send-text {
  824. flex: 1;
  825. overflow: auto;
  826. padding: 20rpx;
  827. background-color: #fff;
  828. border-radius: 20rpx;
  829. font-size: 30rpx;
  830. box-sizing: border-box;
  831. .send-text-area {
  832. width: 100%;
  833. }
  834. }
  835. .btn-send {
  836. margin: 5rpx;
  837. }
  838. }
  839. .chat-tab-bar {
  840. height: 500rpx;
  841. padding: 20rpx;
  842. background-color: #f8f8f8;
  843. .chat-tools {
  844. display: flex;
  845. flex-wrap: wrap;
  846. .chat-tools-item {
  847. width: 140rpx;
  848. padding: 16rpx;
  849. display: flex;
  850. flex-direction: column;
  851. align-items: center;
  852. .tool-icon {
  853. padding: 28rpx;
  854. font-size: 60rpx;
  855. border-radius: 20%;
  856. background-color: white;
  857. color: black;
  858. &.active {
  859. background-color: #ddd;
  860. }
  861. }
  862. .tool-name {
  863. height: 60rpx;
  864. line-height: 60rpx;
  865. font-size: 28rpx;
  866. }
  867. }
  868. }
  869. .chat-emotion {
  870. height: 100%;
  871. .emotion-item-list {
  872. display: flex;
  873. flex-wrap: wrap;
  874. .emotion-item {
  875. width: 40px;
  876. height: 40px;
  877. text-align: center;
  878. cursor: pointer;
  879. padding: 6px;
  880. }
  881. }
  882. }
  883. }
  884. }
  885. </style>