chat-box.vue 24 KB

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