privateChat.vue 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. <template>
  2. <view class="chatInterface" @contextmenu.prevent="">
  3. <view class="scroll-view">
  4. <image v-if="history.loading" class="history-loaded" src="/static/images/loading.svg"/>
  5. <view v-else :class="history.allLoaded ? 'history-loaded':'load'" @click="loadHistoryMessage(false)">
  6. <view>{{ history.allLoaded ? '已经没有更多的历史消息' : '点击获取历史消息' }}</view>
  7. </view>
  8. <checkbox-group @change="selectMessages">
  9. <!--消息记录-->
  10. <view v-for="(message,index) in history.messages" :key="message.messageId">
  11. <!--时间显示,类似于微信,隔5分钟不发言,才显示时间-->
  12. <view class="time-lag">
  13. {{ renderMessageDate(message, index) }}
  14. </view>
  15. <view class="message-recalled" v-if="message.recalled">
  16. <view v-if="message.recaller.id === currentUser.id" class="message-recalled-self">
  17. <view>你撤回了一条消息</view>
  18. <span v-if="message.type === 'text' && Date.now()-message.timestamp< 60 * 1000 "
  19. @click="editRecalledMessage(message.payload.text)">重新编辑</span>
  20. </view>
  21. <view v-else>{{ message.recaller.data.name }}撤回了一条消息</view>
  22. </view>
  23. <view class="message-item" v-else>
  24. <view class="message-item-checkbox">
  25. <checkbox v-show="messageSelector.visible && message.status !== 'sending'" :value="message.messageId"
  26. :checked="messageSelector.messages.includes(message)"/>
  27. </view>
  28. <view class="message-item-content" :class="{'self' : message.senderId === currentUser.id}">
  29. <view class="avatar">
  30. <!-- <image :src="message.senderId === currentUser.id? currentUser.avatar : friend.avatar"></image> -->
  31. <image src="/static/img/touxiang.png"></image>
  32. </view>
  33. <view class="content" @click.right="showActionPopup(message)" @longpress="showActionPopup(message)">
  34. <view class="message-payload">
  35. <b class="pending" v-if="message.status === 'sending'"></b>
  36. <b class="send-fail" v-if="message.status === 'fail'"></b>
  37. <view v-if="message.type === 'text'" class="text-content" v-html="renderTextMessage(message)"></view>
  38. <image v-if="message.type === 'image'"
  39. :data-url="message.payload.url"
  40. :src="message.payload.thumbnail"
  41. class="image-content"
  42. mode="heightFix"
  43. @click="showImageFullScreen"
  44. ></image>
  45. <view class="video-snapshot" v-if="message.type === 'video'" :data-url="message.payload.video.url"
  46. @click="playVideo">
  47. <image
  48. :src="message.payload.thumbnail.url"
  49. :style="{height: getImageHeight(message.payload.thumbnail.width,message.payload.thumbnail.height)+'rpx' }"
  50. mode="heightFix"
  51. ></image>
  52. <view class="video-play-icon"></view>
  53. </view>
  54. <view class="file-content" v-if="message.type === 'file'">
  55. <view class="file-info">
  56. <span class="file-name">{{ message.payload.name }}</span>
  57. <span class="file-size">{{ (message.payload.size / 1024).toFixed(2) }}KB</span>
  58. </view>
  59. <image class="file-img" src="/static/images/file-icon.png"></image>
  60. </view>
  61. <view v-if="message.type ==='audio'" class="audio-content" @click="playAudio(message)">
  62. <view class="audio-facade" :style="{width:Math.ceil(message.payload.duration)*7 + 50 + 'px'}">
  63. <view
  64. class="audio-facade-bg"
  65. :class="{'play-icon':audioPlayer.playingMessage && audioPlayer.playingMessage.messageId === message.messageId}"
  66. ></view>
  67. <view>{{Math.ceil(message.payload.duration) || 1}}<span>"</span></view>
  68. </view>
  69. </view>
  70. <view v-if="message.type === 'order'" class="order-content">
  71. <view class="order-id">订单号:{{ message.payload.id }}</view>
  72. <view class="order-body">
  73. <image :src="message.payload.url" class="order-img"></image>
  74. <view>
  75. <view class="order-name">{{ message.payload.name }}</view>
  76. <view class="order-info">
  77. <view class="order-price">{{ message.payload.price }}</view>
  78. <view class="order-count">共{{ message.payload.count }}件</view>
  79. </view>
  80. </view>
  81. </view>
  82. </view>
  83. </view>
  84. <view v-if="message.senderId === currentUser.id" :class="message.read ?'message-read':'message-unread'">
  85. <view v-if="message.status === 'success'">{{ message.read ? '已读' : '未读' }}</view>
  86. </view>
  87. </view>
  88. </view>
  89. </view>
  90. </view>
  91. </checkbox-group>
  92. </view>
  93. <view class="action-box" v-if="!videoPlayer.visible && !messageSelector.visible">
  94. <view class="action-top">
  95. <view @click="switchAudioKeyboard">
  96. <image class="more" v-if="audio.visible" src="/static/images/jianpan.png"></image>
  97. <image class="more" v-else src="/static/images/audio.png"></image>
  98. </view>
  99. <view v-if="audio.visible" class="record-input" @touchend.stop="onRecordEnd" @touchstart.stop="onRecordStart">
  100. {{ recorderManager.recording ? '松开发送' : '按住录音' }}
  101. </view>
  102. <!-- GoEasyIM最大支持3k的文本消息,如需发送长文本,需调整输入框maxlength值 -->
  103. <input v-else v-model="text" @confirm="sendTextMessage" class="consult-input" maxlength="700" placeholder="发送消息" type="text" />
  104. <view @click="switchEmojiKeyboard">
  105. <image class="more" v-if="emoji.visible" src="/static/images/jianpan.png"></image>
  106. <image class="more" v-else src="/static/images/emoji.png"></image>
  107. </view>
  108. <view>
  109. <image @click="showOtherTypesMessagePanel()" class="more" src="/static/images/more.png"/>
  110. </view>
  111. <view v-if="text" class="send-btn-box">
  112. <text class="btn" @click="sendTextMessage()">发送</text>
  113. </view>
  114. </view>
  115. <!--展示表情列表-->
  116. <view class="action-bottom action-bottom-emoji" v-if="emoji.visible">
  117. <image class="emoji-item" v-for="(emojiItem, emojiKey, index) in emoji.map" :key="index"
  118. :src="emoji.url + emojiItem" @click="chooseEmoji(emojiKey)"></image>
  119. </view>
  120. <!--其他类型消息面板-->
  121. <view v-if="otherTypesMessagePanelVisible" class="action-bottom">
  122. <view class="more-icon">
  123. <image @click="sendImageMessage()" class="operation-icon" src="/static/images/picture.png"></image>
  124. <view class="operation-title">图片</view>
  125. </view>
  126. <view class="more-icon">
  127. <image @click="sendVideoMessage()" class="operation-icon" src="/static/images/video.png"></image>
  128. <view class="operation-title">视频</view>
  129. </view>
  130. <!-- <view class="more-icon">
  131. <image @click="showOrderMessageList()" class="operation-icon" src="/static/images/order.png"></image>
  132. <view class="operation-title">订单</view>
  133. </view>
  134. <view class="more-icon">
  135. <image @click="privateCall()" class="operation-icon" src="/static/images/rtc.png"></image>
  136. <view class="operation-title">视频通话</view>
  137. </view> -->
  138. </view>
  139. </view>
  140. <view class="action-popup" @touchmove.stop.prevent v-if="actionPopup.visible">
  141. <view class="layer"></view>
  142. <view class="action-list">
  143. <view class="action-item" @click="deleteSingleMessage">删除</view>
  144. <view class="action-item" v-if="actionPopup.recallable" @click="recallMessage">撤回</view>
  145. <view class="action-item" @click="showCheckBox">多选</view>
  146. <view class="action-item" @click="hideActionPopup">取消</view>
  147. </view>
  148. </view>
  149. <view class="messageSelector-box" v-if="messageSelector.visible">
  150. <image class="messageSelector-btn" @click="deleteMultipleMessages" src="/static/images/delete.png"></image>
  151. </view>
  152. <view class="record-loading" v-if="recorderManager.recording"></view>
  153. <video v-if="videoPlayer.visible" :src="videoPlayer.url" id="videoPlayer"
  154. @fullscreenchange="onVideoFullScreenChange"></video>
  155. <view v-if="orderList.visible" class="order-list">
  156. <view class="orders-content">
  157. <view class="title">
  158. <view>请选择一个订单</view>
  159. <view class="close" @click="hideOrderMessageList">×</view>
  160. </view>
  161. <view class="orders">
  162. <view
  163. v-for="(order, index) in orderList.orders"
  164. :key="index" class="order-item"
  165. @click="sendOrderMessage(order)"
  166. >
  167. <view class="order-id">订单号:{{ order.id }}</view>
  168. <view class="order-body">
  169. <image :src="order.url" class="order-img"></image>
  170. <view class="order-name">{{ order.name }}</view>
  171. <view class="order-right">
  172. <view class="order-price">{{ order.price }}</view>
  173. <view class="order-count">共{{ order.count }}件</view>
  174. </view>
  175. </view>
  176. </view>
  177. </view>
  178. </view>
  179. </view>
  180. </view>
  181. </template>
  182. <script>
  183. import EmojiDecoder from '../lib/EmojiDecoder';
  184. import restApi from '../lib/restapi';
  185. import {formatDate} from '../lib/utils';
  186. import RecorderManager from '../lib/RecorderManager';
  187. const IMAGE_MAX_WIDTH = 200;
  188. const IMAGE_MAX_HEIGHT = 150;
  189. const recorderManager = new RecorderManager();
  190. const GoEasy = uni.$GoEasy;
  191. const GRTC = uni.$GRTC;
  192. export default {
  193. name: 'privateChat',
  194. data() {
  195. const emojiUrl = 'https://imgcache.qq.com/open/qcloud/tim/assets/emoji/';
  196. const emojiMap = {
  197. '[么么哒]': 'emoji_3@2x.png',
  198. '[乒乓]': 'emoji_4@2x.png',
  199. '[便便]': 'emoji_5@2x.png',
  200. '[信封]': 'emoji_6@2x.png',
  201. '[偷笑]': 'emoji_7@2x.png',
  202. '[傲慢]': 'emoji_8@2x.png'
  203. };
  204. return {
  205. //聊天文本框
  206. text: '',
  207. friend: null,
  208. to: {},// 作为createMessage的参数
  209. currentUser: null,
  210. //定义表情列表
  211. emoji: {
  212. url: emojiUrl,
  213. map: emojiMap,
  214. visible: false,
  215. decoder: new EmojiDecoder(emojiUrl, emojiMap),
  216. },
  217. //是否展示‘其他消息类型面板’
  218. otherTypesMessagePanelVisible: false,
  219. orderList: {
  220. orders: [],
  221. visible: false
  222. },
  223. history: {
  224. messages: [],
  225. allLoaded: false,
  226. loading: false
  227. },
  228. recorderManager: recorderManager,
  229. audio: {
  230. //录音按钮展示
  231. visible: false
  232. },
  233. audioPlayer: {
  234. innerAudioContext: null,
  235. playingMessage: null,
  236. },
  237. videoPlayer: {
  238. visible: false,
  239. url: '',
  240. context: null
  241. },
  242. // 展示消息删除弹出框
  243. actionPopup: {
  244. visible: false,
  245. message: null,
  246. recallable: false,
  247. },
  248. // 消息选择
  249. messageSelector: {
  250. visible: false,
  251. messages: []
  252. }
  253. }
  254. },
  255. onLoad(options) {
  256. //聊天对象
  257. let id = options.to;
  258. this.friend = uni.getStorageSync("friend");
  259. //this.friend = restApi.findUserById(id);
  260. //this.currentUser = uni.$currentUser;
  261. this.currentUser = uni.getStorageSync("currentUser");
  262. this.to = {
  263. id: this.friend.id,
  264. type: GoEasy.IM_SCENE.PRIVATE,
  265. data: {
  266. name: this.friend.supplierName,
  267. avatar: '/static/images/Avatar-1.png'
  268. }
  269. };
  270. this.initGoEasyListeners();
  271. // 语音播放器
  272. this.initialAudioPlayer();
  273. // 录音监听器
  274. this.initRecorderListeners();
  275. },
  276. onShow() {
  277. this.otherTypesMessagePanelVisible = false;
  278. this.emoji.visible = false;
  279. },
  280. onReady() {
  281. this.loadHistoryMessage(true);
  282. this.videoPlayer.context = uni.createVideoContext('videoPlayer', this);
  283. // https://uniapp.dcloud.io/api/ui/navigationbar?id=setnavigationbartitle
  284. uni.setNavigationBarTitle({ title: this.friend.supplierName });
  285. },
  286. onPullDownRefresh(e) {
  287. this.loadHistoryMessage(false);
  288. },
  289. onUnload() {
  290. //退出聊天页面之前,清空监听器
  291. GoEasy.im.off(GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, this.onMessageReceived);
  292. GoEasy.im.off(GoEasy.IM_EVENT.MESSAGE_DELETED, this.onMessageDeleted);
  293. GoEasy.im.off(GoEasy.IM_EVENT.HISTORY_EXPIRED, this.onHistoryExpired);
  294. },
  295. methods: {
  296. //渲染文本消息,如果包含表情,替换为图片
  297. //todo:本不需要该方法,可以在标签里完成,但小程序有兼容性问题,被迫这样实现
  298. renderTextMessage(message) {
  299. return '<span>' + this.emoji.decoder.decode(message.payload.text) + '</span>'
  300. },
  301. //像微信那样显示时间,如果有几分钟没发消息了,才显示时间
  302. //todo:本不需要该方法,可以在标签里完成,但小程序有兼容性问题,被迫这样实现
  303. renderMessageDate(message, index) {
  304. if (index === 0) {
  305. return formatDate(message.timestamp)
  306. } else {
  307. if (message.timestamp - this.history.messages[index - 1].timestamp > 5 * 60 * 1000) {
  308. return formatDate(message.timestamp)
  309. }
  310. }
  311. return '';
  312. },
  313. initGoEasyListeners() {
  314. // 监听私聊消息
  315. GoEasy.im.on(GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, this.onMessageReceived);
  316. //监听消息删除
  317. GoEasy.im.on(GoEasy.IM_EVENT.MESSAGE_DELETED, this.onMessageDeleted);
  318. // 监听断网重连
  319. GoEasy.im.on(GoEasy.IM_EVENT.HISTORY_EXPIRED, this.onHistoryExpired);
  320. },
  321. onMessageReceived (message) {
  322. let senderId = message.senderId;
  323. let receiverId = message.receiverId;
  324. let friendId = this.currentUser.id === senderId ? receiverId : senderId;
  325. if (friendId === this.friend.id) {
  326. this.history.messages.push(message);
  327. //聊天时,收到消息标记为已读
  328. this.markPrivateMessageAsRead();
  329. //收到新消息,是滚动到最底部
  330. this.scrollToBottom();
  331. }
  332. },
  333. onMessageDeleted (deletedMessages) {
  334. deletedMessages.forEach(message => {
  335. let senderId = message.senderId;
  336. let receiverId = message.receiverId;
  337. let friendId = this.currentUser.id === senderId ? receiverId : senderId;
  338. if (friendId === this.friend.id) {
  339. let index = this.history.messages.indexOf(message);
  340. if (index > -1) {
  341. this.history.messages.splice(index, 1);
  342. }
  343. }
  344. });
  345. },
  346. onHistoryExpired() {
  347. this.history.messages = [];
  348. this.loadHistoryMessage(true);
  349. },
  350. initialAudioPlayer () {
  351. this.audioPlayer.innerAudioContext = uni.createInnerAudioContext();
  352. this.audioPlayer.innerAudioContext.onEnded(() => {
  353. this.audioPlayer.playingMessage = null;
  354. });
  355. this.audioPlayer.innerAudioContext.onStop(() => {
  356. this.audioPlayer.playingMessage = null;
  357. });
  358. },
  359. initRecorderListeners() {
  360. recorderManager.onRecordComplete((file, duration) => {
  361. if (duration < 1000) {
  362. uni.showToast({
  363. icon: 'none',
  364. title: '录音时间太短',
  365. duration: 500
  366. });
  367. return;
  368. }
  369. GoEasy.im.createAudioMessage({
  370. to: this.to,
  371. file: file,
  372. notification: {
  373. title: this.currentUser.name + '发来一段语音',
  374. body: '[语音消息]', // 字段最长 50 字符
  375. sound: 'message',
  376. badge: '+1'
  377. },
  378. onProgress: function (progress) {
  379. console.log(progress)
  380. },
  381. onSuccess: (message) => {
  382. this.sendMessage(message);
  383. },
  384. onFailed: (e) => {
  385. console.log('error :', e);
  386. }
  387. });
  388. });
  389. },
  390. /**
  391. * 核心就是设置高度,产生明确占位
  392. *
  393. * 小 (宽度和高度都小于预设尺寸)
  394. * 设高=原始高度
  395. * 宽 (宽度>高度)
  396. * 高度= 根据宽度等比缩放
  397. * 窄 (宽度<高度)或方(宽度=高度)
  398. * 设高=MAX height
  399. *
  400. * @param width,height
  401. * @returns number
  402. */
  403. getImageHeight(width, height) {
  404. if (width < IMAGE_MAX_WIDTH && height < IMAGE_MAX_HEIGHT) {
  405. return height * 2;
  406. } else if (width > height) {
  407. return (IMAGE_MAX_WIDTH / width * height) * 2;
  408. } else if (width === height || width < height) {
  409. return IMAGE_MAX_HEIGHT * 2;
  410. }
  411. },
  412. sendMessage(message) {
  413. this.history.messages.push(message);
  414. this.scrollToBottom();
  415. GoEasy.im.sendMessage({
  416. message: message,
  417. onSuccess: function () {
  418. console.log('发送成功.', message);
  419. },
  420. onFailed: function (error) {
  421. if (error.code === 507) {
  422. console.log('发送语音/图片/视频/文件失败,没有配置OSS存储,详情参考:https://docs.goeasy.io/2.x/im/message/media/alioss');
  423. } else {
  424. console.log('发送失败:', error);
  425. }
  426. }
  427. });
  428. },
  429. sendTextMessage() {
  430. if (this.text.trim() !== '') {
  431. let body = this.text;
  432. if (this.text.length >= 50) {
  433. body = this.text.substring(0, 30) + '...';
  434. }
  435. GoEasy.im.createTextMessage({
  436. text: this.text,
  437. to: this.to,
  438. notification: {
  439. title: this.currentUser.name + '发来一段文字',
  440. body: body,
  441. sound: 'message',
  442. badge: '+1'
  443. },
  444. onSuccess: (message) => {
  445. this.sendMessage(message);
  446. },
  447. onFailed: (e) => {
  448. console.log('error :', e);
  449. }
  450. });
  451. }
  452. this.text = '';
  453. },
  454. sendVideoMessage() {
  455. uni.chooseVideo({
  456. success: (res) => {
  457. GoEasy.im.createVideoMessage({
  458. to: this.to,
  459. file: res,
  460. notification: {
  461. title: this.currentUser.name + '发来一个视频',
  462. body: '[视频消息]', // 字段最长 50 字符
  463. sound: 'message',
  464. badge: '+1'
  465. },
  466. onProgress: function (progress) {
  467. console.log(progress)
  468. },
  469. onSuccess: (message) => {
  470. this.otherTypesMessagePanelVisible = false;
  471. this.sendMessage(message);
  472. },
  473. onFailed: (e) => {
  474. console.log('error :', e);
  475. }
  476. });
  477. }
  478. })
  479. },
  480. sendImageMessage() {
  481. uni.chooseImage({
  482. count: 9,
  483. success: (res) => {
  484. res.tempFiles.forEach(file => {
  485. GoEasy.im.createImageMessage({
  486. to: this.to,
  487. file: file,
  488. notification: {
  489. title: this.currentUser.name + '发来一张图片',
  490. body: '[图片消息]', // 字段最长 50 字符
  491. sound: 'message',
  492. badge: '+1'
  493. },
  494. onProgress: function (progress) {
  495. console.log(progress)
  496. },
  497. onSuccess: (message) => {
  498. this.otherTypesMessagePanelVisible = false;
  499. this.sendMessage(message);
  500. },
  501. onFailed: (e) => {
  502. console.log('error :', e);
  503. }
  504. });
  505. })
  506. }
  507. });
  508. },
  509. sendOrderMessage(order) {
  510. //GoEasyIM自定义消息,实现订单发送
  511. GoEasy.im.createCustomMessage({
  512. type: 'order',
  513. payload: order,
  514. to: this.to,
  515. notification: {
  516. title: this.currentUser.name + '发来一个订单',
  517. body: '[订单消息]',
  518. sound: 'message',
  519. badge: '+1'
  520. },
  521. onSuccess: (message) => {
  522. this.otherTypesMessagePanelVisible = false;
  523. this.sendMessage(message);
  524. },
  525. onFailed: (e) => {
  526. console.log('error :', e);
  527. }
  528. });
  529. this.orderList.visible = false;
  530. },
  531. showActionPopup(message) {
  532. const MAX_RECALLABLE_TIME = 3 * 60 * 1000; //3分钟以内的消息才可以撤回
  533. this.messageSelector.messages = [message];
  534. if ((Date.now() - message.timestamp) < MAX_RECALLABLE_TIME && message.senderId === this.currentUser.id && message.status === 'success') {
  535. this.actionPopup.recallable = true;
  536. } else {
  537. this.actionPopup.recallable = false;
  538. }
  539. this.actionPopup.visible = true;
  540. },
  541. hideActionPopup () {
  542. this.actionPopup.visible = false;
  543. this.actionPopup.message = null;
  544. },
  545. deleteSingleMessage() {
  546. uni.showModal({
  547. content: '确认删除?',
  548. success: (res) => {
  549. this.actionPopup.visible = false;
  550. if (res.confirm) {
  551. this.deleteMessage();
  552. }
  553. },
  554. })
  555. },
  556. deleteMultipleMessages() {
  557. if (this.messageSelector.messages.length > 0) {
  558. uni.showModal({
  559. content: '确认删除?',
  560. success: (res) => {
  561. this.messageSelector.visible = false;
  562. if (res.confirm) {
  563. this.deleteMessage();
  564. }
  565. },
  566. })
  567. }
  568. },
  569. deleteMessage() {
  570. GoEasy.im.deleteMessage({
  571. messages: this.messageSelector.messages,
  572. onSuccess: (result) => {
  573. this.messageSelector.messages.forEach(message => {
  574. let index = this.history.messages.indexOf(message);
  575. if (index > -1) {
  576. this.history.messages.splice(index, 1);
  577. }
  578. });
  579. this.messageSelector.messages = [];
  580. },
  581. onFailed: (error) => {
  582. console.log('error:', error);
  583. }
  584. });
  585. },
  586. recallMessage() {
  587. this.actionPopup.visible = false;
  588. GoEasy.im.recallMessage({
  589. messages: this.messageSelector.messages,
  590. onSuccess: () => {
  591. console.log('撤回成功');
  592. },
  593. onFailed: (error) => {
  594. console.log('撤回失败,error:', error);
  595. }
  596. });
  597. },
  598. editRecalledMessage(text) {
  599. if (this.audio.visible) {
  600. this.audio.visible = false;
  601. }
  602. this.text = text;
  603. },
  604. showCheckBox() {
  605. this.messageSelector.messages = [];
  606. this.messageSelector.visible = true;
  607. this.actionPopup.visible = false;
  608. },
  609. selectMessages(e) {
  610. const selectedMessageIds = e.detail.value;
  611. let selectedMessages = [];
  612. this.history.messages.forEach(message => {
  613. if (selectedMessageIds.includes(message.messageId)) {
  614. selectedMessages.push(message);
  615. }
  616. })
  617. this.messageSelector.messages = selectedMessages;
  618. },
  619. loadHistoryMessage(scrollToBottom) {//历史消息
  620. this.history.loading = true;
  621. let lastMessageTimeStamp = null;
  622. let lastMessage = this.history.messages[0];
  623. if (lastMessage) {
  624. lastMessageTimeStamp = lastMessage.timestamp;
  625. }
  626. GoEasy.im.history({
  627. id: this.friend.id,
  628. type: GoEasy.IM_SCENE.PRIVATE,
  629. lastTimestamp: lastMessageTimeStamp,
  630. limit: 10,
  631. onSuccess: (result) => {
  632. uni.stopPullDownRefresh();
  633. this.history.loading = false;
  634. let messages = result.content;
  635. if (messages.length === 0) {
  636. this.history.allLoaded = true;
  637. } else {
  638. if (lastMessageTimeStamp) {
  639. this.history.messages = messages.concat(this.history.messages);
  640. } else {
  641. this.history.messages = messages;
  642. }
  643. if (messages.length < 10) {
  644. this.history.allLoaded = true;
  645. }
  646. if (scrollToBottom) {
  647. this.scrollToBottom();
  648. //收到的消息设置为已读
  649. this.markPrivateMessageAsRead();
  650. }
  651. }
  652. },
  653. onFailed: (error) => {
  654. //获取失败
  655. console.log('获取历史消息失败:', error);
  656. uni.stopPullDownRefresh();
  657. this.history.loading = false;
  658. }
  659. });
  660. },
  661. //语音录制按钮和键盘输入的切换
  662. switchAudioKeyboard() {
  663. if (!this.audio.visible) {
  664. recorderManager.authorize().then(() => {
  665. console.log('录音权限获取成功');
  666. this.audio.visible = true;
  667. }).catch((err) => {
  668. console.log('err:', err)
  669. uni.showModal({
  670. title: '获取录音权限失败',
  671. content: '请先打开麦克风权限'
  672. });
  673. });
  674. } else {
  675. this.audio.visible = false;
  676. }
  677. },
  678. onRecordStart() {
  679. recorderManager.start();
  680. },
  681. onRecordEnd() {
  682. recorderManager.stop();
  683. },
  684. showImageFullScreen(e) {
  685. let imagesUrl = [e.currentTarget.dataset.url];
  686. uni.previewImage({
  687. urls: imagesUrl
  688. });
  689. },
  690. playVideo(e) {
  691. this.videoPlayer.visible = true;
  692. this.videoPlayer.url = e.currentTarget.dataset.url;
  693. this.$nextTick(() => {
  694. this.videoPlayer.context.requestFullScreen({
  695. direction: 0
  696. });
  697. this.videoPlayer.context.play();
  698. });
  699. },
  700. playAudio (audioMessage) {
  701. let playingMessage = this.audioPlayer.playingMessage;
  702. if (playingMessage) {
  703. this.audioPlayer.innerAudioContext.stop();
  704. // 如果点击的消息正在播放,就认为是停止播放操作
  705. if (playingMessage === audioMessage) {
  706. return;
  707. }
  708. }
  709. this.audioPlayer.playingMessage = audioMessage;
  710. this.audioPlayer.innerAudioContext.src = audioMessage.payload.url;
  711. this.audioPlayer.innerAudioContext.play();
  712. },
  713. onVideoFullScreenChange(e) {
  714. //当退出全屏播放时,隐藏播放器
  715. if (this.videoPlayer.visible && !e.detail.fullScreen) {
  716. this.videoPlayer.visible = false;
  717. this.videoPlayer.context.stop();
  718. }
  719. },
  720. messageInputFocusin() {
  721. this.otherTypesMessagePanelVisible = false;
  722. this.emoji.visible = false;
  723. },
  724. switchEmojiKeyboard() {
  725. this.emoji.visible = !this.emoji.visible;
  726. this.otherTypesMessagePanelVisible = false;
  727. },
  728. showOtherTypesMessagePanel() {
  729. this.otherTypesMessagePanelVisible = !this.otherTypesMessagePanelVisible;
  730. this.emoji.visible = false;
  731. },
  732. chooseEmoji(emojiKey) {
  733. this.text += emojiKey;
  734. },
  735. showOrderMessageList() {
  736. this.orderList.orders = restApi.getOrderList();
  737. this.orderList.visible = true;
  738. },
  739. hideOrderMessageList() {
  740. this.orderList.visible = false;
  741. },
  742. privateCall() {
  743. uni.showActionSheet({
  744. itemList: ['视频通话', '音频通话'],
  745. success: (res) => {
  746. const mediaType = res.tapIndex === 0 ? 1 : 0;
  747. const notificationBody = res.tapIndex === 0 ? '邀请你视频通话' : '邀请你语音通话';
  748. GRTC.call({
  749. calleeId: this.friend.id,
  750. mediaType: mediaType,
  751. notification: {
  752. title: this.currentUser.name,
  753. body: notificationBody,
  754. sound: 'ring',
  755. badge: '+1'
  756. },
  757. }).then(() => {
  758. uni.navigateTo({
  759. url: `./rtc/private/dial`,
  760. })
  761. }).catch((error)=>{
  762. console.log("呼叫失败:", error);
  763. uni.showToast({
  764. icon: "error",
  765. title: "呼叫失败:" + error,
  766. duration: 2000
  767. })
  768. })
  769. },
  770. fail: (res) => {
  771. console.log(res.errMsg);
  772. }
  773. });
  774. },
  775. scrollToBottom() {
  776. this.$nextTick(() => {
  777. uni.pageScrollTo({
  778. scrollTop: 2000000,
  779. duration: 0
  780. });
  781. });
  782. },
  783. markPrivateMessageAsRead() {
  784. GoEasy.im.markMessageAsRead({
  785. id: this.to.id,
  786. type: this.to.type,
  787. onSuccess: function () {
  788. console.log('标记私聊已读成功');
  789. },
  790. onFailed: function (error) {
  791. console.log("标记私聊已读失败", error);
  792. }
  793. });
  794. }
  795. }
  796. }
  797. </script>
  798. <style>
  799. @import url('../static/style/chatInterface.css');
  800. </style>