ChatBox.vue 24 KB

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