index.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. <template>
  2. <view class="main">
  3. <view class="content">
  4. <scroll-view scroll-y="true" class="scroll-view" :scroll-into-view="poaMessgae" scroll-with-animation="true"
  5. refresher-enabled="true" :refresher-triggered="triggered" @refresherrefresh="getFresh">
  6. <view class="list-scroll-view">
  7. <view class="block" v-for="(item,index) in list" :key="index">
  8. <view class="time" v-if="index == 0 || item.time - list[index-1].time >= 300000">
  9. <text>{{formatDate(item.time)}}</text>
  10. </view>
  11. <view class="list" :id="item.speaker._id != userId ? 'left' : 'right'">
  12. <image class="avatar"
  13. :src="item.speaker&&item.speaker.icon.length>0?item.speaker.icon[0].url:config.user_url[0].url"
  14. mode=""></image>
  15. <text class="record" v-if="item.type == 'text'">{{item.content}}</text>
  16. <image :src="item.content" v-if="item.type == 'image'" @tap="onPreview(item.content)"
  17. mode="widthFix">
  18. </image>
  19. <view class="record" v-if="item.type == 'record'" @tap="onPlay(item.content,index)">
  20. <uni-icons v-if="item.speaker._id != userId" custom-prefix="iconfont"
  21. type="icon-zuobofang" size="15" color="#333333">
  22. </uni-icons>
  23. <text class="voice">{{item.voice}}</text>"
  24. <uni-icons v-if="item.speaker._id == userId" custom-prefix="iconfont"
  25. type="icon-youbofang" size="15" color="#ffffff">
  26. </uni-icons>
  27. </view>
  28. </view>
  29. </view>
  30. <view id="poaMessgae"></view> <!-- 仅用于定位到消息最后一条 -->
  31. </view>
  32. </scroll-view>
  33. </view>
  34. <view class="bottom">
  35. <submit_1 :record="record" :inrecord="inrecord" :isRecorder="isRecorder" @toSend="toSend" @heights="heights"
  36. @onRecorderchange="onRecorderchange" @onStart="onStart" @onEnd="onEnd"></submit_1>
  37. </view>
  38. <!-- 语音 -->
  39. <uni-popup ref="voice" background-color="#fff">
  40. <view class="image">
  41. <image class="avatar" :src="config.audio_url[0].url"></image>
  42. </view>
  43. </uni-popup>
  44. </view>
  45. </template>
  46. <script>
  47. import WebSocket from "@/common/websocket.js"
  48. import submit_1 from './common/submit_1.vue';
  49. export default {
  50. components: {
  51. submit_1,
  52. },
  53. data() {
  54. return {
  55. id: '',
  56. // 群
  57. groupId: '',
  58. // 病人
  59. patientId: '',
  60. // 医生
  61. doctorId: '',
  62. // 用户id
  63. userId: '',
  64. user: {},
  65. config: {},
  66. // 聊天列表数据
  67. list: [],
  68. total: 0,
  69. skip: 0,
  70. limit: 6,
  71. page: 0,
  72. record: '', // 全局唯一录音管理区
  73. inrecord: false, // 是否处于录音状态
  74. isRecorder: false, // 是否处于语音状态
  75. bgAudioManager: '', // 全局音频播放
  76. poaMessgae: 'poaMessgae', //滚动到最底部
  77. // 判断是否跳到最后一条
  78. is_bottom: true,
  79. // 判断是否下拉刷新复位
  80. triggered: false,
  81. //实时通信
  82. client: null,
  83. subscription: null
  84. }
  85. },
  86. onLoad: async function(e) {
  87. const that = this;
  88. that.$set(that, `groupId`, e && e.groupId || '');
  89. that.$set(that, `patientId`, e && e.patientId || '');
  90. that.$set(that, `doctorId`, e && e.doctorId || '');
  91. uni.setNavigationBarTitle({
  92. title: e && e.title || '聊天室'
  93. });
  94. await that.searchToken();
  95. await that.searchConfig();
  96. await that.searchOther();
  97. await that.search();
  98. },
  99. onShow: async function() {
  100. const that = this;
  101. // 全局唯一录音管理器
  102. that.record = uni.getRecorderManager();
  103. // 滚动到最底部
  104. that.poalast()
  105. // stomp协议请求 实时链接
  106. that.initWS()
  107. },
  108. // 离开页面是关闭连接
  109. // 我的业务是仿微信这种,每次连接人不同,频繁建立新连接,根据自己需要决定什么时候关闭连接
  110. onUnload: function() {
  111. const that = this;
  112. that.client && that.client.close()
  113. },
  114. methods: {
  115. // 用户信息
  116. searchToken() {
  117. const that = this;
  118. try {
  119. const res = uni.getStorageSync('token');
  120. if (res) {
  121. const user = that.$jwt(res);
  122. that.$set(that, `user`, user);
  123. if (user.role == 'Nurse') that.$set(that, `userId`, user.doctor);
  124. else that.$set(that, `userId`, user._id);
  125. }
  126. } catch (e) {}
  127. },
  128. searchConfig() {
  129. const that = this;
  130. try {
  131. const res = uni.getStorageSync('config');
  132. if (res) that.$set(that, `config`, res);
  133. } catch (e) {}
  134. },
  135. async search() {
  136. const that = this;
  137. // 聊天记录
  138. let info = {
  139. skip: that.skip,
  140. limit: that.limit,
  141. patient: that.patientId,
  142. group: that.groupId,
  143. doctor: that.doctorId
  144. }
  145. const res = await that.$api(`/chat`, 'GET', {
  146. ...info
  147. })
  148. if (res.errcode == '0') {
  149. let list = [...res.data.reverse(), ...that.list];
  150. that.$set(that, `list`, list)
  151. that.$set(that, `total`, res.total)
  152. } else {
  153. uni.showToast({
  154. title: res.errmsg,
  155. icon: 'none'
  156. });
  157. }
  158. },
  159. // 处理时间
  160. formatDate(value) {
  161. if (typeof(value) == 'undefined') {
  162. return ''
  163. } else {
  164. let date = new Date(value)
  165. let now = new Date()
  166. let y = date.getFullYear()
  167. let MM = date.getMonth() + 1
  168. MM = MM < 10 ? ('0' + MM) : MM
  169. let d = date.getDate()
  170. d = d < 10 ? ('0' + d) : d
  171. let h = date.getHours()
  172. h = h < 10 ? ('0' + h) : h
  173. let m = date.getMinutes()
  174. m = m < 10 ? ('0' + m) : m
  175. let s = date.getSeconds()
  176. s = s < 10 ? ('0' + s) : s
  177. if (now.getDate() - d == 1 && now - date < 172800000) {
  178. return '昨天' + h + ':' + m
  179. } else if (now - date < 86400000) {
  180. return h + ':' + m
  181. } else if (now - date >= 86400000 && now - date < 31536000000) {
  182. return MM + '-' + d + ' ' + h + ':' + m
  183. } else if (now - date >= 31536000000) {
  184. return y + '-' + MM + '-' + d + ' ' + h + ':' + m
  185. }
  186. }
  187. },
  188. //输入框高度
  189. heights(e) {
  190. const that = this;
  191. that.poalast()
  192. },
  193. // 切换语音 or 键盘
  194. onRecorderchange() {
  195. const that = this
  196. if (that.isRecorder) {
  197. that.isRecorder = false
  198. } else {
  199. uni.authorize({
  200. scope: 'scope.record',
  201. success: res => {
  202. that.isRecorder = true
  203. }
  204. })
  205. }
  206. },
  207. // 长按开始录入语音
  208. onStart() {
  209. const that = this
  210. that.$set(that, `inrecord`, true);
  211. that.$refs.voice.open('center')
  212. that.record.start({
  213. format: "mp3"
  214. })
  215. },
  216. // 长按结束录入语音
  217. onEnd() {
  218. const that = this
  219. const fileUrl = that.$config.serverUrl;
  220. that.$set(that, `inrecord`, false);
  221. that.$refs.voice.close('center')
  222. that.record.stop()
  223. // 监听录音暂停的回调参数
  224. that.record.onStop(res => {
  225. if (res.duration < 1000) {
  226. return that.global.toast('请说话久一点')
  227. }
  228. // 上传音频
  229. uni.uploadFile({
  230. url: `${fileUrl}/visit/api/files/chat_voice/${that.user._id}/upload`,
  231. filePath: res.tempFilePath,
  232. name: `file`,
  233. formData: {},
  234. success: (arr) => {
  235. const file = JSON.parse(arr.data)
  236. let mess = {
  237. type: 'record',
  238. voice: Math.round(res.duration / 1000), // 时长
  239. content: fileUrl + file.data.uri,
  240. time: new Date() - 0
  241. }
  242. // 写在上传回调内
  243. that.toSend(mess)
  244. },
  245. fail: (err) => {
  246. console.log('uploadImage fail', err);
  247. },
  248. });
  249. let mess = {
  250. type: 'record',
  251. voice: Math.round(res.duration / 1000), // 时长
  252. content: res.tempFilePath,
  253. time: new Date() - 0
  254. }
  255. // 写在上传回调内
  256. that.toSend(mess)
  257. })
  258. that.record.onError(err => {
  259. that.global.toast('获取录音失败')
  260. })
  261. },
  262. // 播放音频
  263. onPlay(e, index) {
  264. const that = this
  265. that.bgAudioManager = uni.createInnerAudioContext()
  266. that.bgAudioManager.src = e
  267. that.bgAudioManager.play()
  268. that.bgAudioManager.onEnded(() => {
  269. that.bgAudioManager.offPlay()
  270. that.bgAudioManager.offEnded()
  271. that.bgAudioManager = null
  272. })
  273. },
  274. // 预览图片
  275. onPreview(e) {
  276. uni.previewImage({
  277. urls: [e]
  278. })
  279. },
  280. // 消息链接
  281. initWS() {
  282. const that = this
  283. const brokerURL = that.$config.brokerURL;
  284. WebSocket.init(
  285. `${brokerURL}`,
  286. // 传参
  287. {
  288. host: 'visit',
  289. login: 'visit',
  290. passcode: 'visit'
  291. },
  292. // ws断开回调
  293. () => {
  294. that.initWS()
  295. }
  296. ).then((client) => {
  297. that.client = client
  298. // 订阅
  299. that.subscription = client.subscribe(
  300. // 路径
  301. `/exchange/chatEx/${that.groupId}_${that.patientId}`,
  302. // 接收到的数据
  303. (res) => {
  304. console.log(res);
  305. that.list.push(JSON.parse(res.body))
  306. // 滚动到最底部
  307. that.poalast()
  308. },
  309. )
  310. })
  311. },
  312. // 发送消息
  313. async toSend(e) {
  314. const that = this;
  315. const mess = {
  316. speaker: that.user._id,
  317. speaker_type: that.user.role,
  318. group: that.groupId,
  319. patient: that.patientId,
  320. doctor: that.doctorId,
  321. }
  322. const data = {
  323. ...e,
  324. ...mess
  325. }
  326. let res = await that.$api(`/chat`, 'POST', data)
  327. if (res.errcode == '0') {
  328. that.search()
  329. that.$set(that, `isRecorder`, false);
  330. that.poalast() // 定位消息最后一行
  331. } else {
  332. uni.showToast({
  333. title: res.errmsg,
  334. icon: 'none'
  335. });
  336. }
  337. },
  338. // 下拉刷新分页
  339. getFresh(e) {
  340. const that = this;
  341. that.$set(that, `triggered`, true)
  342. let list = that.list;
  343. let limit = that.limit;
  344. setTimeout(() => {
  345. if (that.total > list.length) {
  346. uni.showLoading({
  347. title: '加载中',
  348. mask: true
  349. })
  350. let page = that.page + 1;
  351. that.$set(that, `page`, page)
  352. let skip = page * limit;
  353. that.$set(that, `skip`, skip)
  354. that.$set(that, `is_bottom`, false)
  355. that.search();
  356. uni.hideLoading();
  357. } else {
  358. uni.showToast({
  359. title: `没有更多聊天记录了`,
  360. icon: 'none'
  361. })
  362. }
  363. that.triggered = false;
  364. }, 1000)
  365. },
  366. // 定位到消息最后一行
  367. poalast() {
  368. const that = this
  369. that.$nextTick(() => {
  370. that.$set(that, `poaMessgae`, '');
  371. setTimeout(() => {
  372. that.$set(that, `poaMessgae`, 'poaMessgae');
  373. }, 50)
  374. })
  375. },
  376. // 处理已读未读
  377. searchOther() {
  378. const that = this
  379. },
  380. }
  381. }
  382. </script>
  383. <style scoped lang="scss">
  384. .main {
  385. display: flex;
  386. flex-direction: column;
  387. box-sizing: border-box;
  388. width: 100vw;
  389. height: 100vh;
  390. .content {
  391. position: relative;
  392. flex-grow: 1;
  393. .time {
  394. display: flex;
  395. align-items: center;
  396. flex-direction: column;
  397. margin: 2vw 0;
  398. text {
  399. background: rgba(0, 0, 0, 0.6);
  400. color: var(--f6Color);
  401. padding: 1vw 2vw;
  402. border-radius: 5px;
  403. font-size: var(--font12Size);
  404. }
  405. }
  406. .list {
  407. display: flex;
  408. align-items: flex-start;
  409. margin-bottom: 4vw;
  410. .avatar {
  411. border-radius: 50%;
  412. width: 10vw;
  413. height: 10vw;
  414. }
  415. image {
  416. width: 20vw;
  417. }
  418. text {
  419. font-size: var(--font14Size);
  420. font-family: PingFang SC-Regular, PingFang SC;
  421. font-weight: 400;
  422. max-width: 70vw;
  423. }
  424. .record {
  425. display: flex;
  426. align-items: center;
  427. word-break: break-all;
  428. .voice {
  429. margin: 0 1vw;
  430. }
  431. }
  432. }
  433. #left {
  434. .avatar {
  435. margin-right: 2vw;
  436. }
  437. .record {
  438. background: #F4F8FB;
  439. border-radius: 0rpx 2vw 2vw 2vw;
  440. padding: 2vw 3vw;
  441. color: var(--f33Color);
  442. }
  443. }
  444. #right {
  445. flex-direction: row-reverse;
  446. .avatar {
  447. margin-left: 2vw;
  448. }
  449. .record {
  450. background: #6B72F6;
  451. border-radius: 2vw 0 2vw 2vw;
  452. padding: 2vw 3vw;
  453. color: var(--mainColor);
  454. }
  455. }
  456. }
  457. .bottom {
  458. background: var(--mainColor);
  459. }
  460. }
  461. .image {
  462. display: flex;
  463. align-items: center;
  464. .avatar {
  465. width: 50vw;
  466. height: 50vw;
  467. }
  468. }
  469. .scroll-view {
  470. position: absolute;
  471. top: 0;
  472. left: 0;
  473. right: 0;
  474. bottom: 0;
  475. .list-scroll-view {
  476. display: flex;
  477. flex-direction: column;
  478. margin: 0 2vw;
  479. }
  480. }
  481. </style>