12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015 |
- 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 += '<img class="l-previmg" style="display: none;" data-code="'+ v.id +'" data-preview-src="'+ v.content +'" data-preview-group="1">';
- });
- $('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.timestamp<ls[0].timestamp) ))
- firstMsg = ls[0];
- // addMsgToCache(ls);
- showMsg(msg.concat(ls), false, true, false, true);
- }, function(res){
- console.error("e:"+JSON.stringify(res))
- })
-
- }, lastTimestamp);
-
- }
- })
- }
- }
- /**
- * 定位图片位置
- * @param {Object} id
- */
- function locationImg(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.timestamp<ls[0].timestamp) ))
- firstMsg = ls[0];
- addMsgToCache(ls);
- showMsg(msg.concat(ls), false, true, false, true);
- }, function(res){
- console.error("e:"+JSON.stringify(res))
- })
-
- }, lastTimestamp);
-
- }
- })
- }
- }
-
- /**
- * 设置获取到的最后一条消息
- */
- function setLastMsg(msg){
- if(!lastTimestamp || lastTimestamp>msg.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 += '<div class="time-tips"><div>'+ contentMsg +' </div></div>';
- }
-
- continue;
- } else if(typeMsg == 5){
- var con = JSON.parse(msg.content);
- if(msg.sender_id == docInfo.code){
- console.log(msg.content)
- html += '<div class="time-tips"><div>已向'+ con.doctor_name +'医生求助<a data-name="'+ con.doctor_name +'" data-code="'+ con.doctor +'" class="qiuzhu5" href="javascript:void(0)">立即查看</a> </div></div>';
- }
- 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 += '<div class="time-tips"><span>' + time + '</span></div>';
- }
-
- //type:1.文字 2.图片 3.音频
- var temp = '<dl data-type="'+ typeMsg +'" data-code="'+ msg.id +'" class="' + _class.join(" ") + '">'+
- '<dt style="height: auto; text-align: center;"><a><img src="' + doctor_img + '" class="c-images-cycle" /></a></dt>' +
- '<div class="c-content"><span class="c-f12 name">' + doctor_name + '</span>';
- var sendErrDom = "";
- if(!msg.beforeSend && msg.id && msg.id.indexOf('loc')==0){
- sendErrDom = "<i data-info='"+ JSON.stringify(msg) +"' class='c-tips'></i>";
- }
-
- //设置已读标志
- var yiduHtml1 = '<span class="yidu"></span>';
- var yiduHtml2 = '<span class="yidu yidu1"></span>';
- var yiduHtml3 = '<span class="yidu yidu2"></span>';
- 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 = '<span class="yidu">'+ydText+'</span>';//除了视频,文章
- yiduHtml2 = '<span class="yidu yidu1">'+ydText+'</span>';//视频、文章
- yiduHtml3 = '<span class="yidu yidu2">'+ydText+'</span>';//图片
- }
- }
- }else{//团队群聊、求助群聊不显示是否已读
- yiduHtml1 = '';
- yiduHtml2 = '';
- yiduHtml3 = '';
- }
-
- switch(typeMsg) {
- case 0:
- case 1://普通文本
- case 6://开始咨询文本
- case 8://求助文本
- temp += '<div class="c-msg">'+ sendErrDom + yiduHtml1+'<dd class="word-bread" data-is-doctor="' + sender.is_patient + '" data-type="1"><span>' + matchUrl(contentMsg) + '</span></dd></div>';
- 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 += '<div class="c-msg">'+ sendErrDom + '<dd class="word-bread word-bread-img" data-type="2">'+yiduHtml3+'<img onload="imgLoad(this)" data-src="'+ imgUrl +'" data-code="'+ msg.id +'" data-preview-src="" data-preview-group="1" width="100" height="100" src="'+ imgUrl +'" /></dd></div>';
- $('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 += "<div class='c-msg'>"+ sendErrDom + yiduHtml1+"<dd class='word-bread audio' data-type='3' data-code='"+ msg.id +"' data-audio='" + contentMsg + "' data-loc-audio='" + path +"'>"+
- "<div style='width:"+ (rec.times*1.5+30) +"px' class='soundWav'>" +
- "<span class='soundWavT'>"+(rec? rec.times: "") +"\'\'</span>"+
- "</div>"+
- "</dd></div>";
- }
- break;
- case 4: //文章
- temp += formatJyzd(contentMsg, sendErrDom,yiduHtml2, msg.timestamp);
- // temp += '<dd class="word-bread" data-type="1"><span>' + matchUrl(contentMsg) + '</span></dd>';
- break;
- case 12: //视频
- var videoInfo = msg.content.split(",");
- var shichang = formatSeconds(videoInfo[2]);//时长
- if(docInfo.code != msg.sender_id) {
- temp += '<div class="c-msg"><dd data-content="'+msg.content+'" class="preview-video" data-type="12" data-video="'+getImgUrl(videoInfo[1])+'">'+yiduHtml2+
- '<img class="video-img-left" src="'+getImgUrl(videoInfo[0])+'">'+
- '<img class="bofang-icon-left" src="../images/bofang_icon.png">'+
- '<img class="jianjiao-icon-left" src="../images/zuoshanjiao_bg.png">'+
- '<span class="shichang-time-left">'+shichang+'</span>'+
- '</dd></div>';
- }else{
- temp += '<div class="c-msg"><dd data-content="'+msg.content+'" class="preview-video" data-type="12" data-video="'+getImgUrl(videoInfo[1])+'">'+yiduHtml2+
- '<img class="video-img-right" src="'+getImgUrl(videoInfo[0])+'">'+
- '<img class="bofang-icon-right" src="../images/bofang_icon.png">'+
- '<img class="jianjiao-icon-right" src="../images/youshanjiao_bg.png">'+
- '<span class="shichang-time-right">'+shichang+'</span>'+
- '</dd></div>';
- }
- break;
- }
- html += temp + '</div></dl>';
- }
- 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 = '<img src="'+msg.img+'">';
- }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 = '<img src="'+msg.img+'">';
- }else{ //健康教育
- if(msg.img && msg.img!="null"){
- msg.img = getImgUrl(msg.img);
- imgHtml = '<img src="'+msg.img+'">';
- }
- }
- var temp =
- '<div class="c-msg">'+ sendErrDom +'<dd class="word-bread word-article" data-code="'+ msg.id+'" data-inner-type="'+ msg.type +'" data-type="4" data-time="'+timestamp+'">'
- + yiduHtml
- + '<h4 class="text-ellipsis c-f18">'+ msg.title +'</h4>'
- + '<div class="article-content">'+imgHtml
- + '<div>'+ msg.content+'</div>'
- + '</div>'
- + '</dd></div>';
- 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<list.length; i++){
- tmp = list[i];
-
- tx.executeSql(
- 'INSERT INTO '+ tableName +
- ' (id, sender_id, sender_name, content_type, content, timestamp, local_src) '+
- ' VALUES(?,?,?,?,?,?,?)',
- [
- tmp.id, tmp.sender_id, tmp.sender_name, tmp.content_type,
- tmp.content, tmp.timestamp, tmp.local_src || ""
- ],
- function(tx, rs){
- console.log(rs)
- }, function(tx, rs){
- console.log(rs)
- });
- }
- }, function(rs){
- console.error(JSON.stringify(rs));
- })
- }
- /*
- * 刷新数字角标
- */
- function refreshBadge(){
- var userId = plus.storage.getItem('im_userid');
- imClient.Application.getBadgeNo(userId, function(result) {
- console.log(JSON.stringify(result));
- try {
- if (result && result.badge != null) {
- plus.runtime.setBadgeNumber(result.badge);
- }
- } catch (e) {
-
- }
- });
- }
- /*
- * 附加功能
- */
- $(".tw-add").click(function() {
- $(".tw-add-detail").toggle(200);
- });
- var recordCancel = false;
- var recorder = null;
- var audio_tips = document.getElementById("audio_tips");
- var startTimestamp = null;
- var stopTimestamp = null;
- var stopTimer = null;
- var timer = null;
- var MIN_SOUND_TIME = 800;
- var isEnded = false;
- var ui = {
- body: document.querySelector('body'),
- btnMsgType: document.querySelector('#msg-type'),
- boxMsgText: document.querySelector('#msg-text'),
- boxMsgSound: document.querySelector('#msg-sound'),
- btnMsgImage: document.querySelector('#msg-image'),
- areaMsgList: document.querySelector('#msg-list'),
- boxSoundAlert: document.querySelector('#sound-alert')
- };
- ui.boxMsgSound.addEventListener('hold', function(){
- $(this).addClass('yy-hold');
- $(".audio").removeClass("active");
- recordCancel = false;
- if(stopTimer)clearTimeout(stopTimer);
- audio_tips.innerHTML = "手指上划,取消发送";
- ui.boxSoundAlert.classList.remove('rprogress-sigh');
- setSoundAlertVisable(true);
- recorder = plus.audio.getRecorder();
- if (recorder == null) {
- plus.nativeUI.toast("不能获取录音对象");
- return;
- }
- startTimestamp = (new Date()).getTime();
- timer = setInterval(function(){
- var t = (new Date()).getTime();
- if( Math.round( (t-startTimestamp)/1000 ) >=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 = '<video controls style="display:none;" preload="auto" width="1" height="1" src="'+url+'" ></video>';
- $(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 = '<audio preload="auto" src="'+path+'"></audio>';
- $(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 class="urlMatch" href="javascript:void(0)">'+ a[0] +'</a>';
- var str = "";
- var s = content.split(a[0]);
- // var i = content.indexOf(a[0]);
- for(var i=0; i<s.length; i++){
- if(i==s.length-1)
- str += s[i];
- else
- str += s[i] + ah;
- }
- return str;
- }
- return content;
- }
- $('body').on('tap', '.urlMatch', function(){
- mui.openWindow("../../browser/html/browser.html", "browser", {
- extras: {
- url: $(this).html()
- }
- })
- })
- $('body')
- //隐藏打开的附加功能
- .on('touchstart', '#wrapper1', function(){
- $('.tw-add-detail').hide();
- $ipt_content.blur();
- })
- //点击健康教育文章连接
- .on('tap', '.word-article', function(){
- var type = $(this).attr('data-inner-type');
- var code = $(this).attr('data-code');
- if(type==1){
- mui.openWindow('../../jkjl/html/health-record.html', 'health-record', {
- extras: {
- patientCode: code,
- qyRelation: 0
- }
- });
- }else if(type == 2){
- mui.openWindow('../../hzzd/html/guidance_info.html', 'guidance_info', {
- extras:{
- guideId: code
- }
- })
- } else{
- //判断发送时间是否超过"2017-12-29 00:00:00",超过后发送的文章为新的文章
- var sendTime = $(this).attr("data-time"),
- d = new Date("2017-12-29 00:00:00"),
- dTime = d.getTime();
- if(parseInt(sendTime) < dTime){
- mui.openWindow("../../jkjy/html/article.html", "article", {
- extras: {
- article: code
- }
- })
- }else{
- mui.openWindow("../../jkjy/html/article-info.html", "article", {
- extras: {
- articleId: code
- }
- })
- }
-
- }
-
- })
- //点击预约挂号查看详情
- .on('tap', '.word-bread a[name="guahao"]', function(){
- mui.openWindow("../../wdyy/html/detail-appointment.html", "detail-appointment", {
- extras: {
- dataId: $(this).attr('data-id')
- }
- })
- })
- //添加快捷回复
- function kjhf(){
- openWebview("../../kjhf/html/list.html");
- }
- window.addEventListener('fillText', function(e){
- $(".tw-add-detail").hide();
- var content = e.detail.content;
- $("#input_content").show();
- ui.boxMsgSound.style.display = 'none';
- $(".yy-add").find('img:eq(0)').show().next().hide();
- $("#input_content").text(content);
- showSendBtn(true);
- });
- /**
- * 显示重新发送按钮
- * @param {Object} d 数据
- */
- function showResend(d){
- $('#contain dl[data-code="'+ d.id +'"]').find('.c-msg').prepend("<i data-info='"+ JSON.stringify(d) +"' class='c-tips'></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.timestamp<data[0].timestamp) ))
- firstMsg = data[0];
- getNewMsgHandle( data, isInit );
- }, function(res){
- console.error("e:"+JSON.stringify(res))
- })
- }
- /**
- * 从后台获取最前面的消息
- *
- */
- function getFirstMsgs(){
- getMsgs(1, pageSize, "", "", function(data){
- if(data.length>0 && (!firstMsg || (firstMsg.timestamp<data[0].timestamp) ))
- firstMsg = data[0];
- getNewMsgHandle(data, true );
- }, function(res){
- console.error("e:"+JSON.stringify(res))
- })
-
- }
- /**
- * 获取消息
- */
- function getMsgs(page, size, startMsg, endMsg, sucHandle, errHandle, isoffset){
- imClient.Sessions.getMessagesBySession(sessionId, docInfo.code, page || 1, size || paeSize, startMsg, endMsg,
- function(res){
- sucHandle( parseMsg(res) );
- }, function(res){
- mui.toast("获取消息记录失败!");
- console.error("e:"+JSON.stringify(res))
- }, "", isoffset || (endMsg? 1 : ""))
- }
- /**
- * 创建表结构
- */
- function createTable(callBack){
- tableName = "msgLog_"+ sessionId.replace(/-/g, "_") +"_"+ docInfo.code.replace(/-/g, "_");
- /*sqlite.executeSql("DROP TABLE IF EXISTS "+tableName, [], function(){});
- return;*/
-
- sqlite.executeSql("create table if not exists "+ tableName +
- " (id TEXT UNIQUE, sender_id TEXT, sender_name TEXT, content_type INTEGER, " +
- " content TEXT, timestamp INTEGER, local_src BLOB, seq INTEGER PRIMARY KEY AUTOINCREMENT)", [],
- function(tx, rs){
-
- sqlite.executeSql("select * from "+tableName+" where id not like 'loc%' order by timestamp desc limit 0,1", [],
- function(tx, rs){
- isCached = rs.rows.length>0;
- 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; i<rs.rows.length; i++){
- tmp = rs.rows.item(i);
- data.push( tmp );
- /*if(lastTimestamp>tmp.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; i<rs.rows.length; i++){
- tmp = rs.rows.item(i);
- data.push( tmp );
- /*if(lastTimestamp>tmp.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; i<rs.rows.length; i++){
- data.push( rs.rows.item(i) );
- }
- callBack(tx, data);
- }, function(tx, errmsg){
- mui.toast('获取缓存数据失败!');
- console.log(JSON.stringify(errmsg))
- })
- }
- /**
- * 获取最后一条缓存消息
- * @param {Object} callBack
- * @param {Object} lastTimestamp
- */
- function getLastCacheMsg(callBack, lastTimestamp){
- var sql = 'SELECT * FROM '+ tableName + ' where id not like "loc%" ';
- sql += lastTimestamp? " and timestamp<"+lastTimestamp : "";
- sql += " order by timestamp desc ";
- sqlite.executeSql(sql, [], function(tx, rs){
- var data = [];
- for(var i=0; i<rs.rows.length; i++){
- data.push( rs.rows.item(i) );
- }
- callBack(tx, data);
- }, function(tx, errmsg){
- mui.toast('获取缓存数据失败!');
- console.log(JSON.stringify(errmsg))
- })
- }
- /**
- * 发送消息
- * @param {Object} content
- * @param {Object} type
- * @param {Object} oldId
- */
- function sendMsg(d){
- imClient.Sessions.sendMessage(sessionId, docInfo.code, docInfo.name, d.content, d.content_type,
- function(data) {
- console.log(JSON.stringify(data))
- var msg = data.messages[0];
- if( !firstMsg || firstMsg.timestamp<msg.timestamp )
- firstMsg = msg;
- setLastMsg(msg);
- // updateCacheMsgById(d.id, msg.timestamp, msg.id, msg.content);
- }, function(data){
- if(data.status == 406){
- mui.toast("观察者模式无法进行增删改操作");
- }
- showResend(d);
- console.log("sendFail"+ JSON.stringify(data));
- })
- }
- /**
- * 将字符串转为对象
- * @param {Object} data
- */
- function parseMsg(data){
- var d = [];
- for(var i=0; i<data.length; i++){
- d.push(JSON.parse(data[i]));
- }
- return d;
- }
- /**
- * 更新缓存数据
- * @param {Object} oldId 旧id
- * @param {Object} timestamp 更新时间
- * @param {Object} newId 更新id
- * @param {Object} content 内容
- * @param {Object} localSrc 更新本地路径
- */
- function updateCacheMsgById(oldId, timestamp, newId, content, localSrc){
- var sql = "update "+ tableName +" set ";
- var u = [];
- var p = [];
- if(timestamp){
- u.push(" timestamp=? ");
- p.push(timestamp);
- }
-
- if(newId){
- u.push(" id=? ");
- p.push(newId);
- }
-
- if(localSrc){
- u.push(" local_src=? ");
- p.push(localSrc);
- }
-
- if(content){
- u.push(" content=? ");
- p.push(content);
- }
-
- sql += u.join(",")+ " where id=?";
- p.push(oldId);
- sqlite.executeSql( sql, p, function(tx, rs){
- debugger
- }, function(tx, msg){
- alert("更新缓存失败!")
- console.error(JSON.stringify(msg))
- })
- }
- function imgLoad(img){
- if(img.src.indexOf('data:')==0)
- return;
-
- var canvas = document.createElement('CANVAS'),
- ctx = canvas.getContext('2d'),
- newImg = new Image();
- newImg.src = img.src;
-
- canvas.height = newImg.height;
- canvas.width = newImg.width;
- ctx.drawImage(newImg, 0, 0);
- var src = newImg.src;
- var outputFormat = src.substring(src.lastIndexOf('.')+1);
- outputFormat = outputFormat.toLowerCase()=="jpg"? "jpeg" : outputFormat;
- var dataURL = canvas.toDataURL('image/' + outputFormat);
- // updateCacheMsgById($(img).attr('data-code'), "", "", "", dataURL);
- canvas = null;
- }
- /**
- * 获取消息(下拉刷新)
- */
- function getMsgList(pageIndex, isClear, isPre) {
- getMsgs(pageIndex, pageSize, "", "", function(data){
- showMsg(data, isClear, isPre);
- })
-
- //下面代码缓存机制有问题
- // getCacheMsg(lastSeq, pageSize, function(tx, list){
- // if(list.length<pageSize){
- // getMsgs(1, pageSize-list.length, lastId, "", function(data){
- // if(data.length>0){
- // 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)
- }
- });
- }
-
- }
|