index.vue 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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="linkToBack()">记录详情</view>
  8. <view class="message" v-for="(item, index) in messageList" :key="index" :id="`msg-${item.hasBeenSentId}`"
  9. :class="index == 0 ? 'marginTop50' : ' '">
  10. <view class="message-item " :class="item.isItMe ? 'right' : 'left'">
  11. <image class="img" :src="item.fromUserHeadImg" mode=""></image>
  12. <!-- contentType = 1 文本 -->
  13. <view class="content" v-if="item.contentType == 1">{{ item.content }}
  14. <button class="pay-btn-class" @tap="goPayPage" v-show="index == 2">前往缴费</button>
  15. <image class="img" :src="item.fromUserHeadImg" mode=""></image>
  16. </view>
  17. <!-- contentType = 2 语音 -->
  18. <view class="content contentType2" :class="[{ 'content-type-right': item.isItMe }]"
  19. v-if="item.contentType == 2" @tap="handleAudio(item)" hover-class="contentType2-hover-class"
  20. :style="{width:`${130+(item.contentDuration*2)}rpx`}">
  21. <view class="voice_icon" :class="[
  22. { voice_icon_right: item.isItMe },
  23. { voice_icon_left: !item.isItMe },
  24. { voice_icon_right_an: item.anmitionPlay && item.isItMe },
  25. { voice_icon_left_an: item.anmitionPlay && !item.isItMe }
  26. ]"></view>
  27. <view class="">{{ item.contentDuration }}''</view>
  28. </view>
  29. </view>
  30. </view>
  31. </view>
  32. <!-- 底部聊天输入框 -->
  33. <view v-if="false" class="input-box" :class="{ 'input-box-mpInputMargin': mpInputMargin }">
  34. <view class="input-box-flex">
  35. <!-- #ifndef H5 -->
  36. <!-- <image v-if="chatType === 'voice'" class="icon_img" :src="require('@/static/voice.png')" @click="switchChatType('keyboard')"></image>
  37. <image v-if="chatType === 'keyboard'" class="icon_img" :src="require('@/static/keyboard.png')" @click="switchChatType('voice')"></image> -->
  38. <!-- #endif -->
  39. <view class="input-box-flex-grow">
  40. <!-- <input
  41. v-if="chatType === 'voice'"
  42. type="text"
  43. class="content"
  44. id="input"
  45. v-model="formData.content"
  46. :hold-keyboard="true"
  47. :confirm-type="'send'"
  48. :confirm-hold="true"
  49. placeholder-style="color:#DDDDDD;"
  50. :cursor-spacing="10"
  51. @confirm="sendMsg(null)"
  52. /> -->
  53. <view class="voice_title" @touchstart.stop.prevent="startVoice" @touchmove.stop.prevent="moveVoice"
  54. @touchend.stop="endVoice" @touchcancel.stop="cancelVoice">
  55. {{ voiceTitle }}
  56. </view>
  57. </view>
  58. <!-- 功能性按钮 -->
  59. <!-- <image class=" icon_btn_add" :src="require('@/static/add.png')" @tap="switchFun"></image> -->
  60. <!-- #ifdef H5 -->
  61. <!-- <button class="btn" type="primary" size="mini" @touchend.prevent="sendMsg(null)">发送</button> -->
  62. <!-- #endif -->
  63. </view>
  64. <view class="fun-box" :class="{'show-fun-box':showFunBtn}">
  65. <u-grid :col="4" hover-class="contentType2-hover-class" :border="false" @click="clickGrid">
  66. <u-grid-item v-for="(item, index) in funList" :index="index" :key="index" bg-color="#eaeaea">
  67. <u-icon :name="item.icon" :size="52"></u-icon>
  68. <view class="grid-text">{{ item.title }}</view>
  69. </u-grid-item>
  70. </u-grid>
  71. </view>
  72. </view>
  73. <!-- //语音动画 -->
  74. <view class="voice_an" v-if="recording">
  75. <view class="voice_an_icon">
  76. <view id="one" class="wave"></view>
  77. <view id="two" class="wave"></view>
  78. <view id="three" class="wave"></view>
  79. <view id="four" class="wave"></view>
  80. <view id="five" class="wave"></view>
  81. <view id="six" class="wave"></view>
  82. <view id="seven" class="wave"></view>
  83. </view>
  84. <view class="text">{{voiceIconText}}</view>
  85. </view>
  86. </view>
  87. </template>
  88. <script>
  89. export default {
  90. data() {
  91. return {
  92. fromUserInfo: {},
  93. formData: {
  94. content: '',
  95. limit: 15,
  96. index: 1
  97. },
  98. messageList: [],
  99. loading: true, //标识是否正在获取数据
  100. imgHeight: '1000px',
  101. mpInputMargin: false, //适配微信小程序 底部输入框高度被顶起的问题
  102. chatType: "voice", // 图标类型 'voice'语音 'keyboard'键盘
  103. voiceTitle: '点击开始面试',
  104. Recorder: uni.getRecorderManager(),
  105. Audio: uni.createInnerAudioContext(),
  106. recording: false, //标识是否正在录音
  107. isStopVoice: false, //加锁 防止点击过快引起的当录音正在准备(还没有开始录音)的时候,却调用了stop方法但并不能阻止录音的问题
  108. voiceInterval: null,
  109. voiceTime: 0, //总共录音时长
  110. canSend: true, //是否可以发送
  111. PointY: 0, //坐标位置
  112. voiceIconText: "正在录音...",
  113. showFunBtn: false, //是否展示功能型按钮
  114. AudioExam: null, //正在播放音频的实例
  115. funList: [{
  116. icon: "photo-fill",
  117. title: "照片",
  118. uploadType: ["album"]
  119. },
  120. {
  121. icon: "camera-fill",
  122. title: "拍摄",
  123. uploadType: ["camera"]
  124. },
  125. ],
  126. };
  127. },
  128. methods: {
  129. //拼接消息 处理滚动
  130. async joinData() {
  131. if (!this.loading) {
  132. //如果没有获取数据 即loading为false时,return 避免用户重复上拉触发加载
  133. return;
  134. }
  135. this.loading = false;
  136. const data = await this.getMessageData();
  137. // 获取节点信息
  138. const {
  139. index
  140. } = this.formData;
  141. const sel =
  142. `#msg-${index > 1 ? this.messageList[0].hasBeenSentId : data[data.length - 1].hasBeenSentId}`;
  143. // this.messageList = [...data, ...this.messageList];
  144. //填充数据后,视图会自动滚动到最上面一层然后瞬间再跳回bindScroll的指定位置 ---体验不是很好,后期优化
  145. // this.$nextTick(() => {
  146. // this.bindScroll(sel);
  147. // //如果还有数据
  148. // if (this.formData.limit >= data.length) {
  149. // this.formData.index++;
  150. // setTimeout(() => {
  151. // this.loading = true;
  152. // }, 200);
  153. // }
  154. // });
  155. },
  156. //处理滚动
  157. // bindScroll(sel, duration = 0) {
  158. // const query = uni.createSelectorQuery().in(this);
  159. // query
  160. // .select(sel)
  161. // .boundingClientRect(data => {
  162. // uni.pageScrollTo({
  163. // scrollTop: data && data.top - 40,
  164. // duration
  165. // });
  166. // })
  167. // .exec();
  168. // },
  169. //获取消息
  170. getMessageData() {
  171. let getData = () => {
  172. let arr = [];
  173. let startIndex = (this.formData.index - 1) * this.formData.limit;
  174. let endIndex = startIndex + this.formData.limit;
  175. for (let i = startIndex; i < endIndex; i++) {
  176. const isItMe = Math.random() > 0.5 ? true : false;
  177. arr.unshift({
  178. hasBeenSentId: i, //已发送过去消息的id
  179. content: `很高兴认识你,这是第${i + 1}条消息。`,
  180. fromUserHeadImg: isItMe ? this._user_info.headImg : this.fromUserInfo
  181. .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({
  352. tempFilePath,
  353. duration
  354. }) {
  355. let contentDuration;
  356. // #ifdef MP-WEIXIN
  357. this.voiceTime = 0;
  358. if (duration < 600) {
  359. this.voiceIconText = "说话时间过短";
  360. setTimeout(() => {
  361. this.recording = false;
  362. }, 200)
  363. return;
  364. }
  365. contentDuration = duration / 1000;
  366. // #endif
  367. // #ifdef APP-PLUS
  368. contentDuration = this.voiceTime + 1;
  369. this.voiceTime = 0;
  370. if (contentDuration <= 0) {
  371. this.voiceIconText = "说话时间过短";
  372. setTimeout(() => {
  373. this.recording = false;
  374. }, 200)
  375. return;
  376. };
  377. // #endif
  378. this.recording = false;
  379. const params = {
  380. contentType: 2,
  381. content: tempFilePath,
  382. contentDuration: Math.ceil(contentDuration)
  383. };
  384. this.canSend && this.sendMsg(params);
  385. },
  386. //控制播放还是暂停音频文件
  387. handleAudio(item) {
  388. this.AudioExam = item;
  389. this.Audio.paused ? this.playAudio(item) : this.stopAudio(item);
  390. },
  391. //播放音频
  392. playAudio(item) {
  393. this.Audio.src = item.content;
  394. this.Audio.hasBeenSentId = item.hasBeenSentId;
  395. this.Audio.play();
  396. item.anmitionPlay = true;
  397. },
  398. //停止音频
  399. stopAudio(item) {
  400. item.anmitionPlay = false;
  401. this.Audio.src = '';
  402. this.Audio.stop();
  403. },
  404. //关闭动画
  405. closeAnmition() {
  406. const hasBeenSentId = this.Audio.hasBeenSentId;
  407. const item = this.messageList.find(it => it.hasBeenSentId == hasBeenSentId);
  408. item.anmitionPlay = false;
  409. },
  410. //点击宫格时触发
  411. clickGrid(index) {
  412. if (index == 0) {
  413. this.chooseImage(['album'])
  414. } else if (index == 1) {
  415. this.chooseImage(['camera'])
  416. }
  417. },
  418. //发送图片
  419. chooseImage(sourceType) {
  420. uni.chooseImage({
  421. sourceType,
  422. sizeType: ['compressed'],
  423. success: res => {
  424. this.showFunBtn = false;
  425. for (let i = 0; i < res.tempFilePaths.length; i++) {
  426. const params = {
  427. contentType: 3,
  428. content: res.tempFilePaths[i],
  429. };
  430. this.sendMsg(params)
  431. }
  432. }
  433. })
  434. },
  435. //查看大图
  436. viewImg(imgList) {
  437. uni.previewImage({
  438. urls: imgList,
  439. // #ifndef MP-WEIXIN
  440. indicator: 'number'
  441. // #endif
  442. });
  443. },
  444. createrTime(timestamp) {
  445. if (!timestamp) return "";
  446. // 时间戳
  447. // 此处时间戳以毫秒为单位
  448. let date = new Date(parseInt(timestamp) * 1000);
  449. let Year = date.getFullYear();
  450. let Moth = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
  451. let Day = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
  452. let Hour = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
  453. let Minute = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
  454. let Sechond = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
  455. let GMT = Year + '-' + Moth + '-' + Day + ' ' + Hour + ':' + Minute + ':' + Sechond;
  456. return GMT;
  457. },
  458. linkToBack(){
  459. uni.navigateBack()
  460. }
  461. },
  462. onPageScroll(e) {
  463. if (e.scrollTop < 50) {
  464. this.joinData();
  465. }
  466. },
  467. onNavigationBarButtonTap({
  468. index
  469. }) {
  470. if (index == 0) {
  471. //用户详情 设置
  472. } else if (index == 1) {
  473. //返回按钮
  474. this.$u.route({
  475. type: 'switchTab',
  476. url: 'pages/home/home'
  477. });
  478. }
  479. },
  480. //返回按钮事件
  481. onBackPress(e) {
  482. //以下内容对h5不生效
  483. //--所以如果用浏览器自带的返回按钮进行返回的时候页面不会重定向 正在寻找合适的解决方案
  484. this.$u.route({
  485. type: 'switchTab',
  486. url: 'pages/home/home'
  487. });
  488. return true;
  489. },
  490. onLoad(info) {
  491. // { messageId,fromUserName,fromUserHeadImg } = info
  492. // const userInfo = this.firendList.filter(item => item.userId == info.fromUserId)[0];
  493. // console.log('userInfo')
  494. this.fromUserInfo = {
  495. fromUserName: 'ai-test',
  496. fromUserHeadImg: require('@/static/ai-bg.png'),
  497. fromUserId: 1,
  498. messageId: 666
  499. };
  500. //录音开始事件
  501. this.Recorder.onStart(e => {
  502. this.beginVoice();
  503. });
  504. //录音结束事件
  505. this.Recorder.onStop(res => {
  506. clearInterval(this.voiceInterval);
  507. this.handleRecorder(res);
  508. });
  509. //音频停止事件
  510. this.Audio.onStop(e => {
  511. this.closeAnmition();
  512. });
  513. //音频播放结束事件
  514. this.Audio.onEnded(e => {
  515. this.closeAnmition();
  516. });
  517. },
  518. mounted() {
  519. let pages = getCurrentPages(); //获取当前页面栈
  520. let currentPage = pages[pages.length - 1]; //获取当前页面对象
  521. let interviewid = currentPage.options.interviewid;
  522. let that = this;
  523. uni.request({
  524. url: getApp().globalData.services.interviewdetail, //需要设置为全局
  525. method: 'POST',
  526. header: {
  527. 'content-type': 'application/x-www-form-urlencoded'
  528. },
  529. data: {
  530. accesstoken: that.$store.state._token,
  531. jwtcode: that.$store.state._jwtcode,
  532. interviewid
  533. },
  534. success: ({
  535. data: {
  536. errmsg,
  537. data
  538. }
  539. }) => {
  540. if (errmsg === "OK") {
  541. let a = data.map(item => ({
  542. hasBeenSentId: item.id, //已发送过去消息的id
  543. content: item.content || "",
  544. fromUserHeadImg: item.issystem === 2 ? that.$store._user_info.headImg : that.fromUserInfo.fromUserHeadImg, //用户头像
  545. fromUserId: item.userid,
  546. isItMe: item.issystem === 2, //true此条信息是我发送的 false别人发送的
  547. createTime: that.createrTime(item.addtime),
  548. contentType: !!item.file ? 2 : 1, // 1文字文本 2语音
  549. anmitionPlay: false //标识音频是否在播放
  550. }))
  551. that.messageList=a;
  552. }
  553. }
  554. });
  555. },
  556. onReady() {
  557. //自定义返回按钮 因为原生的返回按钮不可阻止默认事件
  558. // #ifdef H5
  559. const icon = document.getElementsByClassName('uni-page-head-btn')[0];
  560. icon.style.display = 'none';
  561. // #endif
  562. uni.setNavigationBarTitle({
  563. title: this.fromUserInfo.fromUserName
  564. });
  565. this.joinData();
  566. uni.getSystemInfo({
  567. success: res => {
  568. this.imgHeight = res.windowHeight + 'px';
  569. }
  570. });
  571. uni.onKeyboardHeightChange(res => {
  572. if (res.height == 0) {
  573. // #ifdef MP-WEIXIN
  574. this.mpInputMargin = false;
  575. // #endif
  576. } else {
  577. this.showFunBtn = false;
  578. }
  579. });
  580. }
  581. };
  582. </script>
  583. <style lang="scss" scoped>
  584. @import './index.scss'
  585. </style>