index.vue 11 KB

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