chat-box.vue 25 KB

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