var winHeight=window.innerHeight;//窗体高度 var winWidth=window.innerWidth;//窗体高度 var self; var docInfo; var teamInfo; var members; //{"37906b9986f211e6b394fa163e424525": {"jobName":"","code":"37906b9986f211e6b394fa163e424525","level":0,"sex":2,"name":"叶亚娟","photo":"","id":3317,"hospital":"3502120800"}} var pageSize = 10; var myScroll; var chatCache = {}; var firstMsg; var offTop = 16, offBot = 52; var winHei; var otherCode, isPatient; var observer = false; var imMsg = ''; var isSend = true; var andriodVideoUrl = "";//andriod录像文件地址 var urlRegex = new RegExp('((https|http|ftp|rtsp|mms)?://)' + '?(([0-9a-zA-Z_!~*\'().&=+$%-]+: )?[0-9a-zA-Z_!~*\'().&=+$%-]+@)?' //ftp的user@ + '(([0-9]{1,3}\\.){3}[0-9]{1,3}' // IP形式的URL- 199.194.52.184 + '|' // 允许IP和DOMAIN(域名) + '([0-9a-zA-Z_!~*\'()-]+\\.)*' // 域名- www. + '([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\\.' // 二级域名 + '(gov|edu|int|com|cn|cx|cn|wang|cc|xin|net|org|top|tech|red|pub|ink|info|xyz|win))' // first level domain- .com or .museum + '(:[0-9]{1,4})?' // 端口- :80 + '((/[0-9a-zA-Z_!~*\'().;?:@&=+$,%#-]+)+/?)?' + '((\\?[0-9a-zA-Z_!~*\'().;:@&=+$,%#-]+)+/?)?'); mui.init({ gestureConfig:{ doubletap: true, longtap: true, hold: true, release: true } }); var UIPasteboard; var AndroidClip; var AndroidContext; var AndroidMain; //开启websql数据库 sqlite.open('MyData','1.0','My Database', 128); var networkStatus = "";//当前网络状态 mui.plusReady(function(){ self = plus.webview.currentWebview(); var opener = self.opener(); if(opener && (opener.id=="jumingim.html" || opener.id=="yishengim.html")){ mui.fire(self.opener(), "xiaoxiUpdate"); } winHei = $('body').height(); self.setStyle({ softinputMode: "adjustResize" }); if(plus.os.name == "Android"){ $(".andriod-video-li").show(); AndroidContext = plus.android.importClass("android.content.Context"); AndroidMain = plus.android.runtimeMainActivity(); AndroidClip = AndroidMain.getSystemService(AndroidContext.CLIPBOARD_SERVICE); } else{ $(".ios-video-li").show(); UIPasteboard = plus.ios.importClass("UIPasteboard"); } //观察者模式隐藏输入框 // var userAgent = JSON.parse(plus.storage.getItem("userAgent")); // if(userAgent.observer == "1"){ // observer = true; // $("#input_div").hide(); // $('#wrapper1').css({top:'16px', bottom: '0px'});//也不能发送指导和教育 // } document.addEventListener("netchange",onNetChange,false); onNetChange(); bindEvents(); }) function onNetChange(){   var nt = plus.networkinfo.getCurrentType();   switch(nt){     case plus.networkinfo.CONNECTION_ETHERNET:     case plus.networkinfo.CONNECTION_WIFI:       networkStatus = "wifi";       break;     case plus.networkinfo.CONNECTION_CELL2G: networkStatus = "2g"; break;      case plus.networkinfo.CONNECTION_CELL3G: networkStatus = "3g"; break;     case plus.networkinfo.CONNECTION_CELL4G: networkStatus = "4g"; break;     default:       mui.toast("当前没有网络");       break;   } } /** * 获取成员信息 */ function getMembers(callBack){ // if(members) { // callBack? callBack() : getNewMsgs(true); // } else { console.log(sessionId) imClient.Sessions.getParticipants(sessionId, function(rs){ members = {}; var patientCode; $.each( rs , function(i, v) { if(v.id!=docInfo.code) otherCode = v.id; if(v.is_patient==1){ isPatient = true; patientCode = v.id; } members[v.id] = { code: v.id, name: v.name, sex: v.sex, photo: v.avatar, role: v.role, is_patient: v.is_patient,//0 医生,1 患者 last_fetch_time:v.last_fetch_time }; }); otherCode = patientCode||otherCode; callBack? callBack() : getFirstMsgs(); // getNewMsgs(true); //读取对话消息, }, function(msg){ console.log("e:"+JSON.stringify(msg)) mui.toast("获取成员列表失败!"); }) // } } /* * 医生缓存信息 姓名和头像 */ function getMineInfo(){ myScroll = $('#contain').lscroll({ type: 2, pullDownMsg1: "下拉加载更多", pullDownMsg2: "松手开始加载", pullDownAction: function(g){ getMsgList(g.options.page, false, true); }, style: "top: "+ offTop +"px; bottom: "+ offBot +"px"}); var infoStr = plus.storage.getItem("docInfo"); if(infoStr) { docInfo = JSON.parse(infoStr); console.log(docInfo.code) docName = docInfo.name; docPhoto = docInfo.photo || (docInfo.sex==1 ? "../../../images/d-male.png" : "../../../images/d-female.png"); } } function getUserId(){ return docInfo.code; } /* * 回复消息 */ function clickReply() { var text = $("#input_content").text().trim(); // $("#input_content").focus() if(text.length == 0) { mui.toast("发送内容不能为空,请重新输入"); return; } $("#input_content").text(""); isSend = false; showSendBtn(false); uploadMsg(1, text); } /** * 插入预浏览图片 * @param {Object} imgs */ function appendPrevImgs(imgs){ if(imgs){ var html = ""; $.each(imgs, function(i, v) { html += ''; }); $('body').prepend(html); } } /** * 获取未读消息成功处理(初始化获取消息) * @param {Object} data */ function getNewMsgHandle(data, isInit) { // debugger console.log("newdata:" + JSON.stringify(data)); if(!isInit){ // addMsgToCache(data, true); showMsg(data, false, false, true); // refreshBadge(); }else { var len = data.length; if(len == 0){ // if(isCached){ // //取缓存数据,并展示信息 // getCacheMsg(undefined, pageSize, function(tx, rs){ // showMsg(rs, false, false, true); // }); // } else { //从服务端加载数据, 并插入缓存, 展示信息 getMsgs(1, pageSize, "", "", function(res){ showMsg(res, false, false, true); // addMsgToCache(res, true); }); // } } else { if(len < pageSize) { // if(isCached){ // addMsgToCache(data, true); // //从缓存中取剩余数据 // getCacheMsg(undefined, pageSize-len, function(tx, rs){ // rs = rs.concat(data); // showMsg(rs, false, false, true); // }) // } else { //从服务端加载剩余数据 getMsgs( 1, pageSize-len, "", data[0].id, function(res){ data = data.concat(res); showMsg(data, false, false, true); // addMsgToCache(data, true); } , null, 1); // } } else { //将消息插入缓存, 并展示信息 // addMsgToCache(data, true); showMsg(data, false, false, true); } // refreshBadge(); } } } /** * 定位聊天记录位置 * @param {Object} id */ function locationLog(id){ var $logdom = $('.chat-log[data-code="'+ id +'"]'); if($logdom.length){ myScroll.scrollToElement( $logdom[0], 0, 0, -20 ); plus.nativeUI.closeWaiting(); } else { getCacheMsgById(id, function(tx, data){ if(data.length>0){ getCacheMsg("", "", function(tx, ls){ showMsg(ls, false, true, false, true); }, data[0].timestamp, true ) } else { getLastCacheMsg(function(tx, msg){ var startmsg = msg.length>0? msg[msg.length-1] : undefined; getMsgs(1, 1000, startmsg? startmsg.id : "", id, function(ls){ if(ls.length>0 && (!firstMsg || (firstMsg.timestamp0){ getCacheMsg("", "", function(tx, ls){ showMsg(ls, false, true, false, true); }, data[0].timestamp, true ) } else { getLastCacheMsg(function(tx, msg){ var startmsg = msg.length>0? msg[msg.length-1] : undefined; getMsgs(1, 1000, startmsg? startmsg.id : "", id, function(ls){ if(ls.length>0 && (!firstMsg || (firstMsg.timestampmsg.timestamp){ lastTimestamp = msg.timestamp; lastSeq = msg.seq; lastId = msg.id.indexOf("loc")==0? lastId : msg.id; } } /** * 显示消息 */ function showMsg(msgList, isClear, isPre, appendImg, scrollToTop) { if(msgList.length == 0) { plus.nativeUI.closeWaiting(); myScroll.refresh(msgList.length==0); return; } var html = ""; var preTime = 0; var typeMsg = 1; var doctor_img ; var doctor_name = ""; var msg; var sender; //设置对方已读标志 var lastFetchTime = members[otherCode]?members[otherCode].last_fetch_time:new Date("1970-01-01");//对聊医生最后读取消息时间或对聊患者最后读取消息时间 for(var i = msgList.length - 1; i >= 0; i--) { msg = msgList[i]; setLastMsg(msg); typeMsg = parseInt(msg.content_type); var contentMsg = msg.content; if(typeMsg == 7 || typeMsg==10 || typeMsg==13 || typeMsg==14){ if(typeMsg == 7 && msg.sender_id == 'system'){ contentMsg = "居民24小时内未回复,系统自动结束咨询"; } if(typeMsg != 14){ //14标记患者进入咨询 html += '
'+ contentMsg +'
'; } continue; } else if(typeMsg == 5){ var con = JSON.parse(msg.content); if(msg.sender_id == docInfo.code){ console.log(msg.content) html += '
已向'+ con.doctor_name +'医生求助立即查看
'; } continue; } sender = members[msg.sender_id]; if(!sender){ sendPostNoAsync("doctor/baseinfo", {code:msg.sender_id}, null, function(res) { if(res.status == 200) { var dtemp = res.data; doctor_name = dtemp.name; doctor_img = getImgUrl(dtemp.photo); members[dtemp.code] = { code: dtemp.code, name: dtemp.name, sex: dtemp.sex, photo: getImgUrl(dtemp.photo), role: 1,//角色不再此讨论组中 is_patient: 0 //不是患者 }; sender = members[msg.sender_id]; } }); }else{ doctor_name = sender.name; // doctor_img = sender.photo ? sender.photo : (sender.avatar || "../../../images/p-default.png"); doctor_img = getImgUrl(sender.photo); } if(msg.sender_id == docInfo.code) { doctor_img = getImgUrl(docInfo.photo); } var _class = ["chat-log"]; if(docInfo.code != msg.sender_id) { _class.push("chat-left"); } else { _class.push("chat-right"); } if(inMoreOpera) _class.push("checkbox");//更多操作模式下 if(msg.timestamp - preTime > 60 * 1000) { preTime = msg.timestamp; var date = new Date(); date.setTime(msg.timestamp); var time = date.format('yyyy-MM-dd hh:mm:ss'); html += '
' + time + '
'; } //type:1.文字 2.图片 3.音频 var temp = '
'+ '
' + '
' + doctor_name + ''; var sendErrDom = ""; if(!msg.beforeSend && msg.id && msg.id.indexOf('loc')==0){ sendErrDom = ""; } //设置已读标志 var yiduHtml1 = ''; var yiduHtml2 = ''; var yiduHtml3 = ''; if(self.id=="p2dzixun" || self.id=="p2p" && !(!msg.beforeSend && msg.id && msg.id.indexOf('loc')==0)){//医生和患者对聊、医生和医生对聊,显示是否已读 //var ydText = "居民已读"; // TODO "居民已读" 临时改为 "已读" var ydText = "已读"; if(!isPatient){//医生对聊 ydText = "已读"; } if (!isSend) { ydText = ''; } if(docInfo.code == msg.sender_id) { if(msg.timestamp<=lastFetchTime){ yiduHtml1 = ''+ydText+'';//除了视频,文章 yiduHtml2 = ''+ydText+'';//视频、文章 yiduHtml3 = ''+ydText+'';//图片 } } }else{//团队群聊、求助群聊不显示是否已读 yiduHtml1 = ''; yiduHtml2 = ''; yiduHtml3 = ''; } switch(typeMsg) { case 0: case 1://普通文本 case 6://开始咨询文本 case 8://求助文本 temp += '
'+ sendErrDom + yiduHtml1+'
' + matchUrl(contentMsg) + '
'; break; case 2://图片 case 9://求助图片 if(msg.local_src=="data:,") contentMsg = msg.content; else if(msg.local_src) contentMsg = msg.local_src.indexOf('data:')==0? msg.local_src: plus.io.convertLocalFileSystemURL(msg.local_src); else contentMsg = msg.content; var imgUrl = contentMsg; if(imgUrl.indexOf("/storage") > -1){ //本地图片 imgUrl = imgUrl; }else{ imgUrl = getImgUrl(contentMsg); } temp += '
'+ sendErrDom + '
'+yiduHtml3+'
'; $('img.l-previmg[data-code="'+ msg.id +'"]').remove(); break; case 3://语音 var rec = msg.local_src? JSON.parse(msg.local_src) : contentMsg? JSON.parse(contentMsg) : undefined; if(rec){ var path = msg.local_src?msg.local_src:msg.content; temp += "
"+ sendErrDom + yiduHtml1+"
"+ "
" + ""+(rec? rec.times: "") +"\'\'"+ "
"+ "
"; } break; case 4: //文章 temp += formatJyzd(contentMsg, sendErrDom,yiduHtml2, msg.timestamp); // temp += '
' + matchUrl(contentMsg) + '
'; break; case 12: //视频 var videoInfo = msg.content.split(","); var shichang = formatSeconds(videoInfo[2]);//时长 if(docInfo.code != msg.sender_id) { temp += '
'+yiduHtml2+ ''+ ''+ ''+ ''+shichang+''+ '
'; }else{ temp += '
'+yiduHtml2+ ''+ ''+ ''+ ''+shichang+''+ '
'; } break; } html += temp + '
'; } if(isPre) lastId = msgList[msgList.length - 1].id; if(typeMsg != null && typeMsg != 1) { $(".tw-add-detail").hide(200); } if(isClear){ $("#input_content").text(""); showSendBtn(false); $("#contain").html(html); }else{ if(isPre){ $("#contain").prepend(html); if(scrollToTop) myScroll.refreshToTop(); else myScroll.refresh(msgList.length==0); return; } else { $("#contain").append(html); } } isSend = true; myScroll.refreshToEnd(); plus.nativeUI.closeWaiting(); } //毫秒转换成时分秒 function formatSeconds(value) { var theTime = parseInt(value/1000);// 秒 var theTime1 = 0;// 分 var theTime2 = 0;// 小时 if(theTime > 60) { theTime1 = parseInt(theTime/60); theTime = parseInt(theTime%60); if(theTime1 > 60) { theTime2 = parseInt(theTime1/60); theTime1 = parseInt(theTime1%60); } } var result = ""+parseInt(theTime);//秒 if(parseInt(theTime)<=9){ result = "0"+parseInt(theTime);//秒 } if(theTime1 > 0) {//分 if(parseInt(theTime1)>9){ result = ""+parseInt(theTime1)+":"+result; }else{ result = "0"+parseInt(theTime1)+":"+result; } } if(theTime2 > 0) {//小时 if(parseInt(theTime2)>9){ result = ""+parseInt(theTime2)+":"+result; }else{ result = "0"+parseInt(theTime2)+":"+result; } } var resResult = ""; if(result.split(":").length==1){//秒 resResult = "00:"+result; }else if(result.split(":").length==2){//分 resResult = "00:"+result; }else{//时 resResult = result; } return resResult; } function formatJyzd(msg, sendErrDom,yiduHtml, timestamp){ // {"title":"2016年春节放假调休门诊安排通知","id":"ff1b39cfdf6a482c958140ba768474cc","img":"http://f1.yihuimg.com/TFS/upfile/WBJ/111/2016-02-05/160294_1454633481085_fullsize.png","content":"为了您的健康,我给您发送了一篇文章,请咨询查阅,如有问题,可随时与我沟通"} if(msg){ //针对\n,\r等特殊字符,在json转换时会报错 msg = msg.replace(/\n/g, "\\n"); msg = msg.replace(/\r/g, "\\r"); msg = JSON.parse(msg); // msg.img = msg.type==1? "../../../images/jkjl_share.png" : msg.img; var imgHtml = ''; if(msg.type == 1){ //健康记录 msg.img = "../../../images/jkjl_share.png"; imgHtml = ''; }else if(msg.type == 2){ //健康指导 var img = msg.img.split(","); if(img[0] && img[0] != "null"){ msg.img = getImgUrl(img[0]); }else{ msg.img = "../../../images/default_share_blue.png"; } imgHtml = ''; }else{ //健康教育 if(msg.img && msg.img!="null"){ msg.img = getImgUrl(msg.img); imgHtml = ''; } } var temp = '
'+ sendErrDom +'
' + yiduHtml + '

