Browse Source

开发消息页医生im、我的工作等功能

lulihong 6 years ago
parent
commit
a019f96e02

+ 4 - 4
html/home/html/xiaoxi.html

@ -17,11 +17,11 @@
		<link rel="stylesheet" type="text/css" href="../../../common/css/ss-doctor.css">
		<link rel="stylesheet" type="text/css" href="../css/xiaoxi.css">
		<style>
			.c-list .c-list-info > p{
			..c-list .c-list-info > p{
				font-size: 16px!important;
			}
			.f-dn{display: none;}
			.div-group-btn{position: absolute;top: 50%;left: 50%;margin-top: -15px;margin-left: -85px;width: 170px;height: 30px;line-height: 30px;border-radius: 10px;background: #039BDC;}
			.div-group-btn{position: absolute;top: 50%;left: 50%;margin-top: -15px;margin-left: -127px;width: 255px;height: 30px;line-height: 30px;border-radius: 10px;background: #039BDC;}
			.div-group-btn .div-item{width: 85px;float: left;position: relative;height: 30px;}
			.div-group-btn .div-item.active{background: #fff;border-radius: 10px;}
			.div-group-btn .div-item .div-image{width:15px;height: 15px;background-size: 15px;margin-top: 8px;margin-right: 5px;position: absolute;left: 20px;}
@ -55,11 +55,11 @@
							<span class="div-red-dian f-dn"></span>
						</div>
						
						<!--<div class="div-item" data-type="3">
						<div class="div-item" data-type="3">
							<div class="div-image yisheng-img"></div>
							<span class="div-title">医生</span> 
							<span class="div-red-dian f-dn"></span>
						</div>-->
						</div>
					</div>
					
				</div>

+ 1 - 1
html/home/js/sousuoyisheng.js

@ -437,7 +437,7 @@ bindEvents = function () {
			type = $this.attr('data-type');
		
			if(type=="yisheng"){//医生和医生间会话
				openWebview("../../message/html/p2p.html",{sessionId: code, sessionName: name});
				openWebview("../../message/html/p2p.html",{sessionId: code, sessionName: name, type:"doctor-to-doctor"});
			}else if(type=="sessions"){//团队群聊
				openWebview("../../message/html/tuanduiqunliao.html",{sessionId: code, sessionName: name});
			}

+ 1 - 1
html/home/js/yishengim.js

@ -391,7 +391,7 @@ bindEvents = function () {
		name = $this.attr('data-name'),
		type = $this.attr('data-type');
		if(type==2){//医生对医生1对1
			openWebview("../../message/html/p2p.html",{sessionId: code, sessionName: name});
			openWebview("../../message/html/p2p.html",{sessionId: code, sessionName: name, type:"doctor-to-doctor"});
		}else{
			openWebview("../../message/html/tuanduiqunliao.html",{sessionId: code, sessionName: name});
		}

+ 2015 - 0
html/message/js/chatRoom.js

@ -0,0 +1,2015 @@
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: 'mine', 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)
	            }
		});
	}
	
}

+ 9 - 9
html/message/js/p2p.js

