// pages/childDetails/childDetails.js // 网络请求工具类 var networkUtil = require('../../utils/network_util.js') var api = require('../../utils/apiFile.js') //聊天工具类 let msgStorage = require("./chat/msgstorage"); let disp = require("../../utils/broadcast"); let WebIM = require("../../utils/WebIM")["default"]; let msgType = require("./chat/msgtype"); // 获取应用实例 var app = getApp(); let LIST_STATUS = { SHORT: "scroll_view_change", NORMAL: "scroll_view" }; let page = 0; let Index = 0; let isFail = false; let RECORD_CONST = require("./audio/record_status"); let RecordStatus = RECORD_CONST.RecordStatus; let RecordDesc = RECORD_CONST.RecordDesc; let RunAnimation = false const InitHeight = [50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50] Page({ /** * 页面的初始数据 */ data: { changedTouches: null, userData:[], illnessValue:'', type:0, memberId:0, serviceId:0, doctorHxName:'', doctorName:'', kfHxName:'', kfName:'', memberHxName:'', memberName:'', unTotleReadCount:0, chatMsg: [], username:'', bubbles:false, isShowRecordingBtn:false, RecordDesc, // 模板中有引用 recorderManager: wx.getRecorderManager(), recordClicked: false, recordStatus: RecordStatus.HIDE, RecordStatus, radomheight: InitHeight, }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { let self=this; var options=JSON.parse(options.username) networkUtil._post(api.addBabyChatroom,{doctorId:options.doctorId},function(res){ console.log(res) self.setData({ memberId:options.memberId, serviceId:options.serviceId, doctorHxName:res.data.data.doctorHxName, doctorName:res.data.data.doctorName, kfHxName:res.data.data.kfHxName, kfName:res.data.data.kfName, memberHxName:res.data.data.memberHxName, memberName:res.data.data.memberName, username:res.data.data.chatroomId }) self.initChat() },function(res){ },'application/json') self.initChat() disp.on('em.xmpp.error.sendMsgErr', function(err) { curMsgMid = err.data.mid isFail = true return console.log('发送失败了') let msgList = me.data.chatMsg msgList.map((item) =>{ if (item.mid.substring(item.mid.length - 10) == curMsgMid.substring(curMsgMid.length - 10)) { item.msg.data[0].isFail = true item.isFail = true me.setData({ chatMsg: msgList }) } }) if (me.curChatMsg[0].mid == curMsgMid) { me.curChatMsg[0].msg.data[0].isShow = false; me.curChatMsg[0].isShow = false } wx.setStorageSync("rendered_" + sessionKey, msgList); }); }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function (e) { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, // 初始化聊天数据 initChat () { //聊天功能 let me = this; let username = this.data.username; let myUsername = wx.getStorageSync("hxName"); let sessionKey = username.groupId ? username + myUsername : username + myUsername; let chatMsg = wx.getStorageSync(sessionKey) || []; this.renderMsg(null, null, chatMsg, sessionKey); wx.setStorageSync(sessionKey, null); }, //获取儿童信息 requestData(id) { var self = this networkUtil.showLoading() networkUtil._get(api.getBabyInfo , {memberId:id}, function (res) { if(0 == res.data.errorcode){ self.setData({ userData: res.data.babyInfo }) } }, function (res) { networkUtil.showErrorToast(res.errormsg) }) }, //跳转血糖值 gohisSuger(){ var id = this.data.memberId; wx.navigateTo({ url: "../historicalSymptoms/historicalSymptoms?memberId="+id, }) }, //结束咨询 endConsultation(){ var id = this.data.serviceId; var that = this; wx.showModal({ title: '确认', content: '请确认是否要结束', showCancel: true, success: function(res) { if (res.confirm) { networkUtil.showLoading() networkUtil._get(api.serviceEnd , {serviceId:id}, function (res) { if(0 == res.data.errorcode){ wx.getNetworkType({ success: function (res) { // console.log("getNetworkType:",res) if (res.networkType == 'none' && wx.getStorageSync('isHxOpend') == true) { wx.showModal({ title: '提示', content: '请检查网络', showCancel: false, success: function (res) { } }) //断网时不清空消息 that.setData({ inputMessage: that.data.sendInfo }) } else { // //console.log(that.data.userMessage) // //console.log(that.data.sendInfo) var myName = wx.getStorageSync('hxName') var id = WebIM.conn.getUniqueId(); var msg = new WebIM.message('txt', id); msg.set({ msg: '医生已结束咨询服务', from: myName, to: that.data.username, roomType: false, ext:{ isEnding:true, serviceId:that.data.serviceId }, success: function (id, serverMsgId) { console.log(' sendMessage success') }, fail: function (error) { console.log("sendMessage error:" + error) } }); console.log('发送消息', msg) msg.body.chatType = 'chatRoom'; msg.body.group = 'groupchat' ; msg.body.from = myName WebIM.conn.send(msg.body); } } }) wx.navigateBack({ delta: 1, }) } }, function (res) { wx.showModal({ title: '服务器异常', content: err.errormsg, showCancel: false }); }) } else if (res.cancel) { console.log('用户点击取消') } }, }); }, //消息发送 bindMessage(e){ //console.log(e.detail.value) this.setData({ userMessage: e.detail.value }); if(this.data.userMessage){ this.setData({ bubbles:true }) }else{ this.setData({ bubbles:false }) } }, sendMessage: function () { String.prototype.trim=function() { return this.replace(/(^\s*)|(\s*$)/g, ''); } if(!this.data.userMessage.trim()){ return; } var that = this wx.getNetworkType({ success: function (res) { // console.log("getNetworkType:",res) if (res.networkType == 'none' && wx.getStorageSync('isHxOpend') == true) { wx.showModal({ title: '提示', content: '请检查网络', showCancel: false, success: function (res) { } }) //断网时不清空消息 that.setData({ inputMessage: that.data.sendInfo }) } else { // //console.log(that.data.userMessage) // //console.log(that.data.sendInfo) var myName = wx.getStorageSync('hxName') var id = WebIM.conn.getUniqueId(); var msg = new WebIM.message('txt', id); msg.set({ msg: that.data.userMessage, to: that.data.username, roomType: false, ext:{ serviceId:that.data.serviceId }, success: function (id, serverMsgId) { console.log(' sendMessage success') }, fail: function (error) { console.log("sendMessage error:" + error) } }); console.log('发送消息', msg) msg.body.chatType = 'chatRoom'; msg.body.group = 'groupchat' ; msg.body.from = myName WebIM.conn.send(msg.body); that.triggerEvent( "newTextMsg", { msg: msg, type: msgType.TEXT, }, { bubbles: true, composed: true } ); if (msg) { var value = WebIM.parseEmoji(msg.value.replace(/\n/mg, '')) var time = WebIM.time() var msgData = { info: { to: msg.body.to }, username: myName, yourname: msg.body.to, msg: { type: msg.type, data: value }, style: 'self', time: time, mid: msg.id } that.data.chatMsg.push(msgData) console.log(that.data.chatMsg) var sessionKey = that.data.username + myName; var historyChatMsgs = wx.getStorageSync("rendered_" + sessionKey) || []; historyChatMsgs.push(msgData); // 消息提醒音效 // const innerAudioContext = wx.createInnerAudioContext(); // innerAudioContext.src = '../../source/maide/9411.mp3'; // innerAudioContext.play(); // innerAudioContext.onPlay(() => { // console.log('开始播放') // }) // innerAudioContext.onError((res) => { // console.log(res.errMsg) // console.log(res.errCode) // }) wx.vibrateLong({ success:function() { console.log('震动调取成功') }, }) wx.setStorage({ key: "rendered_" + that.data.username + myName, data: historyChatMsgs, success: function () { //console.log('success', that.data) that.setData({ chatMsg: that.data.chatMsg, emojiList: [], inputMessage: '', bubbles:false }) that.onRender(); setTimeout(function () { that.setData({ toView: that.data.chatMsg[that.data.chatMsg.length - 1].mid }) }, 100) } }) that.setData({ userMessage: '' }) } } }, }) }, //接收消息 //接收消息 receiveMsg: function (msg, type) { var that = this var myName = wx.getStorageSync('hxName') if (msg.from == that.data.username || msg.to == that.data.username) { console.log(msg) if (type == 'txt') { var value = WebIM.parseEmoji(msg.data.replace(/\n/mg, '')) } else if (type == 'emoji') { var value = msg.data } //console.log(msg) //console.log(value) var time = WebIM.time() var msgData = { info: { from: msg.from, to: msg.to }, username: msg.from, yourname: msg.from, msg: { type: type, data: value, url: msg.url }, style: '', time: time, mid: msg.type + msg.id } if (type == 'audio') { msgData.msg.length = msg.length, msgData.msg.token = msg.accessToken } if (msg.from !== myName) { msgData.style = '' msgData.username = msg.from } else { msgData.style = 'self' msgData.username = msg.to } console.log(msgData, that.data.chatMsg, that.data) that.data.chatMsg.push(msgData) var sessionKey = that.data.username + myName ; var historyChatMsgs = wx.getStorageSync("rendered_" + sessionKey) || []; //console.log('当前历史',renderableMsg) //console.log('历史消息', historyChatMsgs) historyChatMsgs.push(msgData); wx.vibrateLong({ success:function() { console.log('震动调取成功') }, }) wx.setStorage({ key: "rendered_" + that.data.username + myName, data: historyChatMsgs, success: function () { console.log('success接收保存', that.data) that.setData({ chatMsg: that.data.chatMsg, }) that.onRender(); setTimeout(function () { that.setData({ toView: that.data.chatMsg[that.data.chatMsg.length - 1].mid }) }, 100) } }) } }, renderMsg(renderableMsg, type, curChatMsg, sessionKey, isnew){ let me = this var historyChatMsgs = wx.getStorageSync("rendered_" + sessionKey) || []; //console.log('当前历史',renderableMsg) console.log('历史消息', historyChatMsgs) if(curChatMsg !== []){ historyChatMsgs = historyChatMsgs.concat(curChatMsg); wx.setStorageSync(sessionKey, []); app.globalData.unrederMsg[sessionKey] = []; } if(!historyChatMsgs.length) return; this.setData({ chatMsg: historyChatMsgs.slice(-10), // 跳到最后一条 toView: historyChatMsgs[historyChatMsgs.length - 1].mid, }); wx.setStorageSync("rendered_" + sessionKey, historyChatMsgs); Index = historyChatMsgs.slice(-10).length; wx.pageScrollTo({ scrollTop: 5000, duration: 300, }) this.triggerEvent('render') }, onPullDownRefresh: function () { if (app.globalData.token == null || app.globalData.token == '') { wx.stopPullDownRefresh() return } var that = this; // 下拉获取数据 that.historyMsgs(); }, //获取历史聊天记录 historyMsgs : function () { wx.showToast({ title: '加载中...' , icon: 'loading', duration: 300 }) let me = this let username = this.data.username; let myUsername = wx.getStorageSync("hxName"); let sessionKey = username + myUsername; let historyChatMsgs = wx.getStorageSync("rendered_" + sessionKey) || []; if (Index < historyChatMsgs.length) { let timesMsgList = historyChatMsgs.slice(-Index-10, -Index) this.setData({ chatMsg: timesMsgList.concat(me.data.chatMsg), toView: timesMsgList[timesMsgList.length - 1].mid, }); Index += timesMsgList.length; if (timesMsgList.length == 10) { page ++ } wx.stopPullDownRefresh() } }, onRender(){ wx.pageScrollTo({ scrollTop: 50000, duration: 300, success: function(){console.log('滚动成功')}, fail: function(){console.log('滚动失败')} }) }, previewImage(event){ var url = event.target.dataset.url; wx.previewImage({ urls: [url] // 需要预览的图片 http 链接列表 }); }, sendImage(){ var me = this; wx.chooseImage({ count: 1, sizeType: ["original", "compressed"], sourceType: ["album"], success(res){ me.upLoadImage(res); }, }); }, openCamera(){ var me = this; wx.chooseImage({ count: 1, sizeType: ["original", "compressed"], sourceType: ["camera"], success(res){ me.upLoadImage(res); } }); }, upLoadImage(res){ var me = this; var tempFilePaths = res.tempFilePaths; var token = WebIM.conn.context.accessToken wx.getImageInfo({ src: res.tempFilePaths[0], success(res){ var allowType = { jpg: true, gif: true, png: true, bmp: true }; var str = WebIM.config.appkey.split("#"); var width = res.width; var height = res.height; var index = res.path.lastIndexOf("."); var filetype = (~index && res.path.slice(index + 1)) || ""; if(filetype.toLowerCase() in allowType){ wx.uploadFile({ url: "https://a1.easemob.com/" + str[0] + "/" + str[1] + "/chatfiles", filePath: tempFilePaths[0], name: "file", header: { "Content-Type": "multipart/form-data", Authorization: "Bearer " + token }, success(res){ if(res.statusCode === 400){ // 图片上传阿里云检验不合法 var errData = JSON.parse(res.data); if (errData.error === 'content improper') { wx.showToast({ title: '图片不合法' }); return false } } var data = res.data; var dataObj = JSON.parse(data); var id = WebIM.conn.getUniqueId(); // 生成本地消息 id var msg = new WebIM.message('img', id); var myName = wx.getStorageSync('hxName') var file = { type: 'img', size: { width: width, height: height }, url: dataObj.uri + "/" + dataObj.entities[0].uuid, filetype: filetype, filename: tempFilePaths[0] }; msg.set({ apiUrl: WebIM.config.apiURL, body: file, from: myName, to: me.data.username, ext:{ serviceId:me.data.serviceId }, roomType: false, chatType: 'chatRoom', success: function (argument) { disp.fire('em.chat.sendSuccess', id); } }); msg.body.group = 'groupchat'; WebIM.conn.send(msg.body); if(msg){ var time = WebIM.time(); var msgData = { info: { to: msg.body.to }, username: myName, yourname: msg.body.to, msg: { type: msg.type, data: msg.body.body.url, url:msg.body.body.url, size: { width: msg.body.body.size.width, height: msg.body.body.size.height, } }, style: 'self', time: time, mid: msg.id } } me.data.chatMsg.push(msgData) var sessionKey = me.data.username + myName; var historyChatMsgs = wx.getStorageSync("rendered_" + sessionKey) || []; historyChatMsgs.push(msgData); wx.vibrateLong({ success:function() { console.log('震动调取成功') }, }) wx.setStorage({ key: "rendered_" + me.data.username + myName, data: historyChatMsgs, success: function () { console.log('success发送图片', me.data) me.setData({ chatMsg: me.data.chatMsg, }) me.onRender(); setTimeout(function () { me.setData({ toView: me.data.chatMsg[me.data.chatMsg.length - 1].mid }) }, 100) } }) } }); } } }); }, // 录音开始 showRecordingBtn(){ this.setData({ isShowRecordingBtn:!this.data.isShowRecordingBtn }) }, handleRecordingMove(e){ var touches = e.touches[0]; var changedTouches = this.data.changedTouches; if(!changedTouches){ return; } if(this.data.recordStatus == RecordStatus.SWIPE){ if(changedTouches.pageY - touches.pageY < 20){ this.setData({ recordStatus: RecordStatus.HOLD }); } } if(this.data.recordStatus == RecordStatus.HOLD){ if(changedTouches.pageY - touches.pageY > 20){ this.setData({ recordStatus: RecordStatus.SWIPE }); } } }, handleRecording(e){ let me = this; wx.vibrateShort({ success:function() { console.log('震动调取成功') }, }) me.setData({ recordClicked: true }) setTimeout(() => { if (me.data.recordClicked == true) { executeRecord() } }, 350) function executeRecord(){ wx.getSetting({ success: (res) => { let recordAuth = res.authSetting['scope.record'] if (recordAuth == false) { //已申请过授权,但是用户拒绝 wx.openSetting({ success: function (res) { let recordAuth = res.authSetting['scope.record'] if (recordAuth == true) { wx.showToast({ title: "授权成功", icon: "success" }) } else { wx.showToast({ title: "请授权录音", icon: "none" }) } me.setData({ isLongPress: false }) } }) } else if (recordAuth == true) { // 用户已经同意授权 startRecord() } else { // 第一次进来,未发起授权 wx.authorize({ scope: 'scope.record', success: () => {//授权成功 wx.showToast({ title: "授权成功", icon: "success" }) } }) } }, fail: function () { wx.showToast({ title: "鉴权失败,请重试", icon: "none" }) } }) } function startRecord(){ me.data.changedTouches = e.touches[0]; me.setData({ recordStatus: RecordStatus.HOLD }); RunAnimation = true; me.myradom(); let recorderManager = me.data.recorderManager || wx.getRecorderManager(); recorderManager.onStart(() => { // console.log("开始录音..."); }); recorderManager.start({ format: "mp3" }); // 超时 setTimeout(function(){ me.handleRecordingCancel(); RunAnimation = false }, 100000); } }, handleRecordingCancel(){ RunAnimation = false let recorderManager = this.data.recorderManager; // 向上滑动状态停止:取消录音发放 if(this.data.recordStatus == RecordStatus.SWIPE){ this.setData({ recordStatus: RecordStatus.RELEASE }); } else{ this.setData({ recordStatus: RecordStatus.HIDE, recordClicked: false }); } recorderManager.onStop((res) => { console.log("结束录音...", res); if(this.data.recordStatus == RecordStatus.RELEASE){ console.log("user canceled"); this.setData({ recordStatus: RecordStatus.HIDE }); return; } if (res.duration < 1000) { wx.showToast({ title: "录音时间太短", icon: "none" }) } else { // 上传 this.uploadRecord(res.tempFilePath, res.duration); } }); // 停止录音 recorderManager.stop(); }, uploadRecord(tempFilePath, dur){ var str = WebIM.config.appkey.split("#"); var me = this; var token = WebIM.conn.context.accessToken; var myName = wx.getStorageSync('hxName') wx.uploadFile({ url: "https://a1.easemob.com/" + str[0] + "/" + str[1] + "/chatfiles", filePath: tempFilePath, name: "file", header: { "Content-Type": "multipart/form-data", Authorization: "Bearer " + token }, success(res){ // 发送 xmpp 消息 var id = WebIM.conn.getUniqueId(); var msg = new WebIM.message(msgType.AUDIO, id); var dataObj = JSON.parse(res.data); msg.from = myName; // 接收消息对象 msg.set({ apiUrl: WebIM.config.apiURL, accessToken: token, body: { type: msgType.AUDIO, url: dataObj.uri + "/" + dataObj.entities[0].uuid, filetype: "", filename: tempFilePath, accessToken: token, length: Math.ceil(dur / 1000) }, from: myName, ext:{ serviceId:me.data.serviceId }, to: me.data.username, roomType: false, chatType: 'chatRoom', success: function (argument) { disp.fire('em.chat.sendSuccess', id); } }); var msglength = Math.ceil(dur / 1000); //console.log('发送的语音消息', msg.body) msg.body.group = 'groupchat'; WebIM.conn.send(msg.body); if(msg){ var time = WebIM.time(); var msgData = { info: { from: msg.from, to: msg.to }, username: msg.from, yourname: msg.from, msg: { type: 'audio', data: msg.body.body.url, url: msg.body.body.url, token:token, length:msglength, }, style: 'self', time: time, mid: 'audio' + msg.id } me.data.chatMsg.push(msgData) var sessionKey = me.data.username + myName; var historyChatMsgs = wx.getStorageSync("rendered_" + sessionKey) || []; historyChatMsgs.push(msgData); console.log(historyChatMsgs) wx.vibrateLong({ success:function() { console.log('震动调取成功') }, }) wx.setStorage({ key: "rendered_" + me.data.username + myName, data: historyChatMsgs, success: function () { console.log('success发送图片', me.data) me.setData({ chatMsg: me.data.chatMsg, }) me.onRender(); setTimeout(function () { me.setData({ toView: me.data.chatMsg[me.data.chatMsg.length - 1].mid }) }, 100) } }) } } }); }, myradom(){ const that = this; var _radomheight = that.data.radomheight; for (var i = 0; i < that.data.radomheight.length; i++) { //+1是为了避免为0 _radomheight[i] = (100 * Math.random().toFixed(2))+10; } that.setData({ radomheight: _radomheight }); if (RunAnimation) { setTimeout(function () {that.myradom(); }, 300); }else{ return } } })