$(function () {
	//百叶窗风格
	$('.collapse').collapse({
		toggle: false
	})
	//加载表格
	freshTable();
});

//时间格式属性名集合
var commomtable = 'commomtable';
//拼接sql
function getSql(){
	var inputValue = getInputValue();
	if(inputValue != ''){
		//select语句字符串
		var selectNames = 'select ' + commomtable + '.patient_id,CASE WHEN emr_apply_approve.id is null THEN 0 ELSE 1 END isShowDetail,CASE WHEN emr_apply_approve1.id is null THEN 0 ELSE 1 END isDownload,CASE WHEN emr_lock.id is null THEN 0 ELSE 1 END lockStatus,';
		selectNames += $("#englishFields").val();
		//from语句字符串
		var fromTableNames = ' from ';
		//where语句字符串
		var whereNames = ' where ';
		//判断是否多表
		var tables = false;
		$('.otherTable').each(function () {
			if($(this).val() != ''){
				tables = true;
				return false;
			}
		})
		//单表
		fromTableNames += commomtable;
		//拼接where语句
		var name = '';
		//姓名
		var searchName = $("#name").val();
		if(searchName != ''){
			name = 'name';
			//去除前后空格
			searchName = searchName.replace(/(^\s*)|(\s*$)/g, "");
			var pinyin = /^[a-zA-Z]+$/;
			//1.逗号隔开
			if(searchName.indexOf(",")!=-1 || searchName.indexOf("，")!=-1){
				if(searchName.indexOf(",")!=-1){
					searchName = searchName.split(",");
				}else if(searchName.indexOf("，")!=-1){
					searchName = searchName.split("，");
				}
				for (var i = 0; i < searchName.length; i++) {
					if(searchName[i] != ''){
						//拼接前括号
						if(i == 0){
							whereNames += "(";
						}
						if(i != searchName.length-1){
							if(searchName[i].indexOf("*")!=-1){
								//2.带*号
								searchName[i] = searchName[i].replace("*","_");
								whereNames += commomtable+".name_cym LIKE '%"+searchName[i]+"%' OR ";
							}else if(pinyin.test(searchName[i])) {
								//3.拼音缩写
								whereNames += commomtable+".name_cym LIKE '%"+searchName[i]+"%' OR ";
							}else{
								whereNames += commomtable+"."+name+" LIKE '%"+searchName[i]+"%' OR ";
							}
						}else{
							if(searchName[i].indexOf("*")!=-1){
								//2.带*号
								searchName[i] = searchName[i].replace("*","_");
								whereNames += commomtable+".name_cym LIKE '%"+searchName[i]+"%')";
							}else if(pinyin.test(searchName[i])) {
								//3.拼音缩写
								whereNames += commomtable+".name_cym LIKE '%"+searchName[i]+"%')";
							}else{
								whereNames += commomtable+"."+name+" LIKE '%"+searchName[i]+"%')";
							}
						}
					}
				}
				whereNames += " AND ";
			}else if(searchName.indexOf("*")!=-1){
				//2.带*号
				searchName = searchName.replace("*","_");
				whereNames += commomtable+".name_cym LIKE '%"+searchName+"%' AND ";
			}else if(pinyin.test(searchName)) {
				//3.拼音缩写
				whereNames += commomtable+".name_cym LIKE '%"+searchName+"%' AND ";
			}else{
				whereNames += commomtable+"."+name+" LIKE '%"+$("#"+name).val()+"%' AND ";
			}
		}
		//病案号
		var inpatientNo = $("#inpatient_no").val();
		if(inpatientNo != ''){
			name = 'inpatient_no';
			inpatientNo = inpatientNo.replace(/(^\s*)|(\s*$)/g, "");
			//1.逗号隔开
			if(inpatientNo.indexOf(",")!=-1 || inpatientNo.indexOf("，")!=-1){
				if(inpatientNo.indexOf(",")!=-1){
					inpatientNo = inpatientNo.split(",");
				}else if(inpatientNo.indexOf("，")!=-1){
					inpatientNo = inpatientNo.split("，");
				}
				for (var i = 0; i < inpatientNo.length; i++) {
					if(inpatientNo[i] != ''){
						//拼接前括号
						if(i == 0){
							whereNames += "(";
						}
						if(i != inpatientNo.length-1){
							whereNames += commomtable+"."+name+" LIKE '%"+inpatientNo[i]+"%' OR ";
						}else{
							whereNames += commomtable+"."+name+" LIKE '%"+inpatientNo[i]+"%')";
						}
					}
				}
				whereNames += " AND ";
			}else{
				whereNames += commomtable+"."+name+" LIKE '%"+$("#"+name).val()+"%' AND ";
			}
		}
		//ID号
		if($("#admiss_id").val() != ''){
			name = 'admiss_id';
			whereNames += commomtable+"."+name+" LIKE '%"+$("#"+name).val()+"%' AND ";
		}
		//病状转归
		if($("#dis_thing").val() != ''){
			name = 'main_dis_thing';
			whereNames += commomtable+"."+name+" like '%"+$("#dis_thing").val()+"%' AND ";
		}
		var userName = "'" +$("#userId").val()+ "'";
		fromTableNames += ' left join emr_apply_approve on ' + commomtable + '.patient_id = emr_apply_approve.patient_id and emr_apply_approve.apply_type != 3' +
			'and emr_apply_approve.approve_state = 1 and emr_apply_approve.effe_time > GETDATE()-1 and emr_apply_approve.applyer = '+ userName
		fromTableNames += ' left join emr_apply_approve emr_apply_approve1 on ' + commomtable + '.patient_id = emr_apply_approve1.patient_id and emr_apply_approve1.apply_type = 3' +
			'and emr_apply_approve1.approve_state = 1 and emr_apply_approve1.effe_time > GETDATE()-1 and emr_apply_approve1.applyer = '+ userName
		fromTableNames += ' left join emr_lock on ' + commomtable + '.patient_id = emr_lock.patient_id and emr_lock.lock_state = 1';
		if(whereNames != ' where '){
			whereNames = whereNames.substring(0,whereNames.length - 4);
			var orderBys = " ORDER BY "+commomtable+".inpatient_no";
			var sql =  selectNames + fromTableNames + whereNames;
			$("#sql").val(sql);
			$("#orderBys").val(orderBys);
		}
		//console.log(sql);
	}else{
		$("#sql").val("");
	}
}
//搜索功能
function search() {
	getSql();
	freshTable();
}
//查看详情
function showDetail(patientId){
	//隐藏模板选项
	//window.location.href=path+"/commom/showRecord?patientId="+patientId;
}
//导出excel功能
function exportExcel(){
    var checks = $("#checks").val();
	if($("#rows").val() > 5000 && checks == ''){
		toastr.warning("数据量大,暂提供5000条以内数据导出!");
	}else {
		getSql();
		var userName = "'" + $("#userName").val() + "'";
		var sql1 = "select  commomtable.patient_id,CASE WHEN emr_apply_approve.id is null THEN 0 ELSE 1 END isShowDetail,CASE WHEN emr_lock.id is null THEN 0 ELSE 1 END lockStatus,commomtable.inpatient_no,commomtable.admiss_id,commomtable.name,commomtable.main_dis_thing from commomtable left join emr_apply_approve on commomtable.patient_id = emr_apply_approve.patient_id and emr_apply_approve.approve_state = 1 and emr_apply_approve.effe_time > GETDATE()-1 and emr_apply_approve.applyer = " +userName+ " left join emr_lock on commomtable.patient_id = emr_lock.patient_id and emr_lock.lock_state = 1";
		var sql = $("#sql").val();
		if(sql == ''){
			sql = sql1;
		}
		var reg = new RegExp("%", "g");//g,表示全部替换。
		sql = sql.replace(reg, '%25');
		var tableThNames = $("#tableThNames").val();
		var fieldCns = $("#fieldCns").val();
		var orderBys = $("#orderBys").val();
		if (checks != '') {
			//按选择框选择导出
			checks = checks.substring(0, checks.length - 1);
			var isInputValue = getInputValue();
			if(isInputValue == ''){
				sql += ' WHERE ' + commomtable + '.patient_id IN (' + checks + ')';
			}else{
				sql += ' AND ' + commomtable + '.patient_id IN (' + checks + ')';
			}
			sql += orderBys;
			var url = path + "/template/exportExcel";
			post(url, {"sql": sql, "tableThNames": tableThNames, "fieldCns": fieldCns});
		} else {
			Common.confirm({
				title: "提示",
				message: "没有选中，您确定要按搜索栏条件导出?",
				operate: function (reselt) {
					if (reselt) {
						//sql += orderBys;
						var url = path + "/template/exportExcel";
						post(url, {"sql": sql, "tableThNames": tableThNames, "fieldCns": fieldCns});
					}
				}
			})
		}
	}
}
/*****************************************输入框边输入内容边搜索功能方法*************************************************/
//级联病案号，且长度超过4个字节才查询
function getInpatientNoContents(id) {
	var keyword = document.getElementById(id).value;
	if (keyword.length > 4) {
		var ajax = new XMLHttpRequest();
		var url = path+"/approve/getInpatientNosByName?inpatientNo=" + keyword;
		ajax.open("GET", url, true);
		ajax.send(null);
		ajax.onreadystatechange = function() {
			if (ajax.readyState == 4) {
				if (ajax.status == 200) {
					var result = ajax.responseText;
					insertContent(result,id);
				}
			}
		}
	} else {
		clearContent(id);
		return;
	}
}
//级联诊断码
function getDiagCodeContents(id) {
	var keyword = document.getElementById(id).value;
	if (keyword.length > 2) {
		var ajax = new XMLHttpRequest();
		var url = path+"/commom/getDiagCodeContents?code=" + keyword;
		ajax.open("GET", url, true);
		ajax.send(null);
		ajax.onreadystatechange = function() {
			if (ajax.readyState == 4) {
				if (ajax.status == 200) {
					var result = ajax.responseText;
					insertContent(result,id);
				}
			}
		}
	} else {
		clearContent(id);
		return;
	}
}
//级联手术编码
function getOperateCodeContents(id) {
	var keyword = document.getElementById(id).value;
	if (keyword.length > 2) {
		var ajax = new XMLHttpRequest();
		var url = path+"/commom/getOperateCodeContents?code=" + keyword;
		ajax.open("GET", url, true);
		ajax.send(null);
		ajax.onreadystatechange = function() {
			if (ajax.readyState == 4) {
				if (ajax.status == 200) {
					var result = ajax.responseText;
					insertContent(result,id);
				}
			}
		}
	} else {
		clearContent(id);
		return;
	}
}
//添加内容，tr td
function insertContent(content,id) {
	clearContent(id);
	setLocation(id);
	var json = JSON.parse(content);
	for (key in json) {
		var tr = document.createElement("tr");
		var td1 = document.createElement("td");
		var td2 = document.createElement("td");
		var td3 = document.createElement("td");
		var td4 = document.createElement("td");
		tr.setAttribute("bgcolor", "#FFFAFA");
		tr.setAttribute("border", "0");
		if(id == 'inpatient_no'){
			td1.innerHTML = "病案号:";
		}else if(id == 'diag_code'){
			td1.innerHTML = "ICD码:";
		}else if(id == 'operate_code'){
			td1.innerHTML = "手术编码:";
		}
		td2.innerHTML = key;
		if(id == 'inpatient_no'){
			td3.innerHTML = "姓名:";
		}else if(id == 'diag_code'){
			td3.innerHTML = "诊断名称:";
		}else if(id == 'operate_code'){
			td3.innerHTML = "手术名称:";
		}

		td4.innerHTML = json[key];
		tr.appendChild(td1);
		tr.appendChild(td2);
		tr.appendChild(td3);
		tr.appendChild(td4);
		document.getElementById(id+"Content").appendChild(tr);
		tr.onmouseover = function() {
			this.className = 'mouseOver';
			document.getElementById(id).value=$(this).children("td").eq(1).html();
		};
		tr.onmouseout = function() {
			this.className = 'mouseOut';
		};
	}
}
//清楚内容方法
function clearContent(id) {
	var popNode = document.getElementById(id+"Div");
	popNode.style.border = "none";
	var contentNode = document.getElementById(id+"Content");
	var len = contentNode.childNodes.length;
	for (var i = len - 1; i >= 0; i--) {
		contentNode.removeChild(contentNode.childNodes[i]);
	}
}
//设置样式
function setLocation(id){
	var inputNode = document.getElementById(id);
	var width = inputNode.offsetWidth;
	var left = inputNode["offsetLeft"];
	var top = inputNode.offsetHeight+inputNode["offsetTop"];
	var popNode = document.getElementById(id+"Div");
	popNode.style.border = "gray 0.5px solid";
	popNode.style.width = width+"px";
	popNode.style.top = top+"px";
	popNode.style.left = left+"px";
	document.getElementById(id+"Content_table").style.width=width+"px";
}