chat-box.vue 25 KB

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