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