@ -49,13 +49,13 @@
			}
			
			mui.back = function(){
				if(docInfo.level == 1){
					mui.fire(plus.webview.getWebviewById("home1.html"), "refresh");;
				} else {
					var mainWebview = plus.webview.getWebviewById("main");
					mui.fire(mainWebview,"activeXiaoxi");
					mainWebview.show();
				}
//				if(docInfo.level == 1){
//					mui.fire(plus.webview.getWebviewById("home1.html"), "refresh");;
//				} else {
//					var mainWebview = plus.webview.getWebviewById("main");
//					mui.fire(mainWebview,"activeXiaoxi");
//					mainWebview.show();
//				}
				
				mui.later(function(){
					closeOpener(self.opener());
@ -82,8 +82,8 @@
	function initPage(data){
		consultData = data;
		if(consultData.isCommonTeam){
			//同一团队内的,正常聊天
		if(self.type=="doctor-to-doctor"){
			//医生间,正常聊天
			
		} else if(consultData.consult){
			//存在未结束的咨询

+ 11 - 11
html/mine/html/zuyuanziliao.html

@ -173,17 +173,17 @@
			})
			
			$('.send-c').on('tap', function(){
				openWebview("../../message/html/p2p.html",{sessionId: "", sessionName: docName,otherCode:docCode,otherName: docName});
//				mui.openWindow({ 
//					id: "p2p",
//					url: "../../message/html/p2p.html",
//					extras: {
//						otherCode: docCode,
//						otherName: docName,
//						otherPhoto: docInfo.photo,
//						otherSex: docInfo.sex
//					}
//				})
				mui.openWindow({ 
					id: "p2p",
					url: "../../message/html/p2p.html",
					extras: {
						type:"doctor-to-doctor",
						otherCode: docCode,
						otherName: docName,
						otherPhoto: docInfo.photo,
						otherSex: docInfo.sex
					}
				})
			})
		</script>
	</body>

File diff suppressed because it is too large
+ 118 - 0
html/tuandui/css/search-bar.css


+ 127 - 0
html/tuandui/css/searchdoctor.css

@ -0,0 +1,127 @@
.searchbar { border-bottom: 1px solid #CCC; }
#search_suggest_text { position: absolute; top: 50px; left: 8px; color: #17b3ec; font-size: 18px;z-index: 10;}
.locate-city { background-color: #F2F3F5; }
.locate-city img { width: 15px; height: 20px; }
.list-wrap { border-top: 1px solid #CCC; /*background-color: #FFF;*/ }
.more-result { display: block; height: 35px; line-height: 35px; margin-left: -10px; border-top: 1px solid #E7E7E7; border-bottom: 1px solid #E7E7E7; }
.more-result>span { position: relative; color: #666; }
.more-result .fa-angle-right { position: absolute; top: -3px; right: -10px;font-size: 22px; }
.search-target-text em { font-weight: bold; color: #75BF00; }
.scroll-wrapper { top: 0px; }
#search_suggest_text { left: 0; width: 100%; padding-left: 8px; box-sizing: border-box; }
.no-result-img { display: block; width: 320px; height: 184px; margin: 0 auto; margin-top: 160px; }
.j-text-ellipsis em { font-weight: bold; color: #23AFFF; }
#jumin_wrapper .c-list > li { margin-left: 0; }
.l-sanshi-ico { width: 150px; }
.lin-search{
	height: 30px;
	padding: 8px 10px;
	background-color: #fff;
}
.lin-search img{
	width: 29px;
}
.lin-search div{
	text-align: center;
	border-radius: 5px;
	line-height: 29px;
	background-color: #f2f4f6;
	color: #999;
}
.lin-search-ipt{
	height: 30px;
	padding: 8px 10px;
	background-color: #17b3ec;
	display: -webkit-box;
}
.lin-search-ipt .div-input{
	border-radius: 5px;
	line-height: 29px;
	background-color: #f2f4f6;
	color: #999;
	text-align: left; 
	-webkit-box-flex: 1;
}
.lin-search-ipt input{
	background-color: #f2f4f6 ;
	border-radius: 5px;
	height: 30px;
	color: #999;
	text-align: left;
	padding-left: 30px;
	background: url(../../../images/sousuo_icon.png) no-repeat;
	background-size: 30px 30px;
	width: 88%;
}
.lin-search-ipt a{
	font-size: 16px;
	display: block;
	width: 32px;
	padding: 4px 6px 4px 12px;
	color: #fff;
}	
.f-fs12{font-size: 12px;}
.search-his .title{
	padding:0 12px;
	height: 44px;
	border-bottom: solid 1px #dcdcdc;
}
.search-his .cler{
	float: right;
	padding: 10px 0;
	color: #999;
	font-size: 16px;
}
.search-his .his{
	float: left;
	padding: 10px 0;
	font-size: 16px;
	font-weight: bold;
	color: #333;
}
.search-his .his-list{
	box-sizing: border-box;
	border-bottom: solid 1px #f1f1f1;
	padding: 10px 12px;
	font-size: 16px;
	color: #333;
	text-overflow: ellipsis;
	overflow: hidden;
	white-space: nowrap;
}
.search-his .his-list:first-child{
	border-top: none;
}
.search-his .his-list:last-child{
	border-bottom: solid 1px #dcdcdc;
}
.his-list-ul{
	background-color: #fff;
}
.arrow-right{position: absolute; top: 50%; right: 10px; margin-top: -5px;}
.lin-search-ipt{height: 50px;padding: 8px 10px;background-color: #17b3ec;display: -webkit-box;border-bottom: 1px solid #dcdcdc;}
.lin-search-ipt .div-input{padding-top: 2px;border-radius: 5px;line-height: 29px;background-color: #f2f4f6;color: #999;text-align: left; -webkit-box-flex: 1;}
.lin-search-ipt input{background-color: #f2f4f6 ;border-radius: 5px;height: 30px;text-align: left;padding-left: 30px;background: url(../../../images/sousuo_icon.png) no-repeat;background-size: 30px 30px;width: 98%;}
.lin-search-ipt input[type=text]{border: none!important;}
.lin-search-ipt a{font-size: 16px;display: block;width: 50px;padding: 4px 4px 4px 0px;color: #fff;text-align: right;}	
.mb-em{color: #909090;font-size: 12px;display: inline-block;margin-left: 6px;}
.mj-flex{display: flex;align-items: center;display: -webkit-flex;-webkit-align-items: center;padding-top: 5px;}
.weixin-icon { width: 20px; height: 17px; margin-top: 0px; margin-right: 5px; }
.xuetang-icon { width: 12px; height: 21px; margin-top: 0px; margin-right: 0px; }
.xueya-icon { width: 15px; height: 18px; margin-top: 0px; margin-right: 5px; }
.mb-icon-round{width: 40px;height: 40px;border-radius: 50%;text-align: center;line-height: 39px;font-size: 16px;}
.mb-icon-round.red{border: solid 1px #FF4c4c;color: #FF4c4c;}
.mb-icon-round.orange{border: solid 1px #FFc691;color: #FFc691;}
.mb-icon-round.green{border: solid 1px #06bf04;color: #06bf04;}
.mb-icon-flex{display: flex;display: -webkit-flex;justify-content: flex-end;-webkit-justify-content: flex-end;align-items: center;-webkit-align-items: center;}
#pati_list li{padding-right: 10px;}
.mb-yu{ width: 36px; height: 18px;margin-left: 5px;}

+ 17 - 0
html/tuandui/css/tuandui.css

@ -376,3 +376,20 @@ ul.doc-list li{
.c-hide{
	display: none;
}
.lin-search{
	padding: 10px 10px 4px 10px;
	background-color: #fff;
}
.lin-search img{
	width: 29px;
}
.lin-search div{
	text-align: center;
	border-radius: 5px;
	line-height: 29px;
	background-color: #f2f4f6;
	color: #999;
}

+ 9 - 9
html/tuandui/html/gongzuobaogao.html

@ -39,7 +39,7 @@
			<li class="gzbg-con">
				<img src="../images/qy.png" alt="" />
				<ul class="ztqk-list">
					<li>签约人数: <span id="qyrs" class="ztqk-font"></span></li>
					<li>关注人: <span id="qyrs" class="ztqk-font"></span></li>
					<li>服务人次: <span id="fwrs" class="ztqk-font"></span></li>
					<li>平均医生评分: <span id="pjmyd" class="ztqk-font pjmyd-con"></span></li>
				</ul>
@ -47,7 +47,7 @@
		</ul>
		
		<!--签约情况-->
		<ul class="gzbg-echarts">
		<!--<ul class="gzbg-echarts">
			<li class="gzbg-tit">
				<i class="gzbg-icon qyqk-icon"></i><span class="qy-lab">签约情况</span>
				<div id="qiehuan" data-type="1"><i class="gzbg-icon qh-icon"></i><span class="qy-qh">切换续约情况</span></div>
@ -55,7 +55,7 @@
			<li class="gzbg-con" style="">
				<div id="qyqkChart" style="height: 148px;width: 100%;"></div>
			</li>
		</ul>
		</ul>-->
		
		<!--咨询统计-->
		<ul class="gzbg-echarts">
@ -95,28 +95,28 @@
		</ul>
		
		<!--长处方统计-->
		<ul class="gzbg-echarts" style="overflow: hidden;">
		<!--<ul class="gzbg-echarts" style="overflow: hidden;">
            <li class="gzbg-tit"><i class="gzbg-icon ccf-icon"></i><span>长处方统计</span></li>
            <li class="gzbg-con">
                <div id="ccfChart" style="height: 250px;width: 100%;"></div>
            </li>
        </ul>
        </ul>-->
        
		<!--续签转签人数-->
		<ul class="gzbg-echarts">
		<!--<ul class="gzbg-echarts">
			<li class="gzbg-tit"><i class="gzbg-icon xqzq-icon"></i><span>续签转签人数</span></li>
			<li class="gzbg-con">
				<div id="xqzqChart" style="height: 148px;width: 100%;"></div>
			</li>
		</ul>
		</ul>-->
		
		<!--平均医生评分-->
		<ul class="gzbg-echarts">
		<!--<ul class="gzbg-echarts">
			<li class="gzbg-tit"><i class="gzbg-icon myd-icon"></i><span>平均医生评分</span></li>
			<li class="gzbg-con">
				<div id="mydChart" style="height: 148px;width: 100%;"></div>
			</li>
		</ul>
		</ul>-->
		
	</body>
	<script src="../../../js/jquery/2.1.3/jquery.js"></script>

+ 88 - 0
html/tuandui/html/searchdoctor.html

@ -0,0 +1,88 @@
<!DOCTYPE html>
<html>
	<head>
		<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<meta charset="utf-8">
		<title>搜索医生</title>
		<link rel="stylesheet" type="text/css" href="../../../css/mui.min.css"/>
		<link rel="stylesheet" type="text/css" href="../../../common/cross/css/cross.css">
		<link rel="stylesheet" href="../../../common/cross/css/cross.ui.css" type="text/css" />
		<link rel="stylesheet" type="text/css" href="../../../common/css/jy-style.css">
		<link rel="stylesheet" href="../css/search-bar.css" type="text/css"/>
		<link rel="stylesheet" href="../css/searchdoctor.css" type="text/css"/>
	</head>
	<body>
		<div class="c-main">
			<section style="position: fixed;top: 0px;left: 0px;width: 100%;z-index: 5;">
				<div class="lin-search-ipt" style="border-bottom: 1px solid #dcdcdc;">
					<div class="div-input">
						<input id="searchPut" placeholder="输入姓名搜索" class="f-fs12"/>
					</div>
					<a href="javascript:;" class="searchbar-cancel">取消</a>
				</div>
				
				<div id="search_suggest_text" class="c-dn"></div>
				
	        </section>
            <div class="search-his c-hide" id="history_search" style="position: absolute;top:45px;z-index:3;width: 100%;">
				<div class="title">
					<div class="his">历史搜索</div>
					<div id="clear_his_data" class="cler">清空</div>
				</div>
				<div id="his_scroll" class="mui-scroll-wrapper" style="top: 44px;">
            		<div class="mui-scroll">
						<ul class="his-list-ul" id="his_sear_list">
							
						</ul>
					</div>
				</div>
            </div>
           
			<div id="search_result" class="c-hide">
				<div id="jumin_wrapper" class="mui-scroll-wrapper" style="top: 50px;">
	                <div class="mui-scroll">
						<ul id="pati_list" class="c-list">
							
						</ul>
					</div>
				</div>
			</div>
			<div id="no_result_wrap" class="c-hide">
				<img class="no-result-img" src="../../../images/shujuweikong_img.png" />
				<div class="f-fs14 c-323232 c-t-center">抱歉,暂未找到符合条件的结果</div>
			</div>
		</div>
		<script type="text/html" id="pati_list_tmpl">
			{{each list as value j}}
			<li class="n-list-link list-arrow-r n-list-cover" data-code="{{value.code}}" data-name="{{value.name}}">
				<div class="patient-face patient-face-new">
					<img src="{{value.photo}}"> 
				</div>
				<div class="n-list-info">
					<h4 class="c-nowrap c-f16 mt5">{{value.name}}
						<em class="mb-em">({{value.deptName}} {{value.jobName}}岁 )</em>
					</h4>
				</div>
			</li>
			{{/each}}
		</script>
		
		<script type="text/html" id="his_list_tmpl">
			{{each list as v}}
				<li class="his-list">{{v}}</li>
			{{/each}}
		</script>
		<script type="text/javascript" src="../../../js/jquery/2.1.3/jquery.js"></script>
		<script type="text/javascript" src="../../../js/mui.min.js"></script>
		<script src="../../../js/es6-promise.js" type="text/javascript" charset="utf-8"></script>
		<script src="../../../js/underscore.js" type="text/javascript" charset="utf-8"></script>
		<script src="../../../js/common_http.js" type="text/javascript" charset="utf-8"></script>
		<script src="../../../js/template.js" type="text/javascript" charset="utf-8"></script>
		<script src="../../js/common.js" type="text/javascript" charset="utf-8"></script>
		<script src="../../../js/app.js" type="text/javascript" charset="utf-8"></script>
		<!--<script src="../../js/android.js" type="text/javascript" charset="utf-8"></script>-->
		<script src="../js/search-bar.js" type="text/javascript" charset="utf-8"></script>
		<script src="../../js/templateHelp.js" type="text/javascript" charset="utf-8"></script>
		<script src="../js/searchdoctor.js" type="text/javascript" charset="utf-8"></script>
	</body>
</html>

+ 4 - 3
html/tuandui/html/tuandui.html

@ -10,7 +10,7 @@
		<link rel="stylesheet" href="../../../common/cross/css/cross.ui.css" type="text/css" />
		<link rel="stylesheet" type="text/css" href="../../../common/css/jy-style.css">
		<link rel="stylesheet" type="text/css" href="../../../css/mui-pull.css"/>
		<link rel="stylesheet" type="text/css" href="../css/huanzhe.css"/>
		<link rel="stylesheet" type="text/css" href="../css/tuandui.css"/>
	</head>
	<body>
@ -41,8 +41,9 @@
            {{each list as val i}}
            <div class="group-item">
                <div class="patient-type">
                	<div class="arrow "> <i class="ui-arrow ui-arrow-r"></i></div>
                    <h3 class="t c-f16">{{i}}</h3>
                    <div class="arrow "> <i class="ui-arrow ui-arrow-b"></i></div>
                    <h3 style="position: absolute;right: 20px;color: #909090;">{{val.length}}人</h3>
                </div>
                <div class="c-hide group-info">
                    <ul class="n-list">
@ -53,7 +54,7 @@
							</div>
							<div class="n-list-info">
								<h4 class="c-nowrap c-f16 mt5">{{value.name}}
									<em class="mb-em">{{value.job_name}}</em>
									<em class="mb-em c-909090">{{value.job_name}}</em>
								</h4>
							</div>
						</li>

File diff suppressed because it is too large
+ 34 - 32
html/tuandui/js/gongzuobaogao.js


+ 21 - 0
html/tuandui/js/search-bar.js

@ -0,0 +1,21 @@
$.fn.searchBar = function() {
	var $input = this.find('input[type=search]'),
	$cancelBtn = this.find('a.searchbar-cancel'),
	$ele = this;
	$input.off('click.searchinput').on('click.searchinput',function() {
		$ele.addClass('searchbar-active');
		$cancelBtn.css({
			display: 'block',
			'margin-right': 0
		});
	});
	$cancelBtn.off('click.searchbtn').on('click.searchbtn',function() {
		$ele.removeClass('searchbar-active');
		$cancelBtn.css({
			'margin-right': (function(){
				return -$cancelBtn[0].offsetWidth + 'px'
			})()
		})
	});
}

+ 378 - 0
html/tuandui/js/searchdoctor.js

@ -0,0 +1,378 @@
	// 基本信息(包括userAgent)
var baseInfo = null,
	// 基础环境信息(包括当前webview)
	baseEnv = null;
	
	// 搜索框
var $searchbar = $('.searchbar'),
	// 搜索输入框
	$searchbarInput = $('.lin-search-ipt input'),
	// 搜索取消按钮
	$searchCancelBtn = $('.searchbar-cancel'),
	// 搜索框下面悬浮的搜索提示
	$searchSuggest = $('#search_suggest_text'),
	// 搜索结果展示容器
	$searchtResult = $('#search_result'),
	// 搜索无结果时显示
	$noResultWrap = $('#no_result_wrap'),
	$patiList = $('#pati_list'),
	// 分页查询最后一页
	$history = $('#history_search'),//历史搜索
	$hisSearList = $('#his_sear_list');
var search_keyword = "", //记录搜索框的内容
	pagesize = 15,
	historyData=[],//历史数据
	historyStr;
var self;
mui.plusReady(function() {
//	initKeyboardAndroid();
	docInfo = JSON.parse(plus.storage.getItem("docInfo"));
	historyStr = plus.storage.getItem("doctorSearchHis"+docInfo.code);
	if(historyStr){
		historyStr = JSON.parse(historyStr).join(',');
		historyData = historyStr.split(',');
	}else{
		historyData = [];
	}
})
window.addEventListener("initSearch", function(e){
//	openSoftKeyboard();
	baseInfo = getBaseInfo();
	$("#searchAll").show();
	setTimeout(function(){
		$("#searchPut").focus();
	},100)
	if(historyData.length){
		$history.show();
	}
})
// 获取登录相关信息
var getBaseInfo = function() {
		// 登录的相关信息
	var userAgent = JSON.parse(plus.storage.getItem("userAgent"))
	return {
		userAgent: userAgent
	}
},
// 获取基础环境信息
getBaseEnvPromise = function () {
	var env = {
		webview: plus.webview.currentWebview()
	}
	return Promise.resolve().then(function(res) {
		return env;
	})
},
historyList = function(){
	historyStr = plus.storage.getItem("doctorSearchHis"+docInfo.code);
	if(historyStr){
		historyStr = JSON.parse(historyStr).join(',');
		historyData = historyStr.split(',');
	}else{
		historyData = [];
	}
	var html = template('his_list_tmpl',{list:historyData});
	$hisSearList.html('');
	$hisSearList.append(html);
},
// 初始化“患者”视图列表
initPatientViewList = function(data,keyword,isAppend) {
	data = _.map(data,function(item){
		item.photo = getImgUrl(item.photo);
		return item;
	})
	var html = template("pati_list_tmpl", {list: data});
	searchText = $searchbarInput.val().trim();
	if(isAppend == true){
		$patiList.append(html)
	}else{
		mui('#jumin_wrapper').pullRefresh().scrollTo(0,0)
		$patiList.empty().append(html)
		mui('#jumin_wrapper').pullRefresh().refresh(true);//重置
	}
	ellipsisText($patiList.find('li'),searchText);
},
// $el: $('.c-content-warp')
getRowProps = function ($el) {
	var $textEllipsis = $el,
		$text = $textEllipsis.eq(0),
		$chart = $text.text('a'),
		enWidth = $chart.width(),
		$chart = $text.text('中'),
		zhWidth = $chart.width(),
		lineHeight = parseFloat($chart.css("lineHeight"), 10),
		rowHeight = $chart.height();
	$chart.text('');
	return {
		chartWidth: {
			zh: zhWidth,
			en: enWidth
		},
		rowHeight: Math.max(rowHeight, lineHeight),
		rowWidth: $el.width()
	};
},
replaceAll = function (text, arr) {
	var html = text;
	_.each(arr,function(kw) {
		var reg = new RegExp(kw+"(?!>)","gi");
		html = html.replace(reg,'<em>'+kw+'</em>');
	});
	return html;
},
highlineKeyword = function ($el,searchText) {
	var props = getRowProps($el),
		chartWidth = props.chartWidth,
		rowHeight = props.rowHeight,
		rowWidth = props.rowWidth,
		// 每行显示字符数(以中文字符为标准计算)
		chartNum = Math.floor(rowWidth / chartWidth.zh),
		// 排除指定数量字符所占宽度
		exceptNum = 0,
		// 行数
		rowNum = 1,
		// 预计显示总字符数
		expectedNum = chartNum * rowNum - exceptNum,
		$target = $el,
		// 目标文本
		text = $.trim($target.attr('data-text')),
		length = text.length,
		// 关键字数组
		kws = $.trim(searchText).replace(/\s+/g," ").split(" ");
	var fidx = 0,preFidx,diff = 0;
	$target.html(replaceAll(text, kws));
	if(Math.floor($target.height() / rowHeight) <= rowNum) {
		return ;
	}
	if(text.length > expectedNum) {
		fidx = text.indexOf(kws[0])+kws[0].length-1;
		diff = fidx - expectedNum + 1;
		preFidx =  fidx;
		diff = (diff<0)?0:diff;
		var preChar = (diff>0)?"...":"";
		$target.html(preChar+replaceAll(text.slice(diff,preFidx+1), kws)+"...");
		while((Math.floor($target.height() / rowHeight) <= rowNum) && (preFidx < length)) {
			preFidx++;
			$target.html(preChar+replaceAll(text.slice(diff,preFidx+1), kws)+"...");
		}
		if(preFidx == length && (Math.floor($target.height() / rowHeight) <= rowNum)) {
			diff = diff>0?(diff - 1):0;
			$target.html(preChar+replaceAll(text.slice(diff,preFidx), kws));
		} else if((Math.floor($target.height() / rowHeight) > rowNum)) {
			$target.html(preChar+replaceAll(text.slice(diff,preFidx), kws)+"...");
		}
	}
},
ellipsisText = function ($elements, searchText) {
	_.each($elements,function(el) {
	    var $textEl = $(el).find(".j-text-ellipsis");
	    _.each($textEl, function(t){
	        highlineKeyword($(t),searchText)
	    })
	});
},
// 控制搜索关键字悬浮提示的显示
showSearchSuggest = function(text) {
	var suggestText = '搜索“'+text+'”';
	// 如果text不为空,则显示;否则隐藏
	if(text&&text.trim().length) {
		$searchSuggest.text(suggestText);
		$searchSuggest.show();
	} else {
		$searchSuggest.text('');
		$searchSuggest.hide();
	}
},
// 分页查询列表
searchByPaging = function (isAppend,fun) {
	$history.hide();
	$("#searchPut").blur();
	search_keyword = $searchbarInput.val();
	if(!$.trim(search_keyword)) {
		return ;
	}
	plus.nativeUI.showWaiting();
	var url = "/doctor/doctor_name_list",
	 params = { query:search_keyword};
	getReqPromise(url,params, "GET").then(function(res){
		console.error(JSON.stringify(res))
 		if(res.status == 200) {
			if(!res.list.length) {
				$searchtResult.hide();
				$noResultWrap.show();
			} else {
				$noResultWrap.hide();
				$searchtResult.show();
				initPatientViewList(res.list,search_keyword,isAppend);
				fun&&fun.call(this,true)
			}
 		}else{
 			mui.toast("搜索失败");
 		}
 		plus.nativeUI.closeWaiting();
	}).catch(function(e) {
		plus.nativeUI.closeWaiting();
		console && console.error(e)
	})
},
// 绑定页面事件
bindEvents = function (){
	mui.init({
		pullRefresh : {
		    container:'#jumin_wrapper',
		    up : {
			    height:50,
			    contentinit: '',
				contentdown: '',
			    contentrefresh : "正在加载...",
			    contentnomore:'没有更多数据了',
			    callback: function() {
			    	var self = this;
			    	page++;
			    	searchByPaging(true,function(value){
			    		setTimeout(function(){
			    			self.endPullupToRefresh(value);
			    		},500)
			    	})
				}
		    }
		}
	})
	
	$('#his_scroll').css({
		'height':$(window).height()-158
	})
	mui('#his_scroll').scroll({
    	bounce: true, //是否启用回弹
   })
	
	$searchbarInput.on('input', function() {
		var text = $(this).val().trim();
		$searchtResult.hide();
		$('#no_result_wrap').hide();
		if(text.length > 0){
		    $("#searchAll").hide();
		    $history.hide();
		}else{
		    $("#searchAll").show();
		    $history.show();
		}
		showSearchSuggest(text);
	}).on('keydown',function(e) {
		if (e.which === 13) {
		    page = 0;
		    $searchSuggest.hide();
			searchByPaging(false);
			//保存历史数据20个
			saveHisData();
		}
	});
	
	$('#clear_his_data').on('tap', function(){
		plus.storage.removeItem("doctorSearchHis"+docInfo.code);
		historyList();
		$history.hide();
	})
	
	$hisSearList.on('click','.his-list',function(){
		var $that = $(this);
		page = 0;
		$("#searchAll").hide();
	    $searchSuggest.hide();
	    $history.hide();
	    $searchbarInput.val($that.text())
		searchByPaging(false);
	})
	
	$('.lin-search-ipt a').on('tap', function(){
		plus.webview.currentWebview().hide();
		mui.later(function(){
			$('#search_result').hide();
			$('#no_result_wrap').hide();
			$('#searchPut').val("");
			$("#search_suggest_text").html("").hide();
			$("#searchPut").blur();
		}, 50)
	})
	
	$searchSuggest.on('click',function() {
	    page = 0;
		$searchSuggest.hide();
		searchByPaging(false);
		
		//保存历史数据20个
		saveHisData()
	});
	
	$patiList.on('tap','li[data-code]',function(e) {
		var code = $(this).attr("data-code");
		var name = $(this).attr("data-name");
		mui.openWindow('../../mine/html/zuyuanziliao.html', 'zuyuanziliao', {
			extras: {
				docCode: code,
				docName:name,
				teamCode: docInfo.adminTeamCode,
//				isTeamOwner: isTeamOwner
			}
		});
		return false;
	})
	
	function saveHisData(){
		//保存历史数据20个
		var value = $searchbarInput.val().trim();
		if(value){
			if(historyData.length>19){
				historyData.pop();
			}
			if(historyData.indexOf(value)>-1){
				historyData =  _.filter(historyData, function(o){ return o != value; });
			}
			historyData.unshift(value);
			var str = JSON.stringify(historyData)
			plus.storage.setItem("doctorSearchHis"+docInfo.code,str);
			historyList();
		}
	}
	
	$searchCancelBtn.on('click',function() {
		mui.back()
	})
	
	//搜索全部居民的绑定事件
	$("#searchAll").on('click', function(){
	    openWebview("search_all.html");
	});
};
// 页面业务处理流程开始
new Promise(function(resolve, reject) {
	mui.plusReady(function() {
		resolve(true);
	})
}).then(function() {
	// 获取基础环境信息
	return getBaseEnvPromise().then(function(env) {
		baseEnv = env;
	}).then(function() {
		// 获取登录基本信息
		baseInfo = getBaseInfo();
		self = plus.webview.currentWebview();
		$searchbar.searchBar();
//		openSoftKeyboard();
		$searchbarInput.focus();
		historyList();
		if(historyData.length){
			$history.show();
		}
		// 绑定页面事件
		bindEvents();
	})
}).catch(function(e) {
	plus.nativeUI.closeWaiting();
	console && console.error(e);
});

+ 6 - 6
html/tuandui/js/tuandui.js

@ -98,19 +98,19 @@ bindEvents = function () {
            
        if(isOpen) {
            $el.removeClass("current");
            $el.find(".ui-arrow").removeClass("ui-arrow-t");
            $el.find(".ui-arrow").addClass("ui-arrow-b");
            $el.find(".ui-arrow").removeClass("ui-arrow-b");
            $el.find(".ui-arrow").addClass("ui-arrow-r");
            $groupInfo.hide();
        }else{
            var $opened = $(".group-item.current");
            $el.addClass("current");
            $el.find(".ui-arrow").removeClass("ui-arrow-b");
            $el.find(".ui-arrow").addClass("ui-arrow-t");
            $el.find(".ui-arrow").removeClass("ui-arrow-r");
            $el.find(".ui-arrow").addClass("ui-arrow-b");
            
            if($opened.length > 0){
                $opened.removeClass('current').find(".group-info").hide();
                $opened.find(".ui-arrow").removeClass("ui-arrow-t");
                $opened.find(".ui-arrow").addClass("ui-arrow-b");
                $opened.find(".ui-arrow").removeClass("ui-arrow-b");
                $opened.find(".ui-arrow").addClass("ui-arrow-r");
            }
             $groupInfo.show();
        }