chat-box.vue 25 KB

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