chat.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. <template>
  2. <view class="content">
  3. <view class="content-box" @touchstart="touchstart" id="content-box" :class="{'content-showfn':showFunBtn}">
  4. <!-- 背景图- 定位方式 -->
  5. <image class="content-box-bg" :src="_user_info.chatBgImg" :style="{ height: imgHeight }"></image>
  6. <view class="content-box-loading" v-if="loading"><u-loading mode="flower"></u-loading></view>
  7. <view class="history-font" @tap="linkToHistory()">历史记录</view>
  8. <view class="message" v-for="(item, index) in messageList" :key="index" :id="`msg-${item.hasBeenSentId}`" :class="index === 0 ? 'marginTop50' : ' '">
  9. <view class="message-item " :class="item.isItMe ? 'right' : 'left'">
  10. <image class="img" :src="item.fromUserHeadImg" mode=""></image>
  11. <!-- contentType = 1 文本 -->
  12. <view class="content" v-if="item.contentType == 1">{{ item.content }}
  13. <button class="pay-btn-class" @tap="goPayPage">前往缴费</button>
  14. </view>
  15. <!-- contentType = 2 语音 -->
  16. <view
  17. class="content contentType2"
  18. :class="[{ 'content-type-right': item.isItMe }]"
  19. v-if="item.contentType == 2"
  20. @tap="handleAudio(item)"
  21. hover-class="contentType2-hover-class"
  22. :style="{width:`${130+(item.contentDuration*2)}rpx`}"
  23. >
  24. <view
  25. class="voice_icon"
  26. :class="[
  27. { voice_icon_right: item.isItMe },
  28. { voice_icon_left: !item.isItMe },
  29. { voice_icon_right_an: item.anmitionPlay && item.isItMe },
  30. { voice_icon_left_an: item.anmitionPlay && !item.isItMe }
  31. ]"
  32. ></view>
  33. <view class="">{{ item.contentDuration }}''</view>
  34. </view>
  35. </view>
  36. </view>
  37. </view>
  38. <!-- 底部聊天输入框 -->
  39. <view class="input-box" :class="{ 'input-box-mpInputMargin': mpInputMargin }">
  40. <view class="input-box-flex">
  41. <!-- #ifndef H5 -->
  42. <!-- <image v-if="chatType === 'voice'" class="icon_img" :src="require('@/static/voice.png')" @click="switchChatType('keyboard')"></image>
  43. <image v-if="chatType === 'keyboard'" class="icon_img" :src="require('@/static/keyboard.png')" @click="switchChatType('voice')"></image> -->
  44. <!-- #endif -->
  45. <view class="input-box-flex-grow">
  46. <!-- <input
  47. v-if="chatType === 'voice'"
  48. type="text"
  49. class="content"
  50. id="input"
  51. v-model="formData.content"
  52. :hold-keyboard="true"
  53. :confirm-type="'send'"
  54. :confirm-hold="true"
  55. placeholder-style="color:#DDDDDD;"
  56. :cursor-spacing="10"
  57. @confirm="sendMsg(null)"
  58. /> -->
  59. <view
  60. class="voice_title"
  61. @touchstart.stop.prevent="startVoice"
  62. @touchmove.stop.prevent="moveVoice"
  63. @touchend.stop="endVoice"
  64. @touchcancel.stop="cancelVoice"
  65. >
  66. {{ voiceTitle }}
  67. </view>
  68. </view>
  69. <!-- 功能性按钮 -->
  70. <!-- <image class=" icon_btn_add" :src="require('@/static/add.png')" @tap="switchFun"></image> -->
  71. <!-- #ifdef H5 -->
  72. <!-- <button class="btn" type="primary" size="mini" @touchend.prevent="sendMsg(null)">发送</button> -->
  73. <!-- #endif -->
  74. </view>
  75. <view class="fun-box" :class="{'show-fun-box':showFunBtn}">
  76. <u-grid :col="4" hover-class="contentType2-hover-class" :border="false" @click="clickGrid">
  77. <u-grid-item v-for="(item, index) in funList" :index="index" :key="index" bg-color="#eaeaea">
  78. <u-icon :name="item.icon" :size="52"></u-icon>
  79. <view class="grid-text">{{ item.title }}</view>
  80. </u-grid-item>
  81. </u-grid>
  82. </view>
  83. </view>
  84. <!-- //语音动画 -->
  85. <view class="voice_an" v-if="recording">
  86. <view class="voice_an_icon">
  87. <view id="one" class="wave"></view>
  88. <view id="two" class="wave"></view>
  89. <view id="three" class="wave"></view>
  90. <view id="four" class="wave"></view>
  91. <view id="five" class="wave"></view>
  92. <view id="six" class="wave"></view>
  93. <view id="seven" class="wave"></view>
  94. </view>
  95. <view class="text">{{voiceIconText}}</view>
  96. </view>
  97. </view>
  98. </template>
  99. <script>
  100. export default {
  101. data() {
  102. return {
  103. fromUserInfo: {},
  104. formData: {
  105. content: '',
  106. limit: 15,
  107. index: 1
  108. },
  109. messageList: [],
  110. loading: true, //标识是否正在获取数据
  111. imgHeight: '1000px',
  112. mpInputMargin: false, //适配微信小程序 底部输入框高度被顶起的问题
  113. chatType:"voice", // 图标类型 'voice'语音 'keyboard'键盘
  114. voiceTitle: '点击开始面试',
  115. Recorder: uni.getRecorderManager(),
  116. Audio: uni.createInnerAudioContext(),
  117. recording: false, //标识是否正在录音
  118. isStopVoice: false, //加锁 防止点击过快引起的当录音正在准备(还没有开始录音)的时候,却调用了stop方法但并不能阻止录音的问题
  119. voiceInterval:null,
  120. voiceTime:0, //总共录音时长
  121. canSend:true, //是否可以发送
  122. PointY:0, //坐标位置
  123. voiceIconText:"正在录音...",
  124. showFunBtn:false, //是否展示功能型按钮
  125. AudioExam:null, //正在播放音频的实例
  126. funList: [
  127. { icon:"photo-fill",title:"照片",uploadType:["album"] },
  128. { icon:"camera-fill",title:"拍摄",uploadType:["camera"] },
  129. ],
  130. };
  131. },
  132. methods: {
  133. //拼接消息 处理滚动
  134. async joinData() {
  135. if (!this.loading) {
  136. //如果没有获取数据 即loading为false时,return 避免用户重复上拉触发加载
  137. return;
  138. }
  139. this.loading = false;
  140. const data = await this.getMessageData();
  141. //获取节点信息
  142. const { index } = this.formData;
  143. const sel = `#msg-${index > 1 ? this.messageList[0].hasBeenSentId : data[data.length - 1].hasBeenSentId}`;
  144. this.messageList = [...data, ...this.messageList];
  145. //填充数据后,视图会自动滚动到最上面一层然后瞬间再跳回bindScroll的指定位置 ---体验不是很好,后期优化
  146. // this.$nextTick(() => {
  147. // this.bindScroll(sel);
  148. // //如果还有数据
  149. // if (this.formData.limit >= data.length) {
  150. // this.formData.index++;
  151. // setTimeout(() => {
  152. // this.loading = true;
  153. // }, 200);
  154. // }
  155. // });
  156. },
  157. //处理滚动
  158. // bindScroll(sel, duration = 0) {
  159. // const query = uni.createSelectorQuery().in(this);
  160. // query
  161. // .select(sel)
  162. // .boundingClientRect(data => {
  163. // uni.pageScrollTo({
  164. // scrollTop: data && data.top - 40,
  165. // duration
  166. // });
  167. // })
  168. // .exec();
  169. // },
  170. //获取消息
  171. getMessageData() {
  172. let getData = () => {
  173. let arr = [];
  174. let startIndex = (this.formData.index - 1) * this.formData.limit;
  175. let endIndex = startIndex + this.formData.limit;
  176. for (let i = startIndex; i < endIndex; i++) {
  177. const isItMe = Math.random() > 0.5 ? true : false;
  178. arr.unshift({
  179. hasBeenSentId: i, //已发送过去消息的id
  180. content: `很高兴认识你,这是第${i + 1}条消息。`,
  181. fromUserHeadImg: isItMe ? this._user_info.headImg : this.fromUserInfo.fromUserHeadImg, //用户头像
  182. fromUserId: isItMe ? this._user_info.id : this.fromUserInfo.fromUserId,
  183. isItMe, //true此条信息是我发送的 false别人发送的
  184. createTime: Date.now(),
  185. contentType: 1, // 1文字文本 2语音
  186. anmitionPlay: false //标识音频是否在播放
  187. });
  188. }
  189. return arr;
  190. };
  191. return new Promise((resolve, reject) => {
  192. const data = getData();
  193. setTimeout(() => {
  194. resolve(data);
  195. }, 500);
  196. });
  197. },
  198. //切换语音或者键盘方式
  199. switchChatType(type) {
  200. this.chatType = type;
  201. this.showFunBtn =false;
  202. },
  203. //切换功能性按钮
  204. switchFun(){
  205. this.chatType = 'keyboard'
  206. this.showFunBtn = !this.showFunBtn;
  207. uni.hideKeyboard()
  208. },
  209. //发送消息
  210. sendMsg(data) {
  211. const params = {
  212. hasBeenSentId: Date.now(), //已发送过去消息的id
  213. content: this.formData.content,
  214. fromUserHeadImg: this._user_info.headImg, //用户头像
  215. fromUserId: this._user_info.id,
  216. isItMe: true, //true此条信息是我发送的 false别人发送的
  217. createTime: Date.now(),
  218. contentType: 1
  219. };
  220. if (data) {
  221. if(data.contentType == 2){
  222. //说明是发送语音
  223. params.content = data.content;
  224. params.contentType = data.contentType;
  225. params.contentDuration = data.contentDuration;
  226. params.anmitionPlay = false;
  227. }else if(data.contentType == 3){
  228. //发送图片
  229. params.content = data.content;
  230. params.contentType = data.contentType;
  231. }
  232. } else if (!this.$u.trim(this.formData.content)) {
  233. //验证输入框书否为空字符传
  234. return;
  235. }
  236. this.messageList.push(params);
  237. this.$nextTick(() => {
  238. this.formData.content = '';
  239. // #ifdef MP-WEIXIN
  240. if(params.contentType == 1){
  241. uni.pageScrollTo({
  242. scrollTop: 99999,
  243. duration: 0, //小程序如果有滚动效果 input的焦点也会随着页面滚动...
  244. });
  245. }else{
  246. setTimeout(()=>{
  247. uni.pageScrollTo({
  248. scrollTop: 99999,
  249. duration: 0, //小程序如果有滚动效果 input的焦点也会随着页面滚动...
  250. });
  251. },150)
  252. }
  253. // #endif
  254. // #ifndef MP-WEIXIN
  255. uni.pageScrollTo({
  256. scrollTop: 99999,
  257. duration: 100
  258. });
  259. // #endif
  260. if(this.showFunBtn){
  261. this.showFunBtn = false;
  262. }
  263. // #ifdef MP-WEIXIN
  264. if (params.contentType == 1) {
  265. this.mpInputMargin = true;
  266. }
  267. // #endif
  268. //h5浏览器并没有很好的办法控制键盘一直处于唤起状态 而且会有样式性的问题
  269. // #ifdef H5
  270. uni.hideKeyboard();
  271. // #endif
  272. });
  273. },
  274. //用户触摸屏幕的时候隐藏键盘
  275. touchstart() {
  276. uni.hideKeyboard();
  277. },
  278. // userid 用户id
  279. linkToBusinessCard(userId) {
  280. this.$u.route({
  281. url: 'pages/businessCard/businessCard',
  282. params: {
  283. userId
  284. }
  285. });
  286. },
  287. linkToHistory() {
  288. uni.navigateTo({
  289. url:'../history/index'
  290. })
  291. },
  292. goPayPage() {
  293. uni.navigateTo({
  294. url:'../payPage/index'
  295. })
  296. },
  297. //准备开始录音
  298. startVoice(e) {
  299. if(!this.Audio.paused){
  300. //如果音频正在播放 先暂停。
  301. this.stopAudio(this.AudioExam)
  302. }
  303. this.recording = true;
  304. this.isStopVoice = false;
  305. this.canSend = true;
  306. this.voiceIconText = "正在录音..."
  307. this.PointY = e.touches[0].clientY;
  308. this.Recorder.start({
  309. format: 'mp3'
  310. });
  311. },
  312. //录音已经开始
  313. beginVoice(){
  314. if (this.isStopVoice) {
  315. this.Recorder.stop();
  316. return;
  317. }
  318. this.voiceTitle = '松开 结束'
  319. this.voiceInterval = setInterval(()=>{
  320. this.voiceTime ++;
  321. },1000)
  322. },
  323. //move 正在录音中
  324. moveVoice(e){
  325. const PointY = e.touches[0].clientY
  326. const slideY = this.PointY - PointY;
  327. if(slideY > uni.upx2px(120)){
  328. this.canSend = false;
  329. this.voiceIconText = '松开手指 取消发送 '
  330. }else if(slideY > uni.upx2px(60)){
  331. this.canSend = true;
  332. this.voiceIconText = '手指上滑 取消发送 '
  333. }else{
  334. this.voiceIconText = '正在录音... '
  335. }
  336. },
  337. //结束录音
  338. endVoice() {
  339. this.isStopVoice = true; //加锁 确保已经结束录音并不会录制
  340. this.Recorder.stop();
  341. this.voiceTitle = '点击开始面试'
  342. },
  343. //录音被打断
  344. cancelVoice(e){
  345. this.voiceTime = 0;
  346. this.voiceTitle = '点击开始面试';
  347. this.canSend = false;
  348. this.Recorder.stop();
  349. },
  350. //处理录音文件
  351. handleRecorder({ tempFilePath,duration }) {
  352. let contentDuration;
  353. // #ifdef MP-WEIXIN
  354. this.voiceTime = 0;
  355. if (duration < 600) {
  356. this.voiceIconText="说话时间过短";
  357. setTimeout(()=>{
  358. this.recording = false;
  359. },200)
  360. return;
  361. }
  362. contentDuration = duration/1000;
  363. // #endif
  364. // #ifdef APP-PLUS
  365. contentDuration = this.voiceTime +1;
  366. this.voiceTime = 0;
  367. if(contentDuration <= 0) {
  368. this.voiceIconText="说话时间过短";
  369. setTimeout(()=>{
  370. this.recording = false;
  371. },200)
  372. return;
  373. };
  374. // #endif
  375. this.recording = false;
  376. const params = {
  377. contentType: 2,
  378. content: tempFilePath,
  379. contentDuration: Math.ceil(contentDuration)
  380. };
  381. this.canSend && this.sendMsg(params);
  382. },
  383. //控制播放还是暂停音频文件
  384. handleAudio(item) {
  385. this.AudioExam = item;
  386. this.Audio.paused ? this.playAudio(item) : this.stopAudio(item);
  387. },
  388. //播放音频
  389. playAudio(item) {
  390. this.Audio.src = item.content;
  391. this.Audio.hasBeenSentId = item.hasBeenSentId;
  392. this.Audio.play();
  393. item.anmitionPlay = true;
  394. },
  395. //停止音频
  396. stopAudio(item) {
  397. item.anmitionPlay = false;
  398. this.Audio.src = '';
  399. this.Audio.stop();
  400. },
  401. //关闭动画
  402. closeAnmition() {
  403. const hasBeenSentId = this.Audio.hasBeenSentId;
  404. const item = this.messageList.find(it => it.hasBeenSentId == hasBeenSentId);
  405. item.anmitionPlay = false;
  406. },
  407. //点击宫格时触发
  408. clickGrid(index){
  409. if(index == 0){
  410. this.chooseImage(['album'])
  411. }else if(index == 1){
  412. this.chooseImage(['camera'])
  413. }
  414. },
  415. //发送图片
  416. chooseImage(sourceType){
  417. uni.chooseImage({
  418. sourceType,
  419. sizeType:['compressed'],
  420. success:res=>{
  421. this.showFunBtn = false;
  422. for(let i = 0;i<res.tempFilePaths.length;i++){
  423. const params = {
  424. contentType: 3,
  425. content: res.tempFilePaths[i],
  426. };
  427. this.sendMsg(params)
  428. }
  429. }
  430. })
  431. },
  432. //查看大图
  433. viewImg(imgList){
  434. uni.previewImage({
  435. urls: imgList,
  436. // #ifndef MP-WEIXIN
  437. indicator: 'number'
  438. // #endif
  439. });
  440. },
  441. },
  442. onPageScroll(e) {
  443. if (e.scrollTop < 50) {
  444. this.joinData();
  445. }
  446. },
  447. onNavigationBarButtonTap({ index }) {
  448. if (index == 0) {
  449. //用户详情 设置
  450. } else if (index == 1) {
  451. //返回按钮
  452. this.$u.route({
  453. type: 'switchTab',
  454. url: 'pages/home/home'
  455. });
  456. }
  457. },
  458. //返回按钮事件
  459. onBackPress(e) {
  460. //以下内容对h5不生效
  461. //--所以如果用浏览器自带的返回按钮进行返回的时候页面不会重定向 正在寻找合适的解决方案
  462. this.$u.route({
  463. type: 'switchTab',
  464. url: 'pages/home/home'
  465. });
  466. return true;
  467. },
  468. onLoad(info) {
  469. // { messageId,fromUserName,fromUserHeadImg } = info
  470. // const userInfo = this.firendList.filter(item => item.userId == info.fromUserId)[0];
  471. // console.log('userInfo')
  472. this.fromUserInfo = {
  473. fromUserName: 'ai-test',
  474. fromUserHeadImg: require('@/static/ai-bg.png'),
  475. fromUserId: 1,
  476. messageId: 666
  477. };
  478. //录音开始事件
  479. this.Recorder.onStart(e => {
  480. this.beginVoice();
  481. });
  482. //录音结束事件
  483. this.Recorder.onStop(res => {
  484. clearInterval(this.voiceInterval);
  485. this.handleRecorder(res);
  486. });
  487. //音频停止事件
  488. this.Audio.onStop(e => {
  489. this.closeAnmition();
  490. });
  491. //音频播放结束事件
  492. this.Audio.onEnded(e => {
  493. this.closeAnmition();
  494. });
  495. },
  496. onReady() {
  497. //自定义返回按钮 因为原生的返回按钮不可阻止默认事件
  498. // #ifdef H5
  499. const icon = document.getElementsByClassName('uni-page-head-btn')[0];
  500. icon.style.display = 'none';
  501. // #endif
  502. uni.setNavigationBarTitle({
  503. title: this.fromUserInfo.fromUserName
  504. });
  505. this.joinData();
  506. uni.getSystemInfo({
  507. success: res => {
  508. this.imgHeight = res.windowHeight + 'px';
  509. }
  510. });
  511. uni.onKeyboardHeightChange(res => {
  512. if (res.height == 0) {
  513. // #ifdef MP-WEIXIN
  514. this.mpInputMargin = false;
  515. // #endif
  516. }else{
  517. this.showFunBtn = false;
  518. }
  519. });
  520. }
  521. };
  522. </script>
  523. <style lang="scss" scoped>
  524. @import './index.scss'
  525. </style>