ChatBox.vue 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. <template>
  2. <div class="chat-box" @click="closeRefBox()" @mousemove="readedMessage()">
  3. <el-container>
  4. <el-header height="56px">
  5. <span>{{ title }}</span>
  6. <span title="群聊信息" v-show="this.chat.type == 'GROUP'" class="btn-side el-icon-more"
  7. @click="showSide = !showSide"></span>
  8. </el-header>
  9. <el-main style="padding: 0;">
  10. <el-container>
  11. <el-container class="content-box">
  12. <el-main class="im-chat-main" id="chatScrollBox" @scroll="onScroll">
  13. <div class="im-chat-box">
  14. <ul>
  15. <li v-for="(msgInfo, idx) in chat.messages" :key="idx">
  16. <chat-message-item v-if="idx >= showMinIdx" @call="onCall(msgInfo.type)"
  17. :mine="msgInfo.sendId == mine.id" :headImage="headImage(msgInfo)"
  18. :showName="showName(msgInfo)" :msgInfo="msgInfo"
  19. :groupMembers="groupMembers" @delete="deleteMessage"
  20. @recall="recallMessage">
  21. </chat-message-item>
  22. </li>
  23. </ul>
  24. </div>
  25. </el-main>
  26. <el-footer height="240px" class="im-chat-footer">
  27. <div class="chat-tool-bar">
  28. <div title="表情" class="icon iconfont icon-emoji" ref="emotion"
  29. @click.stop="showEmotionBox()">
  30. </div>
  31. <div title="发送图片">
  32. <file-upload :action="'/image/upload'" :maxSize="5 * 1024 * 1024"
  33. :fileTypes="['image/jpeg', 'image/png', 'image/jpg', 'image/webp', 'image/gif']"
  34. @before="onImageBefore" @success="onImageSuccess" @fail="onImageFail">
  35. <i class="el-icon-picture-outline"></i>
  36. </file-upload>
  37. </div>
  38. <div title="发送文件">
  39. <file-upload :action="'/file/upload'" :maxSize="10 * 1024 * 1024"
  40. @before="onFileBefore" @success="onFileSuccess" @fail="onFileFail">
  41. <i class="el-icon-wallet"></i>
  42. </file-upload>
  43. </div>
  44. <div title="回执消息" v-show="chat.type == 'GROUP'" class="icon iconfont icon-receipt"
  45. :class="isReceipt ? 'chat-tool-active' : ''" @click="onSwitchReceipt">
  46. </div>
  47. <div title="发送语音" class="el-icon-microphone" @click="showRecordBox()">
  48. </div>
  49. <div title="语音通话" v-show="chat.type == 'PRIVATE'" class="el-icon-phone-outline"
  50. @click="showPrivateVideo('voice')">
  51. </div>
  52. <div title="语音通话" v-show="chat.type == 'GROUP'" class="el-icon-phone-outline"
  53. @click="onGroupVideo()">
  54. </div>
  55. <div title="视频通话" v-show="chat.type == 'PRIVATE'" class="el-icon-video-camera"
  56. @click="showPrivateVideo('video')">
  57. </div>
  58. <div title="聊天记录" class="el-icon-chat-dot-round" @click="showHistoryBox()"></div>
  59. </div>
  60. <div class="send-content-area">
  61. <div contenteditable="true" v-show="!sendImageUrl" ref="editBox" class="send-text-area"
  62. :disabled="lockMessage" @paste.prevent="onEditorPaste"
  63. @compositionstart="onEditorCompositionStart"
  64. @compositionend="onEditorCompositionEnd" @input="onEditorInput"
  65. :placeholder="placeholder" @blur="onEditBoxBlur()" @keydown.down="onKeyDown"
  66. @keydown.up="onKeyUp" @keydown.enter.prevent="onKeyEnter">x
  67. </div>
  68. <div v-show="sendImageUrl" class="send-image-area">
  69. <div class="send-image-box">
  70. <img class="send-image" :src="sendImageUrl" />
  71. <span class="send-image-close el-icon-close" title="删除"
  72. @click="removeSendImage()"></span>
  73. </div>
  74. </div>
  75. <div class="send-btn-area">
  76. <el-button type="primary" size="small" @click="sendMessage()">发送</el-button>
  77. </div>
  78. </div>
  79. </el-footer>
  80. </el-container>
  81. <el-aside class="chat-group-side-box" width="300px" v-if="showSide">
  82. <chat-group-side :group="group" :groupMembers="groupMembers" @reload="loadGroup(group.id)">
  83. </chat-group-side>
  84. </el-aside>
  85. </el-container>
  86. </el-main>
  87. <emotion ref="emoBox" @emotion="onEmotion"></Emotion>
  88. <chat-at-box ref="atBox" :ownerId="group.ownerId" :members="groupMembers" :search-text="atSearchText"
  89. @select="onAtSelect"></chat-at-box>
  90. <chat-record :visible="showRecord" @close="closeRecordBox" @send="onSendRecord"></chat-record>
  91. <group-member-selector ref="rtcSel" :groupId="group.id" @complete="onInviteOk"></group-member-selector>
  92. <rtc-group-join ref="rtcJoin" :groupId="group.id"></rtc-group-join>
  93. <chat-history :visible="showHistory" :chat="chat" :friend="friend" :group="group"
  94. :groupMembers="groupMembers" @close="closeHistoryBox"></chat-history>
  95. </el-container>
  96. </div>
  97. </template>
  98. <script>
  99. import ChatGroupSide from "./ChatGroupSide.vue";
  100. import ChatMessageItem from "./ChatMessageItem.vue";
  101. import FileUpload from "../common/FileUpload.vue";
  102. import Emotion from "../common/Emotion.vue";
  103. import ChatRecord from "./ChatRecord.vue";
  104. import ChatHistory from "./ChatHistory.vue";
  105. import ChatAtBox from "./ChatAtBox.vue"
  106. import GroupMemberSelector from "../group/GroupMemberSelector.vue"
  107. import RtcGroupJoin from "../rtc/RtcGroupJoin.vue"
  108. export default {
  109. name: "chatPrivate",
  110. components: {
  111. ChatMessageItem,
  112. FileUpload,
  113. ChatGroupSide,
  114. Emotion,
  115. ChatRecord,
  116. ChatHistory,
  117. ChatAtBox,
  118. GroupMemberSelector,
  119. RtcGroupJoin
  120. },
  121. props: {
  122. chat: {
  123. type: Object
  124. }
  125. },
  126. data() {
  127. return {
  128. friend: {},
  129. group: {},
  130. groupMembers: [],
  131. sendImageUrl: "",
  132. sendImageFile: "",
  133. placeholder: "",
  134. isReceipt: true,
  135. showRecord: false, // 是否显示语音录制弹窗
  136. showSide: false, // 是否显示群聊信息栏
  137. showHistory: false, // 是否显示历史聊天记录
  138. lockMessage: false, // 是否锁定发送,
  139. showMinIdx: 0, // 下标低于showMinIdx的消息不显示,否则页面会很卡
  140. atSearchText: "",
  141. focusNode: null, // 缓存光标所在节点
  142. focusOffset: null, // 缓存光标所在节点位置
  143. zhLock: false // 解决中文输入法触发英文的情况
  144. }
  145. },
  146. methods: {
  147. moveChatToTop() {
  148. let chatIdx = this.$store.getters.findChatIdx(this.chat);
  149. this.$store.commit("moveTop", chatIdx);
  150. },
  151. closeRefBox() {
  152. this.$refs.emoBox.close();
  153. this.$refs.atBox.close();
  154. },
  155. onCall(type) {
  156. if (type == this.$enums.MESSAGE_TYPE.ACT_RT_VOICE) {
  157. this.showPrivateVideo('voice');
  158. } else if (type == this.$enums.MESSAGE_TYPE.ACT_RT_VIDEO) {
  159. this.showPrivateVideo('video');
  160. }
  161. },
  162. onKeyDown() {
  163. if (this.$refs.atBox.show) {
  164. this.$refs.atBox.moveDown()
  165. }
  166. },
  167. onKeyUp() {
  168. if (this.$refs.atBox.show) {
  169. this.$refs.atBox.moveUp()
  170. }
  171. },
  172. onKeyEnter() {
  173. if (this.$refs.atBox.show) {
  174. // 键盘操作不会自动修正焦点,需要手动修正,原因不详
  175. this.focusOffset += this.atSearchText.length;
  176. this.$refs.atBox.select();
  177. } else {
  178. this.sendMessage();
  179. }
  180. },
  181. onEditBoxBlur() {
  182. let selection = window.getSelection()
  183. // 记录光标位置(点击emoji时)
  184. this.focusNode = selection.focusNode;
  185. this.focusOffset = selection.focusOffset;
  186. },
  187. onEditorInput(e) {
  188. // 如果触发 @
  189. if (this.chat.type == "GROUP" && !this.zhLock) {
  190. if (e.data == '@') {
  191. // 打开选择弹窗
  192. this.showAtBox(e);
  193. } else {
  194. let selection = window.getSelection()
  195. let range = selection.getRangeAt(0)
  196. this.focusNode = selection.focusNode;
  197. // 截取@后面的名称作为过滤条件
  198. let stIdx = this.focusNode.textContent.lastIndexOf('@');
  199. this.atSearchText = this.focusNode.textContent.substring(stIdx + 1);
  200. }
  201. }
  202. this.refreshPlaceHolder();
  203. },
  204. onEditorCompositionStart() {
  205. this.zhLock = true;
  206. },
  207. onEditorCompositionEnd(e) {
  208. this.zhLock = false;
  209. this.onEditorInput(e);
  210. },
  211. showAtBox(e) {
  212. this.atSearchText = "";
  213. let selection = window.getSelection()
  214. let range = selection.getRangeAt(0)
  215. // 记录光标所在位置
  216. this.focusNode = selection.focusNode;
  217. this.focusOffset = selection.focusOffset;
  218. // 光标所在坐标
  219. let pos = range.getBoundingClientRect();
  220. this.$refs.atBox.open({
  221. x: pos.x,
  222. y: pos.y
  223. })
  224. },
  225. onAtSelect(member) {
  226. let range = window.getSelection().getRangeAt(0)
  227. // 选中输入的 @xx 符
  228. range.setStart(this.focusNode, this.focusOffset - 1 - this.atSearchText.length)
  229. range.setEnd(this.focusNode, this.focusOffset)
  230. range.deleteContents()
  231. // 创建元素节点
  232. let element = document.createElement('SPAN')
  233. element.className = "at"
  234. element.dataset.id = member.userId;
  235. element.contentEditable = 'false'
  236. element.innerText = `@${member.showNickName}`
  237. range.insertNode(element)
  238. // 光标移动到末尾
  239. range.collapse()
  240. // 插入空格
  241. let textNode = document.createTextNode('\u00A0');
  242. range.insertNode(textNode)
  243. range.collapse()
  244. this.atSearchText = "";
  245. this.$refs.editBox.focus()
  246. },
  247. onSwitchReceipt() {
  248. this.isReceipt = !this.isReceipt;
  249. this.refreshPlaceHolder();
  250. },
  251. createSendText() {
  252. let sendText = this.isReceipt ? "【回执消息】" : "";
  253. this.$refs.editBox.childNodes.forEach((node) => {
  254. if (node.nodeName == "#text") {
  255. sendText += this.html2Escape(node.textContent);
  256. } else if (node.nodeName == "SPAN") {
  257. sendText += node.innerHTML;
  258. } else if (node.nodeName == "IMG") {
  259. sendText += node.dataset.code;
  260. }
  261. })
  262. return sendText;
  263. },
  264. html2Escape(strHtml) {
  265. return strHtml.replace(/[<>&"]/g, function(c) {
  266. return {
  267. '<': '&lt;',
  268. '>': '&gt;',
  269. '&': '&amp;',
  270. '"': '&quot;'
  271. } [c];
  272. });
  273. },
  274. createAtUserIds() {
  275. let ids = [];
  276. this.$refs.editBox.childNodes.forEach((node) => {
  277. if (node.nodeName == "SPAN") {
  278. ids.push(node.dataset.id);
  279. }
  280. })
  281. return ids;
  282. },
  283. onEditorPaste(e) {
  284. let txt = e.clipboardData.getData('Text')
  285. if (typeof(txt) == 'string') {
  286. let range = window.getSelection().getRangeAt(0)
  287. let textNode = document.createTextNode(txt);
  288. range.insertNode(textNode)
  289. range.collapse();
  290. }
  291. let items = (e.clipboardData || window.clipboardData).items
  292. if (items.length) {
  293. for (let i = 0; i < items.length; i++) {
  294. if (items[i].type.indexOf('image') !== -1) {
  295. let file = items[i].getAsFile();
  296. this.sendImageFile = file;
  297. this.sendImageUrl = URL.createObjectURL(file);
  298. }
  299. }
  300. }
  301. },
  302. removeSendImage() {
  303. this.sendImageUrl = "";
  304. this.sendImageFile = null;
  305. },
  306. onImageSuccess(data, file) {
  307. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  308. msgInfo.content = JSON.stringify(data);
  309. msgInfo.receipt = this.isReceipt;
  310. this.$http({
  311. url: this.messageAction,
  312. method: 'post',
  313. data: msgInfo
  314. }).then((m) => {
  315. msgInfo.loadStatus = 'ok';
  316. msgInfo.id = m.id;
  317. this.isReceipt = false;
  318. this.refreshPlaceHolder();
  319. this.$store.commit("insertMessage", msgInfo);
  320. })
  321. },
  322. onImageFail(e, file) {
  323. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  324. msgInfo.loadStatus = 'fail';
  325. this.$store.commit("insertMessage", msgInfo);
  326. },
  327. onImageBefore(file) {
  328. let url = URL.createObjectURL(file);
  329. let data = {
  330. originUrl: url,
  331. thumbUrl: url
  332. }
  333. let msgInfo = {
  334. id: 0,
  335. tmpId: this.generateId(),
  336. fileId: file.uid,
  337. sendId: this.mine.id,
  338. content: JSON.stringify(data),
  339. sendTime: new Date().getTime(),
  340. selfSend: true,
  341. type: 1,
  342. readedCount: 0,
  343. loadStatus: "loading",
  344. status: this.$enums.MESSAGE_STATUS.UNSEND
  345. }
  346. // 填充对方id
  347. this.fillTargetId(msgInfo, this.chat.targetId);
  348. // 插入消息
  349. this.$store.commit("insertMessage", msgInfo);
  350. // 会话置顶
  351. this.moveChatToTop();
  352. // 滚动到底部
  353. this.scrollToBottom();
  354. // 借助file对象保存
  355. file.msgInfo = msgInfo;
  356. },
  357. onFileSuccess(url, file) {
  358. let data = {
  359. name: file.name,
  360. size: file.size,
  361. url: url
  362. }
  363. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  364. msgInfo.content = JSON.stringify(data);
  365. msgInfo.receipt = this.isReceipt
  366. this.$http({
  367. url: this.messageAction,
  368. method: 'post',
  369. data: msgInfo
  370. }).then((m) => {
  371. msgInfo.loadStatus = 'ok';
  372. msgInfo.id = m.id;
  373. this.isReceipt = false;
  374. this.refreshPlaceHolder();
  375. this.$store.commit("insertMessage", msgInfo);
  376. })
  377. },
  378. onFileFail(e, file) {
  379. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  380. msgInfo.loadStatus = 'fail';
  381. this.$store.commit("insertMessage", msgInfo);
  382. },
  383. onFileBefore(file) {
  384. let url = URL.createObjectURL(file);
  385. let data = {
  386. name: file.name,
  387. size: file.size,
  388. url: url
  389. }
  390. let msgInfo = {
  391. id: 0,
  392. tmpId: this.generateId(),
  393. sendId: this.mine.id,
  394. content: JSON.stringify(data),
  395. sendTime: new Date().getTime(),
  396. selfSend: true,
  397. type: 2,
  398. loadStatus: "loading",
  399. readedCount: 0,
  400. status: this.$enums.MESSAGE_STATUS.UNSEND
  401. }
  402. // 填充对方id
  403. this.fillTargetId(msgInfo, this.chat.targetId);
  404. // 插入消息
  405. this.$store.commit("insertMessage", msgInfo);
  406. // 会话置顶
  407. this.moveChatToTop();
  408. // 滚动到底部
  409. this.scrollToBottom();
  410. // 借助file对象透传
  411. file.msgInfo = msgInfo;
  412. },
  413. onCloseSide() {
  414. this.showSide = false;
  415. },
  416. onScrollToTop() {
  417. // 多展示10条信息
  418. this.showMinIdx = this.showMinIdx > 10 ? this.showMinIdx - 10 : 0;
  419. },
  420. onScroll(e) {
  421. let scrollElement = e.target
  422. let scrollTop = scrollElement.scrollTop
  423. if (scrollTop < 30) { // 在顶部,不滚动的情况
  424. // 多展示20条信息
  425. this.showMinIdx = this.showMinIdx > 20 ? this.showMinIdx - 20 : 0;
  426. }
  427. },
  428. showEmotionBox() {
  429. let width = this.$refs.emotion.offsetWidth;
  430. let left = this.$elm.fixLeft(this.$refs.emotion);
  431. let top = this.$elm.fixTop(this.$refs.emotion);
  432. this.$refs.emoBox.open({
  433. x: left + width / 2,
  434. y: top
  435. })
  436. },
  437. onEmotion(emoText) {
  438. // 保持输入框焦点
  439. this.$refs.editBox.focus();
  440. let range = window.getSelection().getRangeAt(0);
  441. // 插入光标所在位置
  442. range.setStart(this.focusNode, this.focusOffset)
  443. let element = document.createElement('IMG')
  444. element.className = "emo"
  445. element.dataset.code = emoText;
  446. element.contentEditable = 'true'
  447. element.setAttribute("src", this.$emo.textToUrl(emoText));
  448. // 选中元素节点
  449. range.insertNode(element)
  450. // 光标移动到末尾
  451. range.collapse()
  452. },
  453. showRecordBox() {
  454. this.showRecord = true;
  455. },
  456. closeRecordBox() {
  457. this.showRecord = false;
  458. },
  459. showPrivateVideo(mode) {
  460. let rtcInfo = {
  461. mode: mode,
  462. isHost: true,
  463. friend: this.friend,
  464. }
  465. // 通过home.vue打开单人视频窗口
  466. this.$eventBus.$emit("openPrivateVideo", rtcInfo);
  467. },
  468. onGroupVideo() {
  469. this.$http({
  470. url: "/webrtc/group/info?groupId=" + this.group.id,
  471. method: 'GET'
  472. }).then((rtcInfo) => {
  473. if (rtcInfo.isChating) {
  474. // 已在通话中,可以直接加入通话
  475. this.$refs.rtcJoin.open(rtcInfo);
  476. } else {
  477. // 邀请成员发起通话
  478. let ids = [this.mine.id];
  479. let maxChannel = this.$store.state.configStore.webrtc.maxChannel;
  480. this.$refs.rtcSel.open(maxChannel, ids, ids);
  481. }
  482. })
  483. },
  484. onInviteOk(members) {
  485. if(members.length < 2){
  486. return;
  487. }
  488. let userInfos = [];
  489. members.forEach(m => {
  490. userInfos.push({
  491. id: m.userId,
  492. nickName: m.showNickName,
  493. headImage: m.headImage,
  494. isCamera: false,
  495. isMicroPhone: true
  496. })
  497. })
  498. let rtcInfo = {
  499. isHost: true,
  500. groupId: this.group.id,
  501. inviterId: this.mine.id,
  502. userInfos: userInfos
  503. }
  504. // 通过home.vue打开多人视频窗口
  505. this.$eventBus.$emit("openGroupVideo", rtcInfo);
  506. },
  507. showHistoryBox() {
  508. this.showHistory = true;
  509. },
  510. closeHistoryBox() {
  511. this.showHistory = false;
  512. },
  513. onSendRecord(data) {
  514. let msgInfo = {
  515. content: JSON.stringify(data),
  516. type: 3,
  517. receipt: this.isReceipt
  518. }
  519. // 填充对方id
  520. this.fillTargetId(msgInfo, this.chat.targetId);
  521. this.$http({
  522. url: this.messageAction,
  523. method: 'post',
  524. data: msgInfo
  525. }).then((m) => {
  526. m.selfSend = true;
  527. this.$store.commit("insertMessage", m);
  528. // 会话置顶
  529. this.moveChatToTop();
  530. // 保持输入框焦点
  531. this.$refs.editBox.focus();
  532. // 滚动到底部
  533. this.scrollToBottom();
  534. // 关闭录音窗口
  535. this.showRecord = false;
  536. this.isReceipt = false;
  537. this.refreshPlaceHolder();
  538. })
  539. },
  540. fillTargetId(msgInfo, targetId) {
  541. if (this.chat.type == "GROUP") {
  542. msgInfo.groupId = targetId;
  543. } else {
  544. msgInfo.recvId = targetId;
  545. }
  546. },
  547. sendMessage() {
  548. if (this.sendImageFile) {
  549. this.sendImageMessage();
  550. } else {
  551. this.sendTextMessage();
  552. }
  553. // 消息已读
  554. this.readedMessage()
  555. },
  556. sendImageMessage() {
  557. let file = this.sendImageFile;
  558. this.onImageBefore(this.sendImageFile);
  559. let formData = new FormData()
  560. formData.append('file', file)
  561. this.$http.post("/image/upload", formData, {
  562. headers: {
  563. 'Content-Type': 'multipart/form-data'
  564. }
  565. }).then((data) => {
  566. this.onImageSuccess(data, file);
  567. }).catch((res) => {
  568. this.onImageSuccess(res, file);
  569. })
  570. this.sendImageFile = null;
  571. this.sendImageUrl = "";
  572. this.$nextTick(() => this.$refs.editBox.focus());
  573. this.scrollToBottom();
  574. },
  575. sendTextMessage() {
  576. let sendText = this.createSendText();
  577. if (!sendText.trim()) {
  578. return
  579. }
  580. this.$refs.editBox.cle
  581. let msgInfo = {
  582. content: sendText,
  583. type: 0
  584. }
  585. // 填充对方id
  586. this.fillTargetId(msgInfo, this.chat.targetId);
  587. // 被@人员列表
  588. if (this.chat.type == "GROUP") {
  589. msgInfo.atUserIds = this.createAtUserIds();
  590. msgInfo.receipt = this.isReceipt;
  591. }
  592. this.lockMessage = true;
  593. this.$http({
  594. url: this.messageAction,
  595. method: 'post',
  596. data: msgInfo
  597. }).then((m) => {
  598. m.selfSend = true;
  599. this.$store.commit("insertMessage", m);
  600. // 会话置顶
  601. this.moveChatToTop();
  602. }).finally(() => {
  603. // 解除锁定
  604. this.lockMessage = false;
  605. this.scrollToBottom();
  606. this.resetEditor();
  607. this.isReceipt = false;
  608. this.refreshPlaceHolder();
  609. });
  610. },
  611. deleteMessage(msgInfo) {
  612. this.$confirm('确认删除消息?', '删除消息', {
  613. confirmButtonText: '确定',
  614. cancelButtonText: '取消',
  615. type: 'warning'
  616. }).then(() => {
  617. this.$store.commit("deleteMessage", msgInfo);
  618. });
  619. },
  620. recallMessage(msgInfo) {
  621. this.$confirm('确认撤回消息?', '撤回消息', {
  622. confirmButtonText: '确定',
  623. cancelButtonText: '取消',
  624. type: 'warning'
  625. }).then(() => {
  626. let url = `/message/${this.chat.type.toLowerCase()}/recall/${msgInfo.id}`
  627. this.$http({
  628. url: url,
  629. method: 'delete'
  630. }).then(() => {
  631. this.$message.success("消息已撤回");
  632. msgInfo = JSON.parse(JSON.stringify(msgInfo));
  633. msgInfo.type = 10;
  634. msgInfo.content = '你撤回了一条消息';
  635. msgInfo.status = this.$enums.MESSAGE_STATUS.RECALL;
  636. this.$store.commit("insertMessage", msgInfo);
  637. })
  638. });
  639. },
  640. readedMessage() {
  641. if (this.chat.unreadCount == 0) {
  642. return;
  643. }
  644. this.$store.commit("resetUnreadCount", this.chat)
  645. if (this.chat.type == "GROUP") {
  646. var url = `/message/group/readed?groupId=${this.chat.targetId}`
  647. } else {
  648. url = `/message/private/readed?friendId=${this.chat.targetId}`
  649. }
  650. this.$http({
  651. url: url,
  652. method: 'put'
  653. }).then(() => {})
  654. },
  655. loadReaded(fId) {
  656. this.$http({
  657. url: `/message/private/maxReadedId?friendId=${fId}`,
  658. method: 'get'
  659. }).then((id) => {
  660. this.$store.commit("readedMessage", {
  661. friendId: fId,
  662. maxId: id
  663. });
  664. });
  665. },
  666. loadGroup(groupId) {
  667. this.$http({
  668. url: `/group/find/${groupId}`,
  669. method: 'get'
  670. }).then((group) => {
  671. this.group = group;
  672. this.$store.commit("updateChatFromGroup", group);
  673. this.$store.commit("updateGroup", group);
  674. });
  675. this.$http({
  676. url: `/group/members/${groupId}`,
  677. method: 'get'
  678. }).then((groupMembers) => {
  679. this.groupMembers = groupMembers;
  680. });
  681. },
  682. loadFriend(friendId) {
  683. // 获取对方最新信息
  684. this.$http({
  685. url: `/user/find/${friendId}`,
  686. method: 'get'
  687. }).then((friend) => {
  688. this.friend = friend;
  689. this.$store.commit("updateChatFromFriend", friend);
  690. this.$store.commit("updateFriend", friend);
  691. })
  692. },
  693. showName(msgInfo) {
  694. if (this.chat.type == 'GROUP') {
  695. let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
  696. return member ? member.showNickName : "";
  697. } else {
  698. return msgInfo.sendId == this.mine.id ? this.mine.nickName : this.chat.showName
  699. }
  700. },
  701. headImage(msgInfo) {
  702. if (this.chat.type == 'GROUP') {
  703. let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
  704. return member ? member.headImage : "";
  705. } else {
  706. return msgInfo.sendId == this.mine.id ? this.mine.headImageThumb : this.chat.headImage
  707. }
  708. },
  709. resetEditor() {
  710. this.sendImageUrl = "";
  711. this.sendImageFile = null;
  712. this.$nextTick(() => {
  713. this.$refs.editBox.innerHTML = "";
  714. this.$refs.editBox.focus();
  715. });
  716. },
  717. scrollToBottom() {
  718. this.$nextTick(() => {
  719. let div = document.getElementById("chatScrollBox");
  720. div.scrollTop = div.scrollHeight;
  721. });
  722. },
  723. refreshPlaceHolder() {
  724. if (this.isReceipt) {
  725. this.placeholder = "【回执消息】"
  726. } else if (this.$refs.editBox && this.$refs.editBox.innerHTML) {
  727. this.placeholder = ""
  728. } else {
  729. this.placeholder = "聊点什么吧~";
  730. }
  731. },
  732. generateId(){
  733. // 生成临时id
  734. return String(new Date().getTime()) + String(Math.floor(Math.random() * 1000));
  735. }
  736. },
  737. computed: {
  738. mine() {
  739. return this.$store.state.userStore.userInfo;
  740. },
  741. title() {
  742. let title = this.chat.showName;
  743. if (this.chat.type == "GROUP") {
  744. let size = this.groupMembers.filter(m => !m.quit).length;
  745. title += `(${size})`;
  746. }
  747. return title;
  748. },
  749. messageAction() {
  750. return `/message/${this.chat.type.toLowerCase()}/send`;
  751. },
  752. unreadCount() {
  753. return this.chat.unreadCount;
  754. },
  755. messageSize() {
  756. if (!this.chat || !this.chat.messages) {
  757. return 0;
  758. }
  759. return this.chat.messages.length;
  760. }
  761. },
  762. watch: {
  763. chat: {
  764. handler(newChat, oldChat) {
  765. if (newChat.targetId > 0 && (!oldChat || newChat.type != oldChat.type ||
  766. newChat.targetId != oldChat.targetId)) {
  767. if (this.chat.type == "GROUP") {
  768. this.loadGroup(this.chat.targetId);
  769. } else {
  770. this.loadFriend(this.chat.targetId);
  771. // 加载已读状态
  772. this.loadReaded(this.chat.targetId)
  773. }
  774. // 滚到底部
  775. this.scrollToBottom();
  776. this.showSide = false;
  777. // 消息已读
  778. this.readedMessage()
  779. // 初始状态只显示30条消息
  780. let size = this.chat.messages.length;
  781. this.showMinIdx = size > 30 ? size - 30 : 0;
  782. // 重置输入框
  783. this.resetEditor();
  784. // 复位回执消息
  785. this.isReceipt = false;
  786. // 更新placeholder
  787. this.refreshPlaceHolder();
  788. }
  789. },
  790. immediate: true
  791. },
  792. messageSize: {
  793. handler(newSize, oldSize) {
  794. if (newSize > oldSize) {
  795. // 拉至底部
  796. this.scrollToBottom();
  797. }
  798. }
  799. }
  800. },
  801. mounted() {
  802. let div = document.getElementById("chatScrollBox");
  803. div.addEventListener('scroll', this.onScroll)
  804. }
  805. }
  806. </script>
  807. <style lang="scss">
  808. .chat-box {
  809. position: relative;
  810. width: 100%;
  811. background: #f8f8f8;
  812. border: #dddddd solid 1px;
  813. .el-header {
  814. padding: 3px;
  815. background-color: white;
  816. line-height: 50px;
  817. font-size: 20px;
  818. font-weight: 600;
  819. border-bottom: 1px #ddd solid;
  820. .btn-side {
  821. position: absolute;
  822. right: 20px;
  823. line-height: 50px;
  824. font-size: 25px;
  825. cursor: pointer;
  826. }
  827. }
  828. .im-chat-main {
  829. padding: 0;
  830. background-color: #f8f8f8;
  831. .im-chat-box {
  832. >ul {
  833. padding: 0 20px;
  834. li {
  835. list-style-type: none;
  836. }
  837. }
  838. }
  839. }
  840. .im-chat-footer {
  841. display: flex;
  842. flex-direction: column;
  843. padding: 0;
  844. .chat-tool-bar {
  845. display: flex;
  846. position: relative;
  847. width: 100%;
  848. height: 40px;
  849. text-align: left;
  850. box-sizing: border-box;
  851. border-top: #ccc solid 1px;
  852. padding: 2px;
  853. background-color: #E8F2FF;
  854. >div {
  855. font-size: 22px;
  856. cursor: pointer;
  857. color: black;
  858. line-height: 34px;
  859. width: 34px;
  860. height: 34px;
  861. text-align: center;
  862. border-radius: 3px;
  863. &:hover {
  864. color: black;
  865. }
  866. &.chat-tool-active {
  867. background: #ddd;
  868. }
  869. }
  870. }
  871. .send-content-area {
  872. position: relative;
  873. display: flex;
  874. flex-direction: column;
  875. height: 100%;
  876. background-color: white !important;
  877. .send-text-area {
  878. box-sizing: border-box;
  879. padding: 5px;
  880. width: 100%;
  881. flex: 1;
  882. resize: none;
  883. font-size: 16px;
  884. color: black;
  885. outline-color: rgba(83, 160, 231, 0.61);
  886. text-align: left;
  887. line-height: 30 px;
  888. &:before {
  889. content: attr(placeholder);
  890. color: gray;
  891. }
  892. .at {
  893. color: blue;
  894. font-weight: 600;
  895. }
  896. .receipt {
  897. color: darkblue;
  898. font-size: 15px;
  899. font-weight: 600;
  900. }
  901. .emo {
  902. width: 30px;
  903. height: 30px;
  904. vertical-align: bottom;
  905. }
  906. }
  907. .send-image-area {
  908. text-align: left;
  909. border: #53a0e7 solid 1px;
  910. .send-image-box {
  911. position: relative;
  912. display: inline-block;
  913. .send-image {
  914. max-height: 180px;
  915. border: 1px solid #ccc;
  916. border-radius: 2%;
  917. margin: 2px;
  918. }
  919. .send-image-close {
  920. position: absolute;
  921. padding: 3px;
  922. right: 7px;
  923. top: 7px;
  924. color: white;
  925. cursor: pointer;
  926. font-size: 15px;
  927. font-weight: 600;
  928. background-color: #aaa;
  929. border-radius: 50%;
  930. border: 1px solid #ccc;
  931. }
  932. }
  933. }
  934. .send-btn-area {
  935. padding: 10px;
  936. position: absolute;
  937. bottom: 0;
  938. right: 0;
  939. }
  940. }
  941. }
  942. .chat-group-side-box {
  943. border: #dddddd solid 1px;
  944. animation: rtl-drawer-in .3s 1ms;
  945. }
  946. }
  947. </style>