chat-box.vue 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. <template>
  2. <view class="page chat-box">
  3. <nav-bar back more @more="onShowMore">{{ title }}</nav-bar>
  4. <view class="chat-main-box" :style="{height: chatMainHeight+'px'}">
  5. <view class="chat-msg" @click="switchChatTabBox('none')">
  6. <scroll-view class="scroll-box" scroll-y="true" upper-threshold="200" @scrolltoupper="onScrollToTop"
  7. :scroll-into-view="'chat-item-' + scrollMsgIdx">
  8. <view v-if="chat" v-for="(msgInfo, idx) in chat.messages" :key="idx">
  9. <chat-message-item v-if="idx >= showMinIdx" :headImage="headImage(msgInfo)"
  10. @call="onRtCall(msgInfo)" :showName="showName(msgInfo)" @recall="onRecallMessage"
  11. @copy="onCopyMessage" @delete="onDeleteMessage" @longPressHead="onLongPressHead(msgInfo)"
  12. @download="onDownloadFile" :id="'chat-item-' + idx" :msgInfo="msgInfo"
  13. :groupMembers="groupMembers">
  14. </chat-message-item>
  15. </view>
  16. </scroll-view>
  17. </view>
  18. <view v-if="atUserIds.length > 0" class="chat-at-bar" @click="openAtBox()">
  19. <view class="iconfont icon-at">:&nbsp;</view>
  20. <scroll-view v-if="atUserIds.length > 0" class="chat-at-scroll-box" scroll-x="true" scroll-left="120">
  21. <view class="chat-at-items">
  22. <view v-for="m in atUserItems" class="chat-at-item">
  23. <head-image :name="m.showNickName" :url="m.headImage" size="minier"></head-image>
  24. </view>
  25. </view>
  26. </scroll-view>
  27. </view>
  28. <view class="send-bar">
  29. <view v-if="!showRecord" class="iconfont icon-voice-circle" @click="onRecorderInput()"></view>
  30. <view v-else class="iconfont icon-keyboard" @click="onKeyboardInput()"></view>
  31. <chat-record v-if="showRecord" class="chat-record" @send="onSendRecord"></chat-record>
  32. <view v-else class="send-text">
  33. <editor id="editor" class="send-text-area" :placeholder="isReceipt ? '[回执消息]' : ''"
  34. :read-only="isReadOnly" @focus="onEditorFocus" @blur="onEditorBlur" @ready="onEditorReady"
  35. @input="onTextInput">
  36. </editor>
  37. <!-- <textarea class="send-text-area" v-model="sendText" auto-height :show-confirm-bar="false"
  38. :placeholder="isReceipt ? '[回执消息]' : ''" :adjust-position="false" @confirm="sendTextMessage()"
  39. @keyboardheightchange="onKeyboardheightchange" @input="onTextInput" confirm-type="send"
  40. confirm-hold :hold-keyboard="true"></textarea> -->
  41. </view>
  42. <view v-if="chat && chat.type == 'GROUP'" class="iconfont icon-at" @click="openAtBox()"></view>
  43. <view class="iconfont icon-icon_emoji" @click="onShowEmoChatTab()"></view>
  44. <view v-if="isEmpty" class="iconfont icon-add" @click="onShowToolsChatTab()">
  45. </view>
  46. <button v-if="!isEmpty || atUserIds.length > 0" class="btn-send" type="primary"
  47. @touchend.prevent="sendTextMessage()" size="mini">发送</button>
  48. </view>
  49. </view>
  50. <view class="chat-tab-bar">
  51. <view v-if="chatTabBox == 'tools'" class="chat-tools" :style="{height: keyboardHeight+'px'}">
  52. <view class="chat-tools-item">
  53. <image-upload :maxCount="9" sourceType="album" :onBefore="onUploadImageBefore"
  54. :onSuccess="onUploadImageSuccess" :onError="onUploadImageFail">
  55. <view class="tool-icon iconfont icon-picture"></view>
  56. </image-upload>
  57. <view class="tool-name">相册</view>
  58. </view>
  59. <view class="chat-tools-item">
  60. <image-upload sourceType="camera" :onBefore="onUploadImageBefore" :onSuccess="onUploadImageSuccess"
  61. :onError="onUploadImageFail">
  62. <view class="tool-icon iconfont icon-camera"></view>
  63. </image-upload>
  64. <view class="tool-name">拍摄</view>
  65. </view>
  66. <view class="chat-tools-item">
  67. <file-upload ref="fileUpload" :onBefore="onUploadFileBefore" :onSuccess="onUploadFileSuccess"
  68. :onError="onUploadFileFail">
  69. <view class="tool-icon iconfont icon-folder"></view>
  70. </file-upload>
  71. <view class="tool-name">文件</view>
  72. </view>
  73. <view class="chat-tools-item" @click="onRecorderInput()">
  74. <view class="tool-icon iconfont icon-microphone"></view>
  75. <view class="tool-name">语音消息</view>
  76. </view>
  77. <view v-if="chat.type == 'GROUP'" class="chat-tools-item" @click="switchReceipt()">
  78. <view class="tool-icon iconfont icon-receipt" :class="isReceipt ? 'active' : ''"></view>
  79. <view class="tool-name">回执消息</view>
  80. </view>
  81. <!-- #ifndef MP-WEIXIN -->
  82. <!-- 音视频不支持小程序 -->
  83. <view v-if="chat.type == 'PRIVATE'" class="chat-tools-item" @click="onPriviteVideo()">
  84. <view class="tool-icon iconfont icon-video"></view>
  85. <view class="tool-name">视频通话</view>
  86. </view>
  87. <view v-if="chat.type == 'PRIVATE'" class="chat-tools-item" @click="onPriviteVoice()">
  88. <view class="tool-icon iconfont icon-call"></view>
  89. <view class="tool-name">语音通话</view>
  90. </view>
  91. <view v-if="chat.type == 'GROUP'" class="chat-tools-item" @click="onGroupVideo()">
  92. <view class="tool-icon iconfont icon-call"></view>
  93. <view class="tool-name">语音通话</view>
  94. </view>
  95. <!-- #endif -->
  96. </view>
  97. <scroll-view v-if="chatTabBox === 'emo'" class="chat-emotion" scroll-y="true"
  98. :style="{height: keyboardHeight+'px'}">
  99. <view class="emotion-item-list">
  100. <image class="emotion-item emoji-large" :title="emoText" :src="$emo.textToPath(emoText)"
  101. v-for="(emoText, i) in $emo.emoTextList" :key="i" @click="selectEmoji(emoText)" mode="aspectFit"
  102. lazy-load="true"></image>
  103. </view>
  104. </scroll-view>
  105. </view>
  106. <!-- @用户时选择成员 -->
  107. <chat-at-box ref="atBox" :ownerId="group.ownerId" :members="groupMembers"
  108. @complete="onAtComplete"></chat-at-box>
  109. <!-- 群语音通话时选择成员 -->
  110. <!-- #ifndef MP-WEIXIN -->
  111. <group-member-selector ref="selBox" :members="groupMembers" :maxSize="configStore.webrtc.maxChannel"
  112. @complete="onInviteOk"></group-member-selector>
  113. <group-rtc-join ref="rtcJoin" :groupId="group.id"></group-rtc-join>
  114. <!-- #endif -->
  115. </view>
  116. </template>
  117. <script>
  118. import UNI_APP from '@/.env.js';
  119. export default {
  120. data() {
  121. return {
  122. chat: {},
  123. friend: {},
  124. group: {},
  125. groupMembers: [],
  126. isReceipt: false, // 是否回执消息
  127. scrollMsgIdx: 0, // 滚动条定位为到哪条消息
  128. chatTabBox: 'none',
  129. showRecord: false,
  130. keyboardHeight: 300,
  131. chatMainHeight: 0, // 聊天窗口高度
  132. atUserIds: [],
  133. needScrollToBottom: false, // 需要滚动到底部
  134. showMinIdx: 0, // 下标小于showMinIdx的消息不显示,否则可能很卡
  135. reqQueue: [], // 请求队列
  136. isSending: false, // 是否正在发送请求
  137. isShowKeyBoard: false, // 键盘是否正在弹起
  138. editorCtx: null, // 编辑器上下文
  139. isEmpty: true, // 编辑器是否为空
  140. isFocus: false, // 编辑器是否焦点
  141. isReadOnly: false // 编辑器是否只读
  142. }
  143. },
  144. methods: {
  145. onRecorderInput() {
  146. this.showRecord = true;
  147. this.switchChatTabBox('none');
  148. },
  149. onKeyboardInput() {
  150. this.showRecord = false;
  151. this.switchChatTabBox('none');
  152. },
  153. onSendRecord(data) {
  154. let msgInfo = {
  155. content: JSON.stringify(data),
  156. type: this.$enums.MESSAGE_TYPE.AUDIO,
  157. receipt: this.isReceipt
  158. }
  159. // 填充对方id
  160. this.fillTargetId(msgInfo, this.chat.targetId);
  161. this.sendMessageRequest(msgInfo).then((m) => {
  162. m.selfSend = true;
  163. this.chatStore.insertMessage(m);
  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. // 邀请成员发起通话
  192. let ids = [this.mine.id];
  193. this.$refs.selBox.init(ids, ids);
  194. this.$refs.selBox.open();
  195. },
  196. onInviteOk(ids) {
  197. if (ids.length < 2) {
  198. return;
  199. }
  200. let users = [];
  201. ids.forEach(id => {
  202. let m = this.groupMembers.find(m => m.userId == id);
  203. // 只取部分字段,压缩url长度
  204. users.push({
  205. id: m.userId,
  206. nickName: m.showNickName,
  207. headImage: m.headImage,
  208. isCamera: false,
  209. isMicroPhone: true
  210. })
  211. })
  212. const groupId = this.group.id;
  213. const inviterId = this.mine.id;
  214. const userInfos = encodeURIComponent(JSON.stringify(users));
  215. uni.navigateTo({
  216. url: `/pages/chat/chat-group-video?groupId=${groupId}&isHost=true
  217. &inviterId=${inviterId}&userInfos=${userInfos}`
  218. })
  219. },
  220. moveChatToTop() {
  221. let chatIdx = this.chatStore.findChatIdx(this.chat);
  222. this.chatStore.moveTop(chatIdx);
  223. },
  224. switchReceipt() {
  225. this.isReceipt = !this.isReceipt;
  226. },
  227. openAtBox() {
  228. this.$refs.atBox.init(this.atUserIds);
  229. this.$refs.atBox.open();
  230. },
  231. onAtComplete(atUserIds) {
  232. this.atUserIds = atUserIds;
  233. },
  234. onLongPressHead(msgInfo) {
  235. if (!msgInfo.selfSend && this.chat.type == "GROUP" && this.atUserIds.indexOf(msgInfo.sendId) < 0) {
  236. this.atUserIds.push(msgInfo.sendId);
  237. }
  238. },
  239. headImage(msgInfo) {
  240. if (this.chat.type == 'GROUP') {
  241. let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
  242. return member ? member.headImage : "";
  243. } else {
  244. return msgInfo.selfSend ? this.mine.headImageThumb : this.chat.headImage
  245. }
  246. },
  247. showName(msgInfo) {
  248. if (this.chat.type == 'GROUP') {
  249. let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
  250. return member ? member.showNickName : "";
  251. } else {
  252. return msgInfo.selfSend ? this.mine.nickName : this.chat.showName
  253. }
  254. },
  255. sendTextMessage() {
  256. this.editorCtx.getContents({
  257. success: (e) => {
  258. let sendText = this.isReceipt ? "【回执消息】" : "";
  259. e.delta.ops.forEach((op) => {
  260. if (op.insert.image) {
  261. // emo表情
  262. sendText += `#${op.attributes.alt};`
  263. } else(
  264. // 文字
  265. sendText += op.insert
  266. )
  267. })
  268. if (!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 + sendText + atText,
  278. atUserIds: this.atUserIds,
  279. receipt: this.isReceipt,
  280. type: 0
  281. }
  282. // 填充对方id
  283. this.fillTargetId(msgInfo, this.chat.targetId);
  284. this.sendMessageRequest(msgInfo).then((m) => {
  285. m.selfSend = true;
  286. this.chatStore.insertMessage(m, this.chat);
  287. // 会话置顶
  288. this.moveChatToTop();
  289. }).finally(() => {
  290. // 滚动到底部
  291. this.scrollToBottom();
  292. // 清空编辑框数据
  293. this.atUserIds = [];
  294. this.isReceipt = false;
  295. this.editorCtx.clear();
  296. });
  297. }
  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')
  345. },
  346. onShowToolsChatTab() {
  347. this.showRecord = false;
  348. this.switchChatTabBox('tools')
  349. },
  350. switchChatTabBox(chatTabBox) {
  351. this.chatTabBox = chatTabBox;
  352. this.reCalChatMainHeight();
  353. if (chatTabBox != 'tools' && this.$refs.fileUpload) {
  354. this.$refs.fileUpload.hide()
  355. }
  356. },
  357. selectEmoji(emoText) {
  358. let path = this.$emo.textToPath(emoText)
  359. // 先把键盘禁用了,否则会重新弹出键盘
  360. this.isReadOnly = true;
  361. this.isEmpty = false;
  362. this.$nextTick(() => {
  363. this.editorCtx.insertImage({
  364. src: path,
  365. alt: emoText,
  366. extClass: 'emoji-small',
  367. nowrap: true,
  368. complete: () => {
  369. this.isReadOnly = false;
  370. this.editorCtx.blur();
  371. }
  372. });
  373. })
  374. },
  375. onUploadImageBefore(file) {
  376. let data = {
  377. originUrl: file.path,
  378. thumbUrl: file.path
  379. }
  380. let msgInfo = {
  381. id: 0,
  382. tmpId: this.generateId(),
  383. fileId: file.uid,
  384. sendId: this.mine.id,
  385. content: JSON.stringify(data),
  386. sendTime: new Date().getTime(),
  387. selfSend: true,
  388. type: this.$enums.MESSAGE_TYPE.IMAGE,
  389. readedCount: 0,
  390. loadStatus: "loading",
  391. status: this.$enums.MESSAGE_STATUS.UNSEND
  392. }
  393. // 填充对方id
  394. this.fillTargetId(msgInfo, this.chat.targetId);
  395. // 插入消息
  396. this.chatStore.insertMessage(msgInfo);
  397. // 会话置顶
  398. this.moveChatToTop();
  399. // 借助file对象保存
  400. file.msgInfo = msgInfo;
  401. // 滚到最低部
  402. this.scrollToBottom();
  403. return true;
  404. },
  405. onUploadImageSuccess(file, res) {
  406. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  407. msgInfo.content = JSON.stringify(res.data);
  408. msgInfo.receipt = this.isReceipt
  409. this.sendMessageRequest(msgInfo).then((m) => {
  410. msgInfo.loadStatus = 'ok';
  411. msgInfo.id = m.id;
  412. this.isReceipt = false;
  413. this.chatStore.insertMessage(msgInfo);
  414. })
  415. },
  416. onUploadImageFail(file, err) {
  417. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  418. msgInfo.loadStatus = 'fail';
  419. this.chatStore.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.chatStore.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.sendMessageRequest(msgInfo).then((m) => {
  461. msgInfo.loadStatus = 'ok';
  462. msgInfo.id = m.id;
  463. this.isReceipt = false;
  464. this.chatStore.insertMessage(msgInfo);
  465. })
  466. },
  467. onUploadFileFail(file, res) {
  468. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  469. msgInfo.loadStatus = 'fail';
  470. this.chatStore.insertMessage(msgInfo);
  471. },
  472. onDeleteMessage(msgInfo) {
  473. uni.showModal({
  474. title: '删除消息',
  475. content: '确认删除消息?',
  476. success: (res) => {
  477. if (!res.cancel) {
  478. this.chatStore.deleteMessage(msgInfo);
  479. uni.showToast({
  480. title: "删除成功",
  481. icon: "none"
  482. })
  483. }
  484. }
  485. })
  486. },
  487. onRecallMessage(msgInfo) {
  488. uni.showModal({
  489. title: '撤回消息',
  490. content: '确认撤回消息?',
  491. success: (res) => {
  492. if (!res.cancel) {
  493. let url = `/message/${this.chat.type.toLowerCase()}/recall/${msgInfo.id}`
  494. this.$http({
  495. url: url,
  496. method: 'DELETE'
  497. }).then(() => {
  498. msgInfo = JSON.parse(JSON.stringify(msgInfo));
  499. msgInfo.type = this.$enums.MESSAGE_TYPE.RECALL;
  500. msgInfo.content = '你撤回了一条消息';
  501. msgInfo.status = this.$enums.MESSAGE_STATUS.RECALL;
  502. this.chatStore.insertMessage(msgInfo);
  503. })
  504. }
  505. }
  506. })
  507. },
  508. onCopyMessage(msgInfo) {
  509. uni.setClipboardData({
  510. data: msgInfo.content,
  511. success: () => {
  512. uni.showToast({ title: '已复制', icon: 'none' });
  513. },
  514. fail: () => {
  515. uni.showToast({ title: '复制失败', icon: 'none' });
  516. }
  517. });
  518. },
  519. onDownloadFile(msgInfo) {
  520. let url = JSON.parse(msgInfo.content).url;
  521. uni.downloadFile({
  522. url: url,
  523. success(res) {
  524. if (res.statusCode === 200) {
  525. var filePath = encodeURI(res.tempFilePath);
  526. uni.openDocument({
  527. filePath: filePath,
  528. showMenu: true
  529. });
  530. }
  531. },
  532. fail(e) {
  533. uni.showToast({
  534. title: "文件下载失败",
  535. icon: "none"
  536. })
  537. }
  538. });
  539. },
  540. onScrollToTop() {
  541. if (this.showMinIdx == 0) {
  542. console.log("消息已滚动到顶部")
  543. return;
  544. }
  545. // #ifndef H5
  546. // 防止滚动条定格在顶部,不能一直往上滚
  547. this.scrollToMsgIdx(this.showMinIdx);
  548. // #endif
  549. // 多展示0条信息
  550. this.showMinIdx = this.showMinIdx > 20 ? this.showMinIdx - 20 : 0;
  551. },
  552. onShowMore() {
  553. if (this.chat.type == "GROUP") {
  554. uni.navigateTo({
  555. url: "/pages/group/group-info?id=" + this.group.id
  556. })
  557. } else {
  558. uni.navigateTo({
  559. url: "/pages/common/user-info?id=" + this.friend.id
  560. })
  561. }
  562. },
  563. onTextInput(e) {
  564. this.isEmpty = e.detail.html == '<p><br></p>'
  565. },
  566. onEditorReady() {
  567. const query = uni.createSelectorQuery().in(this);
  568. query.select('#editor').context((res) => {
  569. this.editorCtx = res.context
  570. }).exec()
  571. },
  572. onEditorFocus(e) {
  573. this.isFocus = true;
  574. this.scrollToBottom()
  575. this.switchChatTabBox('none')
  576. },
  577. onEditorBlur(e) {
  578. this.isFocus = false;
  579. },
  580. loadReaded(fid) {
  581. this.$http({
  582. url: `/message/private/maxReadedId?friendId=${fid}`,
  583. method: 'get'
  584. }).then((id) => {
  585. this.chatStore.readedMessage({
  586. friendId: fid,
  587. maxId: id
  588. });
  589. });
  590. },
  591. readedMessage() {
  592. if (this.unreadCount == 0) {
  593. return;
  594. }
  595. let url = ""
  596. if (this.chat.type == "GROUP") {
  597. url = `/message/group/readed?groupId=${this.chat.targetId}`
  598. } else {
  599. url = `/message/private/readed?friendId=${this.chat.targetId}`
  600. }
  601. this.$http({
  602. url: url,
  603. method: 'PUT'
  604. }).then(() => {
  605. this.chatStore.resetUnreadCount(this.chat)
  606. this.scrollToBottom();
  607. })
  608. },
  609. loadGroup(groupId) {
  610. this.$http({
  611. url: `/group/find/${groupId}`,
  612. method: 'GET'
  613. }).then((group) => {
  614. this.group = group;
  615. this.chatStore.updateChatFromGroup(group);
  616. this.groupStore.updateGroup(group);
  617. });
  618. this.$http({
  619. url: `/group/members/${groupId}`,
  620. method: 'GET'
  621. }).then((groupMembers) => {
  622. this.groupMembers = groupMembers;
  623. });
  624. },
  625. loadFriend(friendId) {
  626. // 获取对方最新信息
  627. this.$http({
  628. url: `/user/find/${friendId}`,
  629. method: 'GET'
  630. }).then((friend) => {
  631. this.friend = friend;
  632. this.chatStore.updateChatFromFriend(friend);
  633. this.friendStore.updateFriend(friend);
  634. })
  635. },
  636. rpxTopx(rpx) {
  637. // px转换成rpx
  638. let info = uni.getSystemInfoSync()
  639. let px = info.windowWidth * rpx / 750;
  640. return Math.floor(rpx);
  641. },
  642. sendMessageRequest(msgInfo) {
  643. return new Promise((resolve, reject) => {
  644. // 请求入队列,防止请求"后发先至",导致消息错序
  645. this.reqQueue.push({ msgInfo, resolve, reject });
  646. this.processReqQueue();
  647. })
  648. },
  649. processReqQueue() {
  650. if (this.reqQueue.length && !this.isSending) {
  651. this.isSending = true;
  652. const reqData = this.reqQueue.shift();
  653. this.$http({
  654. url: this.messageAction,
  655. method: 'post',
  656. data: reqData.msgInfo
  657. }).then((res) => {
  658. reqData.resolve(res)
  659. }).catch((e) => {
  660. reqData.reject(e)
  661. }).finally(() => {
  662. this.isSending = false;
  663. // 发送下一条请求
  664. this.processReqQueue();
  665. })
  666. }
  667. },
  668. listenKeyBoard() {
  669. // #ifdef H5
  670. // 由于H5无法触发TextArea的@keyboardheightchange事件,所以通过
  671. // 监听屏幕高度变化来实现键盘监听
  672. let initHeight = window.innerHeight;
  673. window.addEventListener('resize', () => {
  674. let keyboardHeight = initHeight - window.innerHeight;
  675. this.isShowKeyBoard = keyboardHeight > 0;
  676. if (this.isShowKeyBoard) {
  677. this.keyboardHeight = keyboardHeight;
  678. }
  679. this.reCalChatMainHeight();
  680. });
  681. // #endif
  682. // #ifndef H5
  683. uni.onKeyboardHeightChange((res) => {
  684. this.isShowKeyBoard = res.height > 0;
  685. if (this.isShowKeyBoard) {
  686. this.keyboardHeight = res.height; // 获取并保存键盘高度
  687. }
  688. this.reCalChatMainHeight();
  689. });
  690. // #endif
  691. },
  692. reCalChatMainHeight() {
  693. const sysInfo = uni.getSystemInfoSync();
  694. let h = sysInfo.windowHeight;
  695. // 减去标题栏高度
  696. h -= 50;
  697. // #ifdef H5
  698. // h5的sysInfo.windowHeight默认就已经减去键盘高度了
  699. if (this.chatTabBox != 'none') {
  700. h -= this.keyboardHeight;
  701. }
  702. // #endif
  703. // #ifndef H5
  704. // 减去状态栏高度
  705. h -= sysInfo.statusBarHeight;
  706. if (this.isShowKeyBoard || this.chatTabBox != 'none') {
  707. h -= this.keyboardHeight;
  708. }
  709. // #endif
  710. console.log("h:", h)
  711. this.chatMainHeight = h;
  712. },
  713. generateId() {
  714. // 生成临时id
  715. return String(new Date().getTime()) + String(Math.floor(Math.random() * 1000));
  716. }
  717. },
  718. computed: {
  719. mine() {
  720. return this.userStore.userInfo;
  721. },
  722. title() {
  723. if (!this.chat) {
  724. return "";
  725. }
  726. let title = this.chat.showName;
  727. if (this.chat.type == "GROUP") {
  728. let size = this.groupMembers.filter(m => !m.quit).length;
  729. title += `(${size})`;
  730. }
  731. return title;
  732. },
  733. messageAction() {
  734. return `/message/${this.chat.type.toLowerCase()}/send`;
  735. },
  736. messageSize() {
  737. if (!this.chat || !this.chat.messages) {
  738. return 0;
  739. }
  740. return this.chat.messages.length;
  741. },
  742. unreadCount() {
  743. if (!this.chat || !this.chat.unreadCount) {
  744. return 0;
  745. }
  746. return this.chat.unreadCount;
  747. },
  748. atUserItems() {
  749. let atUsers = [];
  750. this.atUserIds.forEach((id) => {
  751. if (id == -1) {
  752. atUsers.push({
  753. id: -1,
  754. showNickName: "全体成员"
  755. })
  756. return;
  757. }
  758. let member = this.groupMembers.find((m) => m.userId == id);
  759. if (member) {
  760. atUsers.push(member);
  761. }
  762. })
  763. return atUsers;
  764. }
  765. },
  766. watch: {
  767. messageSize: function(newSize, oldSize) {
  768. // 接收到消息时滚动到底部
  769. if (newSize > oldSize) {
  770. let pages = getCurrentPages();
  771. let curPage = pages[pages.length - 1].route;
  772. if (curPage == "pages/chat/chat-box") {
  773. this.scrollToBottom();
  774. } else {
  775. this.needScrollToBottom = true;
  776. }
  777. }
  778. },
  779. unreadCount: {
  780. handler(newCount, oldCount) {
  781. if (newCount > 0) {
  782. // 消息已读
  783. this.readedMessage()
  784. }
  785. }
  786. }
  787. },
  788. onLoad(options) {
  789. // 聊天数据
  790. this.chat = this.chatStore.chats[options.chatIdx];
  791. // 初始状态只显示20条消息
  792. let size = this.messageSize;
  793. this.showMinIdx = size > 20 ? size - 20 : 0;
  794. // 消息已读
  795. this.readedMessage()
  796. // 加载好友或群聊信息
  797. if (this.chat.type == "GROUP") {
  798. this.loadGroup(this.chat.targetId);
  799. } else {
  800. this.loadFriend(this.chat.targetId);
  801. this.loadReaded(this.chat.targetId)
  802. }
  803. // 激活当前会话
  804. this.chatStore.activeChat(options.chatIdx);
  805. // 复位回执消息
  806. this.isReceipt = false;
  807. // 监听键盘高度
  808. this.listenKeyBoard();
  809. // 计算聊天窗口高度
  810. this.$nextTick(()=>this.reCalChatMainHeight())
  811. },
  812. onShow() {
  813. if (this.needScrollToBottom) {
  814. // 页面滚到底部
  815. this.scrollToBottom();
  816. this.needScrollToBottom = false;
  817. }
  818. }
  819. }
  820. </script>
  821. <style lang="scss" scoped>
  822. .chat-box {
  823. $icon-color: rgba(0, 0, 0, 0.88);
  824. position: relative;
  825. background-color: #fafafa;
  826. .header {
  827. display: flex;
  828. justify-content: center;
  829. align-items: center;
  830. height: 60rpx;
  831. padding: 5px;
  832. background-color: #fafafa;
  833. line-height: 50px;
  834. font-size: $im-font-size-large;
  835. box-shadow: $im-box-shadow-lighter;
  836. z-index: 1;
  837. .btn-side {
  838. position: absolute;
  839. line-height: 60rpx;
  840. cursor: pointer;
  841. &.right {
  842. right: 30rpx;
  843. }
  844. }
  845. }
  846. .chat-main-box {
  847. // #ifdef H5
  848. top: $im-nav-bar-height;
  849. // #endif
  850. // #ifndef H5
  851. top: calc($im-nav-bar-height + var(--status-bar-height));
  852. // #endif
  853. position: fixed;
  854. width: 100%;
  855. display: flex;
  856. flex-direction: column;
  857. z-index: 9;
  858. .chat-msg {
  859. flex: 1;
  860. padding: 0;
  861. overflow: hidden;
  862. position: relative;
  863. background-color: white;
  864. .scroll-box {
  865. height: 100%;
  866. }
  867. }
  868. .chat-at-bar {
  869. display: flex;
  870. align-items: center;
  871. padding: 0 10rpx;
  872. .icon-at {
  873. font-size: $im-font-size-larger;
  874. color: $im-color-primary;
  875. font-weight: bold;
  876. }
  877. .chat-at-scroll-box {
  878. flex: 1;
  879. width: 80%;
  880. .chat-at-items {
  881. display: flex;
  882. align-items: center;
  883. height: 70rpx;
  884. .chat-at-item {
  885. padding: 0 3rpx;
  886. }
  887. }
  888. }
  889. }
  890. .send-bar {
  891. display: flex;
  892. align-items: center;
  893. padding: 10rpx;
  894. border-top: $im-border solid 1px;
  895. background-color: $im-bg;
  896. min-height: 80rpx;
  897. margin-bottom: 14rpx;
  898. .iconfont {
  899. font-size: 60rpx;
  900. margin: 0 10rpx;
  901. color: $icon-color;
  902. }
  903. .chat-record {
  904. flex: 1;
  905. }
  906. .send-text {
  907. flex: 1;
  908. overflow: auto;
  909. padding: 14rpx 20rpx;
  910. background-color: #fff;
  911. border-radius: 8rpx;
  912. font-size: $im-font-size;
  913. box-sizing: border-box;
  914. margin: 0 10rpx;
  915. position: relative;
  916. .send-text-area {
  917. width: 100%;
  918. height: 100%;
  919. min-height: 40rpx;
  920. max-height: 200rpx;
  921. font-size: 30rpx;
  922. }
  923. }
  924. .btn-send {
  925. margin: 5rpx;
  926. }
  927. }
  928. }
  929. .chat-tab-bar {
  930. position: fixed;
  931. bottom: 0;
  932. background-color: $im-bg;
  933. .chat-tools {
  934. display: flex;
  935. flex-wrap: wrap;
  936. align-items: top;
  937. height: 310px;
  938. padding: 40rpx;
  939. box-sizing: border-box;
  940. .chat-tools-item {
  941. width: 25%;
  942. padding: 16rpx;
  943. box-sizing: border-box;
  944. display: flex;
  945. flex-direction: column;
  946. align-items: center;
  947. .tool-icon {
  948. padding: 26rpx;
  949. font-size: 54rpx;
  950. border-radius: 20%;
  951. background-color: white;
  952. color: $icon-color;
  953. &:active {
  954. background-color: $im-bg-active;
  955. }
  956. }
  957. .tool-name {
  958. height: 60rpx;
  959. line-height: 60rpx;
  960. font-size: 28rpx;
  961. }
  962. }
  963. }
  964. .chat-emotion {
  965. height: 310px;
  966. padding: 20rpx;
  967. box-sizing: border-box;
  968. .emotion-item-list {
  969. display: flex;
  970. flex-wrap: wrap;
  971. justify-content: space-between;
  972. align-content: center;
  973. .emotion-item {
  974. text-align: center;
  975. cursor: pointer;
  976. padding: 5px;
  977. }
  978. }
  979. }
  980. }
  981. }
  982. </style>