chat-box.vue 24 KB

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