'+ msg.title +'

' + '
'+imgHtml + '
'+ msg.content+'
' + '
' + '
'; return temp; } return ""; } /** * 缓存消息 * @param {Object} data */ function addMsgToCache(list, appendImg) { // id TEXT, sender_id TEXT, sender_name TEXT, content_type TEXT, // content TEXT, timestamp TEXT, local_src TEXT, seq isCached = true; var tmp ; sqlite.db.transaction(function(tx){ for(var i=0; i=60){ clearInterval(timer); recordEnd(); mui.toast("最多录制60秒"); isEnded = true; } }, 1000) recorder.record({ filename: "_doc/audio/", format: "amr" }, function(path) { if (recordCancel) return; var recTime = Math.round((stopTimestamp - startTimestamp)/1000) ; var p = JSON.stringify(plus.io.convertLocalFileSystemURL( path )); uploadMsg(3, "", {path: path, times: recTime>60? 60 : recTime}, true, function(data){ uploadImg(data) }); }, function(e) { plus.nativeUI.toast("录音时出现异常: " + e.message); }); }) function recordEnd(event) { if(isEnded){ isEnded = false; return; } clearInterval(timer); $(ui.boxMsgSound).removeClass('yy-hold'); if (audio_tips.classList.contains("cancel")) { audio_tips.classList.remove("cancel"); audio_tips.innerHTML = "手指上划,取消发送"; } stopTimestamp = (new Date()).getTime(); if (stopTimestamp - startTimestamp < MIN_SOUND_TIME) { audio_tips.innerHTML = "录音时间太短"; ui.boxSoundAlert.classList.add('rprogress-sigh'); recordCancel = true; stopTimer=setTimeout(function(){ setSoundAlertVisable(false); },800); }else{ setSoundAlertVisable(false); } recorder.stop(); } ui.boxMsgSound.addEventListener('release', recordEnd, false); ui.body.addEventListener('drag', function(event) { if (Math.abs(event.detail.deltaY) > 50) { if (!recordCancel) { recordCancel = true; if (!audio_tips.classList.contains("cancel")) { audio_tips.classList.add("cancel"); } audio_tips.innerHTML = "松开手指,取消发送"; } } else { if (recordCancel) { recordCancel = false; if (audio_tips.classList.contains("cancel")) { audio_tips.classList.remove("cancel"); } audio_tips.innerHTML = "手指上划,取消发送"; } } }, false); var setSoundAlertVisable=function(show){ if(show){ ui.boxSoundAlert.style.display = 'block'; ui.boxSoundAlert.style.opacity = 1; }else{ ui.boxSoundAlert.style.opacity = 0; //fadeOut 完成再真正隐藏 setTimeout(function(){ ui.boxSoundAlert.style.display = 'none'; },200); } }; $(".yy-add").click(function() { if($('#msg-sound:visible').length){ $ipt_content.show(); ui.boxMsgSound.style.display = 'none'; $(this).find('img:eq(0)').show().next().hide(); } else { $ipt_content.hide(); ui.boxMsgSound.style.display = 'block'; $(this).find('img:eq(0)').hide().next().show(); } }); var inMoreOpera = false; var $logOper = $('.log-oper'); var $curChatLog; $('#contain').on('longtap', '.word-bread[data-type!="4"][data-type!="3"],.preview-video[data-type="12"]', function(e){ //弹出操作菜单 复制、转发、更多 if(!inMoreOpera){ var w = 264;//264 if($(this).attr('data-type') != 1){ w = 114; $logOper.find('.fz').hide(); $logOper.find('.kjhf').hide(); } else { $logOper.find('.fz').show(); $logOper.find('.kjhf').show(); } if ($(this).attr('data-type') == 1 && $(this).attr('data-is-doctor') == 0) { w = 378; imMsg = $(this).find('span').html(); $('.zdmb').show(); } else { $('.zdmb').hide(); } // alert(w); var sx = e.originalEvent.detail.touches[0].screenX; var left = 0; if(sx-(w/2)<0){ left = 0; } else if(sx+(w/2)>winWidth) { left = winWidth - w; } else { left = sx - (w/2); } var top = e.originalEvent.detail.touches[0].screenY - 56; $logOper.find('div').css('left', (sx-left)+ 'px'); $logOper.css({'top': top +'px', 'left': left + 'px', 'display': '-webkit-box'}); $curChatLog = $(this).parent().parent(); if (w == 378) { var wW = $(window).width(), c = wW - w, ol = $logOper[0].offsetLeft; if ((ol + w) > wW) { left = c; $logOper.css({'top': top +'px', 'left': left + 'px', 'display': '-webkit-box'}); } } return false; } }).on('tap', '.chat-log', function(){ //选择聊天记录 if(inMoreOpera){ $(this).toggleClass('checked'); return false; } }).on('tap', '.c-tips', function(){ var tips = $(this); if(tips.length==0) return false; dialog({ content:'重发该消息?', okValue:'重发', ok: function() { var data = JSON.parse(tips.attr('data-info')); if(data.content_type==2){ uploadImg(data); } else if(data.content_type==3){ } else { sendMsg(data); } tips.remove(); }, cancelValue: '取消', cancel: function () { return; } }).showModal(); return false; }).on('tap', '.word-bread[data-type="3"]', function(){ $('#contain').find('.word-bread[data-type="3"]').removeClass("active"); var $dom = $(this); var loc = $(this).attr('data-loc-audio'); $dom.addClass('active'); if(!loc){ var ser = $(this).attr('data-audio'); if(ser){ ser = JSON.parse(ser); //下载 var path = "_doc/audio/"+new Date().getTime()+".wav"; var dtask = plus.downloader.createDownload( ser.path, { filename: path }, function ( d, status ) { if ( status == 200 ) { //更新数据,播放语音 playRecord(path, $dom); } else { $dom.removeClass('active'); mui.toast("下载语音失败!"); } }); dtask.start(); } else{ $dom.removeClass('active'); mui.toast("语音数据丢失!"); } } else { loc = JSON.parse(loc); var filename = "_doc/audio/", path = ""; if(loc.path.indexOf(filename) > -1){ path = loc.path; }else{ path = getImgUrl(loc.path); } //播放语音 playRecord(path, $dom); } }).on('tap', '.preview-video[data-type="12"]', function(){//播放视频 var url = $(this).attr('data-video'); if(plus.os.name=="iOS"){//ios $(document.body).find('video').remove(); var html = ''; $(document.body).append(html); var video = $(document.body).find('video')[0]; video.play(); }else{//andriod var Intent = plus.android.importClass("android.content.Intent"); var Uri = plus.android.importClass("android.net.Uri"); var main = plus.android.runtimeMainActivity(); var intent=new Intent(Intent.ACTION_VIEW); var uri=Uri.parse(url); intent.setDataAndType(uri,"video/*"); main.startActivity(intent); } }) var player; var $playDom = false; function playRecord(path, dom){ var isPlayBenDi = path.indexOf('.amr')>=0; if($playDom){ if(player){ if(plus.os.name=="iOS" && !isPlayBenDi){//ios player.pause(); }else{ player.stop(); } $playDom.removeClass('active'); if($playDom.attr('data-code') == dom.attr('data-code')){ $playDom = false; return; } } } $playDom = dom; if(plus.os.name=="iOS" && !isPlayBenDi){//ios $(document.body).find('audio').remove(); var html = ''; $(document.body).append(html); player = $(document.body).find('audio')[0]; player.play(); player.addEventListener('ended', function () { $playDom.removeClass('active'); $playDom = false; }, false); }else{//andriod player = plus.audio.createPlayer(path); player.play(function() { $playDom.removeClass('active'); $playDom = false; }, function(e) { $playDom.removeClass('active'); $playDom = false; }); } } /** * 批量操作按钮事件 */ $logOper.on('touchstart', '.pl', function(){ inMoreOpera = true; $logOper.hide(); $curChatLog.addClass('checked'); $('.chat-log[data-type!=4][data-type!=3]').addClass('checkbox'); $('#input_div').addClass('c-hide'); $('.footer-bar').removeClass('c-hide'); $('#qun_detail').hide(); $('#cancel').show(); myScroll.refresh(); }) /** * 复制操作按钮事件 */ $logOper.on('touchstart', '.fz', function(){ $logOper.hide(); copy($curChatLog.find('.word-bread span').text(), 1); return false; }) /** * 转发操作按钮事件 */ $logOper.on('touchstart', '.zf', function(){ $logOper.hide(); var type = $curChatLog.find('.word-bread').attr("data-type"); var text = ""; if(type=="1"){//文本 var $d = $curChatLog.find('.word-bread span'); text = $d.text(); }else { if($curChatLog.closest("dl").attr("data-type")=="12"){//视频 text = $curChatLog.find(".c-msg dd").attr("data-content"); type = 12; }else{//图片 var $d = $curChatLog.find('.word-bread img'); text = $d.attr('data-src'); type = 2; } } toZf([{content: text, type: type}]); return false; }) /** * 快捷回复操作按钮事件 */ $logOper.on('touchstart', '.kjhf', function(){ $logOper.hide(); var $d = $curChatLog.find('.word-bread span'); var text = ""; if($d.length > 0){ text = $d.text(); service.replyAdd(text); } return false; }) /** * 添加指导模板操作按钮事件 */ $logOper.on('touchstart', '.zdmb', function(){ $logOper.hide(); dialog({ content: "是否确认将内容添加到指导模板?", okValue: "立即添加", ok: function(){ openWebview('../../hzzd/html/edit_guidance.html',{action: "add",reference: 'zuyuanziliao', pageid:self.id, msg: imMsg}); }, cancelValue: "不了,谢谢", cancel: function(){} }).showModal(); // return false; }) /** * 转发操作按钮事件 */ $('#plzf').on('touchstart', function(){ var msgs = []; var text = ""; var $d; var type; $.each($('.chat-log.checked'), function(i, v) { type = $(v).find('.word-bread').attr("data-type"); if(type=="1"){//文本 $d = $(v).find('.word-bread span'); text = $d.text(); }else { if($(v).attr("data-type")=="12"){//视频 text = $(v).find(".c-msg dd").attr("data-content"); type = 12; }else{ $d = $(v).find('.word-bread img'); text = $d.attr('src'); type = 2; } } msgs.push({content: text, type: type}); }); toZf(msgs); return false; }) /** * 跳转转发界面 * @param {Object} texts */ function toZf(texts){ mui.openWindow({ url: "zhuanfa.html", id: "zhuanfa.html", extras: { imMessages: texts } }) } /** * 复制 * @param {Object} content * @param {Object} type */ function copy(content, type){ if(plus.os.name == "Android"){ if(type == 1) plus.android.invoke(AndroidClip, "setText", content); else{ // ClipData clip = ClipData.newUri(AndroidMain.getContentResolver(), "URI", copyUri); // plus.android.invoke(AndroidClip, "setPrimaryClip", clip); } } else { var generalPasteboard = UIPasteboard.generalPasteboard(); // 设置/获取文本内容: if(type == 1) generalPasteboard.setValueforPasteboardType(content, "public.utf8-plain-text"); else generalPasteboard.setDataforPasteboardType(content, "public.png"); // UIPasteboard.generalPasteboard().setData(fileData, forPasteboardType: "public.png") } } /** * 还原批量操作状态 */ function revertPl(){ if(inMoreOpera){ inMoreOpera = false; $('.chat-log').removeClass('checkbox checked'); $('#input_div').removeClass('c-hide'); $('.footer-bar').addClass('c-hide'); $('#qun_detail').show(); $('#cancel').hide(); myScroll.refresh(); } } /** * 取消按钮事件 */ $('#cancel').on('tap', function(){ revertPl(); }) var touchLogOper = false; // $('.log-oper').on('touchstart', function(){ // touchLogOper = true; // }) /** * 点击任意地方 关闭操作菜单 */ $('body').on('touchstart', function(){ if($('.log-oper:visible').length){ $logOper.hide(); return false; } }) /** * 显示发送按钮的事件 */ var valLen = 0; var $ipt_content = $('#input_content'); $ipt_content.on('input', function(e){ showSendBtn($(this).text()) }) .on('tap', function(){ $(".tw-add-detail").hide(); $ipt_content.focus(); mui.later(scrollToEnd, 300); }) function scrollToEnd(){ if(winHei-$('body').height() > 0){ myScroll.scrollToEnd(500); $ipt_content.focus(); } else { mui.later(scrollToEnd, 100); } } function showSendBtn(isShow){ if(isShow){ $('.tw-add').hide(); $('#reply').fadeIn('fast', 'swing'); } else if(valLen == 1 || isShow==false){ $('#reply').fadeOut('fast', 'swing', function(){ $('.tw-add').show(); }); } valLen = isShow ? isShow.length : 0; } /* * 发送照片 */ function clickGallery() { plus.gallery.pick(function(path) { var lastIdx = path.lastIndexOf("/"), imgName = path; if(lastIdx>-1) { imgName = path.slice(lastIdx+1); } var locSrc= "_doc/chat/gallery/" + imgName; plus.zip.compressImage({ src: path, dst: locSrc, quality: 20, overwrite: true }, function(e) { console.log(e.target) uploadMsg(2, "", locSrc, true, function(data){ uploadImg(data); }); }, function(err) { console.error("压缩失败:" + err.message); }); }, function(err) {}); }; function uploadImg(data){ var task = plus.uploader.createUpload(server + "upload/chat?type="+data.content_type, { method: "post" }, function(t, sta) { if(sta == 200) { var msg = t.responseText; var oImg = JSON.parse(msg); if(oImg.status==200){ var imgUrl = oImg.urls; var re = new RegExp("\\\\", "g"); imgUrl = imgUrl.replace(re, "/"); if(data.content_type==3){ var loc = JSON.parse(data.local_src); data.content = JSON.stringify({path: imgUrl, times: loc.times}); } else { if($("#contain").find("dl:last").attr("data-code").substring(0,3)=="loc"){//上传图片成功后,更新图片url $("#contain").find("dl:last").find("dd img").attr("src",getImgUrl(imgUrl)).attr("data-src",getImgUrl(imgUrl)); } data.content = imgUrl; } sendMsg(data); } else { mui.toast("发送失败,请重试!"); showResend(data); } } else { mui.toast("发送失败,请重试!"); showResend(data); } }); if(data.content_type==3){ var loc = JSON.parse(data.local_src); task.addFile(loc.path, {}); } else { task.addFile(data.local_src, {}); } task.start(); } /* * 拍照 */ function clickCamera() { var cmr = plus.camera.getCamera(); var res = cmr.supportedImageResolutions[0]; var fmt = cmr.supportedImageFormats[0]; cmr.captureImage(function(path) { plus.io.resolveLocalFileSystemURL(path, function(entry) { var localUrl = entry.toLocalURL(); var lastIdx = localUrl.lastIndexOf("/"), imgName = localUrl; if(lastIdx>-1) { imgName = localUrl.slice(lastIdx+1); } var locSrc= "_doc/chat/camera/" + imgName; plus.zip.compressImage({ src: localUrl, dst: locSrc, quality: 20, overwrite: true }, function(e) { uploadMsg(2, "", locSrc, true, function(data){ uploadImg(data); }); }, function(err) { console.log("压缩失败: " + err.message); }); }); }, function(err) { if(err.code==11 && err.message == "null") { plus.nativeUI.toast("您尚未授权拍照权限,无法使用拍照功能。"); } console.error("拍照失败:" + err.message); }, { index: 1 }); }; /** * 更新信息事件 */ window.addEventListener("update", function() { console.log("update"); getNewMsgs(false); }); /** * 后台返回应用时获取消息 */ document.addEventListener("resume", function() { console.log("运行环境从后台切换到前台事件") getNewMsgs(false); connectSocket(); }, false); //运行环境从前台切换到后台事件 document.addEventListener("pause", function() { console.log("运行环境从前台切换到后台事件") logoutSocketConnect(); }, false); /** * 还原转发状态 */ document.addEventListener("revertZf", function() { $logOper.hide(); revertPl(); hideMenu(); prevImage.close(); // getNewMsgs(); }); function backToParent(){ // var old_back = mui.back; mui.back = function() { var wv = self.opener(); if(wv){ mui.fire(wv, "xiaoxiUpdate"); } self.close(); // old_back(); } } function matchUrl(content){ var a = urlRegex.exec(content); if(a){ var ah = ''+ a[0] +''; var str = ""; var s = content.split(a[0]); // var i = content.indexOf(a[0]); for(var i=0; i"); } /** * 创建聊天会话 */ var sessionId; function createSession(type, callBack){ if(self.sessionId){ sessionId = self.sessionId; $('#title').html(self.sessionName); createTable(callBack); } else { if(type==2) imClient.Sessions.createP2pSession(docInfo.code, self.otherCode, self.otherName,function(res){ if(res.status==200){ sessionId = res.data.id; $('#title').html(res.data.name || self.otherName); createTable(callBack); } else { alert("创建聊天会话失败!"); } }, function(res){ alert("创建聊天会话失败!"); console.error("fail:"+JSON.stringify(res)) }) else if(type == 1) createTable(callBack); else if(type==3){ imClient.Sessions.createGroupSession(teamInfo.code, teamInfo.teamName, members, function(res){ if(res.status == 200){ sessionId = res.data.id; $('#title').html(res.data.name || teamInfo.teamName); createTable(callBack); } else alert("创建聊天会话失败!"); }, function(res){ alert("创建聊天会话失败!"); console.error("fail:"+JSON.stringify(res)) }) } } } var tableName = ""; var isCached = false; /** * 获取新消息 * @param {Object} isInit */ function getNewMsgs(isInit){ if(isInit && self.msgId){ //带msgId定位参数的, locationLog(self.msgId); } else getMsgs(1, pageSize, "", firstMsg? firstMsg.id : "", function(data){ if(data.length>0 && (!firstMsg || (firstMsg.timestamp0 && (!firstMsg || (firstMsg.timestamp0; if(!isCached){ sqlite.executeSql("select * from "+tableName+" limit 0,1", [], function(tx, rs){ isCached = rs.rows.length>0; callBack ? callBack() : ""; }, function(tx, rs){ alert("获取聊天缓存失败!"); }) } else { firstMsg = rs.rows.item(0); callBack ? callBack() : ""; } }, function(tx, rs){ console.error(JSON.stringify(rs)) alert("获取聊天缓存失败!"); }) }, function(tx, rs){ console.error(tableName) alert("创建缓存空间失败!"); }) } var lastSeq = 0; var lastTimestamp; /** * 获取缓存消息 * @param {Object} seq * @param {Object} size * @param {Object} callBack * @param {Object} timestamp * @param {Object} isNext */ function getCacheMsg(seq, size, callBack, timestamp, isNext){ var p = []; var sql = 'SELECT * FROM '+ tableName; var where = []; if(seq){ where.push(" seq<>? "); p.push(seq); } if(timestamp){ where.push(" timestamp"+ (isNext? ">=" : "<") +"? "); p.push(timestamp); } sql += where.length>0? " where "+ where.join(" and ") : ""; sql += " order by timestamp desc "; sql += size? " limit 0,"+size : ""; sqlite.executeSql(sql, p, function(tx, rs){ var data = []; var tmp; for(var i=0; itmp.timestamp){ lastTimestamp = tmp.timestamp; lastSeq = tmp.seq; lastId = tmp.id.indexOf("loc")==0? lastId : tmp.id; }*/ } callBack(tx, data); }, function(tx, errmsg){ mui.toast('获取缓存数据失败!'); console.log(JSON.stringify(errmsg)) }) } /** * 获取缓存消息 * @param {Object} startTime * @param {Object} endTime * @param {Object} callBack */ function getCacheMsgByRange(startTime, endTime, callBack){ var p = []; var sql = 'SELECT * FROM '+ tableName +' where timestamp>='+ startTime +' and timestamp<'+ endTime; sql += " order by timestamp desc "; sqlite.executeSql(sql, p, function(tx, rs){ var data = []; var tmp; for(var i=0; itmp.timestamp){ lastTimestamp = tmp.timestamp; lastSeq = tmp.seq; lastId = tmp.id.indexOf("loc")==0? lastId : tmp.id; }*/ } callBack(tx, data); }, function(tx, errmsg){ mui.toast('获取缓存数据失败!'); console.log(JSON.stringify(errmsg)) }) } /** * 获取缓存消息 * @param {Object} id * @param {Object} callBack */ function getCacheMsgById(id, callBack){ var sql = 'SELECT * FROM '+ tableName + ' where id=?'; sqlite.executeSql(sql, [id], function(tx, rs){ var data = []; for(var i=0; i0){ // addMsgToCache(data); // } // showMsg(list.concat(data), isClear, isPre); // }) // } else { // showMsg(list, isClear, isPre); // } // }, lastTimestamp); } function uploadMsgBase(type, content, locSrc, isNotSend, callBack){ var tim = new Date().getTime(); var id = "loc"+tim; locSrc = type==3? JSON.stringify(locSrc): locSrc; var d = [{ "sender_id": docInfo.code,"sender_name": docInfo.name, "content_type": type, "content": content, "timestamp": tim,"id": id, local_src: locSrc, beforeSend: true}] showMsg(d, false, false, true); // addMsgToCache(d, true); isNotSend? "" : sendMsg(d[0]); if (callBack) callBack(d[0]); // return d[0]; } //录像 function clickVideo(){ if(plus.os.name == "Android"){ plus.nativeUI.toast("请录制10秒左右的短视频,以防录制完成后无法发送",{duration:"long"}); var File = plus.android.importClass("java.io.File"); var MediaStore = plus.android.importClass("android.provider.MediaStore"); var Intent = plus.android.importClass("android.content.Intent"); var intent = new Intent("android.media.action.VIDEO_CAPTURE"); var outPutPath = plus.io.convertLocalFileSystemURL("http://localhost:13131/_doc/camera/test.mp4"); var Uri = plus.android.importClass("android.net.Uri"); var file = new File(outPutPath); var outPutUri = Uri.fromFile(file); intent.putExtra("android.intent.extra.videoQuality", 1);//0 最低质量, 1高质量 intent.putExtra("android.provider.MediaStore.EXTRA_OUTPUT", outPutUri);//录像输出位置 // intent.putExtra("android.intent.extra.durationLimit", 10);//控制录制时间单位秒 var main = plus.android.runtimeMainActivity(); main.startActivityForResult(intent,200); main.onActivityResult = function(request, code, data) { var context = main; plus.android.importClass(data); var contactData = data.getData(); var resolver = context.getContentResolver(); plus.android.importClass(resolver); var cursor = resolver.query(contactData, null, null, null, null); plus.android.importClass(cursor); cursor.moveToFirst(); var column = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA); //获取录制的视频路径 andriodVideoUrl = cursor.getString(column); //解析视频文件的属性 plus.io.resolveLocalFileSystemURL(andriodVideoUrl,function( entry ) { // 可通过entry对象操作test.html文件 entry.file( function(file){ console.log("size=="+file.size+" name=="+file.name); var fileSize = (file.size/1024/1024).toFixed(2);//字节转换成M fileSizeJudge(fileSize);//文件大小判断 } ); }, function ( e ) { plus.nativeUI.toast( "Resolve file URL failed: " + e.message ); }); }; } } function bindEvents(){ //录制视频 $(".lz-video-img").click(function(){ plus.nativeUI.toast("请录制10秒左右的短视频,以防录制完成后无法发送",{duration:"long"}); $("#upload_input").click(); return false; }) //立即发送 $("#lijifasong").on("tap", function(){ uploadVideo(); mui('#sheet1').popover('toggle'); return false; }); //不再提醒 $("#buzaitixing").on("tap", function(){ plus.storage.setItem("isTiXingVideoFaSong","1"); uploadVideo(); mui('#sheet1').popover('toggle'); return false; }); } //ios录像回调事件 function videoFileChange(target) { var fileSize = (target.files[0].size/1024/1024).toFixed(2);//字节转换成M fileSizeJudge(fileSize); } //文件大小判断 function fileSizeJudge(fileSize){ if(parseInt(fileSize)>30){ dialog({ content:'对不起,视频超过30Mb,无法发送,请录制10秒左右的短视频', okValue:'我知道了', ok: function() { return; } }).showModal(); }else{ if(networkStatus=="wifi" || (plus.storage.getItem("isTiXingVideoFaSong") && plus.storage.getItem("isTiXingVideoFaSong")=="1")){//wifi环境或用户点击移动网络弹框中的”不再提醒“按钮 uploadVideo(); }else{ $("#mui-content").html('您正在使用移动网络,继续发送将消耗'+fileSize+'Mb流量,是否继续发送?'); mui('#sheet1').popover('toggle'); } } } //上传视频 function uploadVideo(){ plus.nativeUI.showWaiting(); if(plus.os.name == "Android"){//andriod上传视频 var task = plus.uploader.createUpload(server + "upload/chat?type=4", {method: "post"}, function(t, sta) { if(t.responseText){ var msg = t.responseText; var oImg = JSON.parse(msg); if(oImg.status==200){ uploadMsg(12, oImg.urls); }else if(oImg.status==-1){ mui.toast(oImg.msg); }else{ mui.toast("发送失败,请重试!"); } }else{ mui.toast("发送失败,请重试!"); } plus.nativeUI.closeWaiting(); }); task.addFile(andriodVideoUrl, {}); task.start(); }else{//ios上传视频 var fd=new FormData(); fd.append('file',document.getElementById("upload_input").files[0]); $.ajax(server+"/upload/chat?type=4", { data: fd, contentType: false, cache: false, processData: false, type: 'post', success: function(resData) { if(resData.status==200){ uploadMsg(12, resData.urls); }else if(resData.status==-1){ mui.toast(oImg.msg); }else{ mui.toast("发送失败,请重试!"); } plus.nativeUI.closeWaiting(); }, error:function (XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest.status); console.log(XMLHttpRequest.readyState); console.log(textStatus) } }); } }