privateChatWeb.vue 35 KB

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