index.vue 13 KB

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