chat-box.vue 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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 v-if="showKeyBoard"></view>
  106. </view>
  107. <!-- @用户时选择成员 -->
  108. <chat-at-box ref="atBox" :ownerId="group.ownerId" :members="groupMembers"
  109. @complete="onAtComplete"></chat-at-box>
  110. <!-- 群语音通话时选择成员 -->
  111. <!-- #ifndef MP-WEIXIN -->
  112. <group-member-selector ref="selBox" :members="groupMembers" :maxSize="configStore.webrtc.maxChannel"
  113. @complete="onInviteOk"></group-member-selector>
  114. <group-rtc-join ref="rtcJoin" :groupId="group.id"></group-rtc-join>
  115. <!-- #endif -->
  116. </view>
  117. </template>
  118. <script>
  119. import UNI_APP from '@/.env.js';
  120. export default {
  121. data() {
  122. return {
  123. chat: {},
  124. friend: {},
  125. group: {},
  126. groupMembers: [],
  127. isReceipt: false, // 是否回执消息
  128. scrollMsgIdx: 0, // 滚动条定位为到哪条消息
  129. chatTabBox: 'none',
  130. showRecord: false,
  131. keyboardHeight: 300,
  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. if (chatTabBox != 'tools' && this.$refs.fileUpload) {
  353. this.$refs.fileUpload.hide()
  354. }
  355. },
  356. selectEmoji(emoText) {
  357. let path = this.$emo.textToPath(emoText)
  358. // 先把键盘禁用了,否则会重新弹出键盘
  359. this.isReadOnly = true;
  360. this.isEmpty = false;
  361. this.$nextTick(() => {
  362. this.editorCtx.insertImage({
  363. src: path,
  364. alt: emoText,
  365. extClass: 'emoji-small',
  366. nowrap: true,
  367. complete: () => {
  368. this.isReadOnly = false;
  369. this.editorCtx.blur();
  370. }
  371. });
  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. onCopyMessage(msgInfo) {
  508. uni.setClipboardData({
  509. data: msgInfo.content,
  510. success: () => {
  511. uni.showToast({ title: '已复制', icon: 'none' });
  512. },
  513. fail: () => {
  514. uni.showToast({ title: '复制失败', icon: 'none' });
  515. }
  516. });
  517. },
  518. onDownloadFile(msgInfo) {
  519. let url = JSON.parse(msgInfo.content).url;
  520. uni.downloadFile({
  521. url: url,
  522. success(res) {
  523. if (res.statusCode === 200) {
  524. var filePath = encodeURI(res.tempFilePath);
  525. uni.openDocument({
  526. filePath: filePath,
  527. showMenu: true
  528. });
  529. }
  530. },
  531. fail(e) {
  532. uni.showToast({
  533. title: "文件下载失败",
  534. icon: "none"
  535. })
  536. }
  537. });
  538. },
  539. onScrollToTop() {
  540. if (this.showMinIdx == 0) {
  541. console.log("消息已滚动到顶部")
  542. return;
  543. }
  544. // #ifndef H5
  545. // 防止滚动条定格在顶部,不能一直往上滚
  546. this.scrollToMsgIdx(this.showMinIdx);
  547. // #endif
  548. // 多展示0条信息
  549. this.showMinIdx = this.showMinIdx > 20 ? this.showMinIdx - 20 : 0;
  550. },
  551. onShowMore() {
  552. if (this.chat.type == "GROUP") {
  553. uni.navigateTo({
  554. url: "/pages/group/group-info?id=" + this.group.id
  555. })
  556. } else {
  557. uni.navigateTo({
  558. url: "/pages/common/user-info?id=" + this.friend.id
  559. })
  560. }
  561. },
  562. onTextInput(e) {
  563. this.isEmpty = e.detail.html == '<p><br></p>'
  564. },
  565. onEditorReady() {
  566. const query = uni.createSelectorQuery().in(this);
  567. query.select('#editor').context((res) => {
  568. this.editorCtx = res.context
  569. }).exec()
  570. },
  571. onEditorFocus(e) {
  572. this.isFocus = true;
  573. this.scrollToBottom()
  574. this.switchChatTabBox('none')
  575. },
  576. onEditorBlur(e) {
  577. this.isFocus = false;
  578. },
  579. loadReaded(fid) {
  580. this.$http({
  581. url: `/message/private/maxReadedId?friendId=${fid}`,
  582. method: 'get'
  583. }).then((id) => {
  584. this.chatStore.readedMessage({
  585. friendId: fid,
  586. maxId: id
  587. });
  588. });
  589. },
  590. readedMessage() {
  591. if (this.unreadCount == 0) {
  592. return;
  593. }
  594. let url = ""
  595. if (this.chat.type == "GROUP") {
  596. url = `/message/group/readed?groupId=${this.chat.targetId}`
  597. } else {
  598. url = `/message/private/readed?friendId=${this.chat.targetId}`
  599. }
  600. this.$http({
  601. url: url,
  602. method: 'PUT'
  603. }).then(() => {
  604. this.chatStore.resetUnreadCount(this.chat)
  605. this.scrollToBottom();
  606. })
  607. },
  608. loadGroup(groupId) {
  609. this.$http({
  610. url: `/group/find/${groupId}`,
  611. method: 'GET'
  612. }).then((group) => {
  613. this.group = group;
  614. this.chatStore.updateChatFromGroup(group);
  615. this.groupStore.updateGroup(group);
  616. });
  617. this.$http({
  618. url: `/group/members/${groupId}`,
  619. method: 'GET'
  620. }).then((groupMembers) => {
  621. this.groupMembers = groupMembers;
  622. });
  623. },
  624. loadFriend(friendId) {
  625. // 获取对方最新信息
  626. this.$http({
  627. url: `/user/find/${friendId}`,
  628. method: 'GET'
  629. }).then((friend) => {
  630. this.friend = friend;
  631. this.chatStore.updateChatFromFriend(friend);
  632. this.friendStore.updateFriend(friend);
  633. })
  634. },
  635. rpxTopx(rpx) {
  636. // px转换成rpx
  637. let info = uni.getSystemInfoSync()
  638. let px = info.windowWidth * rpx / 750;
  639. return Math.floor(rpx);
  640. },
  641. sendMessageRequest(msgInfo) {
  642. return new Promise((resolve, reject) => {
  643. // 请求入队列,防止请求"后发先至",导致消息错序
  644. this.reqQueue.push({ msgInfo, resolve, reject });
  645. this.processReqQueue();
  646. })
  647. },
  648. processReqQueue() {
  649. if (this.reqQueue.length && !this.isSending) {
  650. this.isSending = true;
  651. const reqData = this.reqQueue.shift();
  652. this.$http({
  653. url: this.messageAction,
  654. method: 'post',
  655. data: reqData.msgInfo
  656. }).then((res) => {
  657. reqData.resolve(res)
  658. }).catch((e) => {
  659. reqData.reject(e)
  660. }).finally(() => {
  661. this.isSending = false;
  662. // 发送下一条请求
  663. this.processReqQueue();
  664. })
  665. }
  666. },
  667. listenKeyBoard() {
  668. // #ifdef H5
  669. // 由于H5无法触发TextArea的@keyboardheightchange事件,所以通过
  670. // 监听屏幕高度变化来实现键盘监听
  671. let initHeight = window.innerHeight;
  672. window.addEventListener('resize', () => {
  673. let keyboardHeight = initHeight - window.innerHeight;
  674. this.isShowKeyBoard = keyboardHeight > 0;
  675. if (this.isShowKeyBoard) {
  676. this.keyboardHeight = keyboardHeight;
  677. }
  678. });
  679. // #endif
  680. // #ifndef H5
  681. uni.onKeyboardHeightChange((res) => {
  682. this.isShowKeyBoard = res.height > 0;
  683. if (this.isShowKeyBoard) {
  684. this.keyboardHeight = res.height; // 获取并保存键盘高度
  685. }
  686. });
  687. // #endif
  688. },
  689. generateId() {
  690. // 生成临时id
  691. return String(new Date().getTime()) + String(Math.floor(Math.random() * 1000));
  692. }
  693. },
  694. computed: {
  695. mine() {
  696. return this.userStore.userInfo;
  697. },
  698. title() {
  699. if (!this.chat) {
  700. return "";
  701. }
  702. let title = this.chat.showName;
  703. if (this.chat.type == "GROUP") {
  704. let size = this.groupMembers.filter(m => !m.quit).length;
  705. title += `(${size})`;
  706. }
  707. return title;
  708. },
  709. messageAction() {
  710. return `/message/${this.chat.type.toLowerCase()}/send`;
  711. },
  712. messageSize() {
  713. if (!this.chat || !this.chat.messages) {
  714. return 0;
  715. }
  716. return this.chat.messages.length;
  717. },
  718. unreadCount() {
  719. if (!this.chat || !this.chat.unreadCount) {
  720. return 0;
  721. }
  722. return this.chat.unreadCount;
  723. },
  724. atUserItems() {
  725. let atUsers = [];
  726. this.atUserIds.forEach((id) => {
  727. if (id == -1) {
  728. atUsers.push({
  729. id: -1,
  730. showNickName: "全体成员"
  731. })
  732. return;
  733. }
  734. let member = this.groupMembers.find((m) => m.userId == id);
  735. if (member) {
  736. atUsers.push(member);
  737. }
  738. })
  739. return atUsers;
  740. },
  741. chatMainHeight() {
  742. const sysInfo = uni.getSystemInfoSync();
  743. let h = sysInfo.windowHeight;
  744. // 减去标题栏高度
  745. h -= 50;
  746. // #ifdef H5
  747. // h5的sysInfo.windowHeight默认就已经减去键盘高度了
  748. if (this.chatTabBox != 'none') {
  749. h -= this.keyboardHeight;
  750. }
  751. // #endif
  752. // #ifndef H5
  753. // 减去状态栏高度
  754. h -= sysInfo.statusBarHeight;
  755. if (this.isShowKeyBoard || this.chatTabBox != 'none') {
  756. h -= this.keyboardHeight;
  757. }
  758. // #endif
  759. return h;
  760. }
  761. },
  762. watch: {
  763. messageSize: function(newSize, oldSize) {
  764. // 接收到消息时滚动到底部
  765. if (newSize > oldSize) {
  766. let pages = getCurrentPages();
  767. let curPage = pages[pages.length - 1].route;
  768. if (curPage == "pages/chat/chat-box") {
  769. this.scrollToBottom();
  770. } else {
  771. this.needScrollToBottom = true;
  772. }
  773. }
  774. },
  775. unreadCount: {
  776. handler(newCount, oldCount) {
  777. if (newCount > 0) {
  778. // 消息已读
  779. this.readedMessage()
  780. }
  781. }
  782. }
  783. },
  784. onLoad(options) {
  785. // 聊天数据
  786. this.chat = this.chatStore.chats[options.chatIdx];
  787. // 初始状态只显示20条消息
  788. let size = this.messageSize;
  789. this.showMinIdx = size > 20 ? size - 20 : 0;
  790. // 消息已读
  791. this.readedMessage()
  792. // 加载好友或群聊信息
  793. if (this.chat.type == "GROUP") {
  794. this.loadGroup(this.chat.targetId);
  795. } else {
  796. this.loadFriend(this.chat.targetId);
  797. this.loadReaded(this.chat.targetId)
  798. }
  799. // 激活当前会话
  800. this.chatStore.activeChat(options.chatIdx);
  801. // 复位回执消息
  802. this.isReceipt = false;
  803. // 监听键盘高度
  804. this.listenKeyBoard();
  805. },
  806. onShow() {
  807. if (this.needScrollToBottom) {
  808. // 页面滚到底部
  809. this.scrollToBottom();
  810. this.needScrollToBottom = false;
  811. }
  812. }
  813. }
  814. </script>
  815. <style lang="scss" scoped>
  816. .chat-box {
  817. $icon-color: rgba(0, 0, 0, 0.88);
  818. position: relative;
  819. background-color: #fafafa;
  820. .header {
  821. display: flex;
  822. justify-content: center;
  823. align-items: center;
  824. height: 60rpx;
  825. padding: 5px;
  826. background-color: #fafafa;
  827. line-height: 50px;
  828. font-size: $im-font-size-large;
  829. box-shadow: $im-box-shadow-lighter;
  830. z-index: 1;
  831. .btn-side {
  832. position: absolute;
  833. line-height: 60rpx;
  834. cursor: pointer;
  835. &.right {
  836. right: 30rpx;
  837. }
  838. }
  839. }
  840. .chat-main-box {
  841. // #ifdef H5
  842. top: $im-nav-bar-height;
  843. // #endif
  844. // #ifndef H5
  845. top: calc($im-nav-bar-height + var(--status-bar-height));
  846. // #endif
  847. position: fixed;
  848. width: 100%;
  849. display: flex;
  850. flex-direction: column;
  851. z-index: 9;
  852. .chat-msg {
  853. flex: 1;
  854. padding: 0;
  855. overflow: hidden;
  856. position: relative;
  857. background-color: white;
  858. .scroll-box {
  859. height: 100%;
  860. }
  861. }
  862. .chat-at-bar {
  863. display: flex;
  864. align-items: center;
  865. padding: 0 10rpx;
  866. .icon-at {
  867. font-size: $im-font-size-larger;
  868. color: $im-color-primary;
  869. font-weight: bold;
  870. }
  871. .chat-at-scroll-box {
  872. flex: 1;
  873. width: 80%;
  874. .chat-at-items {
  875. display: flex;
  876. align-items: center;
  877. height: 70rpx;
  878. .chat-at-item {
  879. padding: 0 3rpx;
  880. }
  881. }
  882. }
  883. }
  884. .send-bar {
  885. display: flex;
  886. align-items: center;
  887. padding: 10rpx;
  888. border-top: $im-border solid 1px;
  889. background-color: $im-bg;
  890. min-height: 80rpx;
  891. margin-bottom: 14rpx;
  892. .iconfont {
  893. font-size: 60rpx;
  894. margin: 0 10rpx;
  895. color: $icon-color;
  896. }
  897. .chat-record {
  898. flex: 1;
  899. }
  900. .send-text {
  901. flex: 1;
  902. overflow: auto;
  903. padding: 14rpx 20rpx;
  904. background-color: #fff;
  905. border-radius: 8rpx;
  906. font-size: $im-font-size;
  907. box-sizing: border-box;
  908. margin: 0 10rpx;
  909. position: relative;
  910. .send-text-area {
  911. width: 100%;
  912. height: 100%;
  913. min-height: 40rpx;
  914. max-height: 200rpx;
  915. font-size: 30rpx;
  916. }
  917. }
  918. .btn-send {
  919. margin: 5rpx;
  920. }
  921. }
  922. }
  923. .chat-tab-bar {
  924. position: fixed;
  925. bottom: 0;
  926. background-color: $im-bg;
  927. .chat-tools {
  928. display: flex;
  929. flex-wrap: wrap;
  930. align-items: top;
  931. height: 310px;
  932. padding: 40rpx;
  933. box-sizing: border-box;
  934. .chat-tools-item {
  935. width: 25%;
  936. padding: 16rpx;
  937. box-sizing: border-box;
  938. display: flex;
  939. flex-direction: column;
  940. align-items: center;
  941. .tool-icon {
  942. padding: 26rpx;
  943. font-size: 54rpx;
  944. border-radius: 20%;
  945. background-color: white;
  946. color: $icon-color;
  947. &:active {
  948. background-color: $im-bg-active;
  949. }
  950. }
  951. .tool-name {
  952. height: 60rpx;
  953. line-height: 60rpx;
  954. font-size: 28rpx;
  955. }
  956. }
  957. }
  958. .chat-emotion {
  959. height: 310px;
  960. padding: 20rpx;
  961. box-sizing: border-box;
  962. .emotion-item-list {
  963. display: flex;
  964. flex-wrap: wrap;
  965. justify-content: space-between;
  966. align-content: center;
  967. .emotion-item {
  968. text-align: center;
  969. cursor: pointer;
  970. padding: 5px;
  971. }
  972. }
  973. }
  974. }
  975. }
  976. </style>