$(function () {
	//百叶窗风格
	$('.collapse').collapse({
		toggle: false
	})
	//加载表格
	freshTable();
	//加载时间控件1
	initDateInput(1);
	//加载时间控件2
	initDateInput(2);
	//加载性别
	loadSex();
	//加载科室
	loadDept();
	//加载转归情况
	loadDiagStatus();
});
//加载性别
function loadSex(){
	$.ajax({
		type:'get',
		url:path+'/commom/getSex',
		dataType:'json',
		success:function (data) {
			if(null != data){
				$("#sex").empty();
				var html = '';
				for (var i = 0; i < data.length; i++) {
					if(i > 1){
						html += '<div class="col-sm-3 radioDiv">'
							 +'<input type="radio"  name="sex" value="'+data[i].name+'" class="sexInput">'+data[i].name+'</div>';
					}else{
						html += '<div class="col-sm-2 radioDiv">'
							 +'<input type="radio"  name="sex" value="'+data[i].name+'" class="sexInput">'+data[i].name+'</div>';
					}
				}
				$("#sex").append(html);
			}
		}
	})
}

//加载科室
function loadDept(){
	$.ajax({
		type:'get',
		url:path+'/commom/getDept',
		dataType:'json',
		success:function (data) {
			if(null != data){
				$("#dis_dept").empty();
				var html = '<option value=""></option>';
				for (var i = 0; i < data.length; i++) {
					if(data[i].name != ''){
						html += '<option value="'+data[i].name+'">'+data[i].name+'</option>';
					}
				}
				$("#dis_dept").append(html);
				$("#dis_dept").selectpicker('refresh');
			}
		}
	})
}

//加载转归情况
function loadDiagStatus(){
	$.ajax({
		type:'get',
		url:path+'/commom/getDiagStatus',
		dataType:'json',
		success:function (data) {
			if(null != data){
				$("#dis_thing").empty();
				var html = '<option value="">全部</option>';
				for (var i = 0; i < data.length; i++) {
					if(data[i].code != '0'){
						html += '<option value="'+data[i].name+'">'+data[i].name+'</option>';
					}
				}
				$("#dis_thing").append(html);
			}
		}
	})
}

//动态控制限手术的值
$("#isOper").change(function () {
	var checked = $(this).is(':checked');
	if(checked){
		$(this).val(1)
	}else{
		$(this).val("");
	}
})
//时间格式属性名集合
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_lock.id is null THEN 0 ELSE 1 END lockStatus,archive_master.checked_datetime,';
		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 ";
			}
		}
		//年龄
		if($("#age1").val() != '' && $("#age2").val() != ''){
			var ageType = $("#ageType").val();
			if(ageType == '1'){
				name = 'age';
				if($("#age1").val() < $("#age2").val()){
					whereNames += "(" + commomtable+"."+name+" BETWEEN "+$("#age1").val()+" AND "+($("#age2").val()-1)+" or (" + commomtable+"."+name+"="+$("#age2").val()+" and "+commomtable+".age_month=0 and "+commomtable+".age_day=0)) AND ";
				}else if($("#age2").val() < $("#age1").val()){
					whereNames += "(" + commomtable+"."+name+" BETWEEN "+$("#age2").val()+" AND "+($("#age1").val()-1)+" or (" + commomtable+"."+name+"="+$("#age1").val()+" and "+commomtable+".age_month=0 and "+commomtable+".age_day=0)) AND ";
				}
			}else if(ageType == '2'){
				//周
				name = 'age_month';
				if($("#age1").val() < $("#age2").val()){
					whereNames += "(" + 'age = 0 AND '+ commomtable+"."+name+" BETWEEN "+$("#age1").val()+" AND "+($("#age2").val()-1)+" OR ("+commomtable+".age = 0 AND "+commomtable+".age_month = "+$("#age2").val()+" AND "+commomtable+".age_day = 0)) AND ";
				}else if($("#age2").val() < $("#age1").val()){
					whereNames += "(" + 'age = 0 AND '+ commomtable+"."+name+" BETWEEN "+$("#age2").val()+" AND "+($("#age1").val()-1)+" OR ("+commomtable+".age = 0 AND "+commomtable+".age_month = "+$("#age1").val()+" AND "+commomtable+".age_day = 0)) AND ";
				}
			}else if(ageType == '3'){
				//天
				name = 'age_day';
				if($("#age1").val() < $("#age2").val()){
					whereNames += commomtable+"."+name+" BETWEEN "+$("#age1").val()+" AND "+$("#age2").val()+" AND ";
				}else if($("#age2").val() < $("#age1").val()){
					whereNames += commomtable+"."+name+" BETWEEN "+$("#age2").val()+" AND "+$("#age1").val()+" AND ";
				}
				whereNames += 'age = 0 AND age_month = 0 AND ';
			}
		}
		//性别
		var sex = $("input[name='sex']:checked").val();
		if(sex != ''){
			name = 'sex';
			whereNames += commomtable+"."+name+" = '"+sex+"' 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] != ''){
						inpatientNo[i] = inpatientNo[i].replace(/(^\s*)|(\s*$)/g, "");
						//拼接前括号
						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 ";
		}
		//出院科室
		var disDept = $("#dis_dept").val();
		if(disDept != '' && disDept != null && disDept != 'null'){
			var disDepts = "";
			for (var i = 0; i < disDept.length; i++) {
				if(disDept[i] != ''){
					disDepts+="'"+disDept[i]+"',";
				}
			}
			disDepts = disDepts.substring(0,disDepts.length-1);
			name = 'dis_dept';
			whereNames += commomtable+"."+name+" IN ("+disDepts+") AND ";
		}
		//病状转归
		if($("#dis_thing").val() != ''){
			name = 'main_dis_thing';
			whereNames += commomtable+"."+name+" = '"+$("#dis_thing").val()+"' AND ";
		}
		//入院日期
		if($("#startTime1").val() != '' && $("#endTime1").val() != ''){
			name = 'admiss_date';
			whereNames += commomtable+"."+name+" BETWEEN '"+$("#startTime1").val()+" 00:00:00' AND '"+$("#endTime1").val()+" 23:59:59' AND ";
		}
		//出院日期
		if($("#startTime2").val() != '' && $("#endTime2").val() != ''){
			name = 'dis_date';
			whereNames += commomtable+"."+name+" BETWEEN '"+$("#startTime2").val()+" 00:00:00' AND '"+$("#endTime2").val()+" 23:59:59' AND ";
		}
		//诊断名称
		if($("#diag_name").val() != ''){
			name = 'main_diag_name';
			whereNames += commomtable+"."+name+" LIKE '%"+$("#diag_name").val()+"%' AND ";
		}
		//诊断表
		//诊断码
		if($("#diag_code").val() != ''){
			name = 'diag_code';
			whereNames += "t_diag."+name+" LIKE '%"+$("#"+name).val()+"%' AND ";
		}
		//病理诊断
		if($("#pathology_name").val() != ''){
			name = 'diag_name';
			whereNames += "t_diag.diag_type='3' AND t_diag."+name+" LIKE '%"+$("#pathology_name").val()+"%' AND ";
		}
		//伴随诊断
		if($("#follow_name").val() != ''){
			name = 'follow_name';
			whereNames += "t_diag.diag_type>'1' AND t_diag.diag_name LIKE '%"+$("#"+name).val()+"%' AND ";
		}
		//手术表
		//手术编号
		if($("#operate_code").val() != ''){
			name = 'operate_code';
			whereNames += "t_operate."+name+" LIKE '%"+$("#"+name).val()+"%' AND ";
		}
		//手术名称
		if($("#operate_name").val() != ''){
			name = 'operate_name';
			whereNames += "t_operate."+name+" LIKE '%"+$("#"+name).val()+"%' AND ";
		}
		var userName = "'" +$("#userId").val()+ "'";
		fromTableNames += ' left join emr_apply_approve on ' + commomtable + '.patient_id = emr_apply_approve.patient_id \n' +
			'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 diagFlag = false;
		var otherTable = "";
		$(".diagTable").each(function () {
			if($(this).val() != ''){
				diagFlag = true;
				return false;
			}
		})
		if(diagFlag){
			otherTable = 't_diag';
			fromTableNames += ' left join '+otherTable+' on '+commomtable+'.patient_id='+otherTable+'.patient_id';
		}
		//拼接手术表
		var operFlag = false;
		$(".operTable").each(function () {
			if($(this).val() != '' && $(this).val() != 'on'){
				operFlag = true;
				return false;
			}
		})
		if(operFlag){
			otherTable = 't_operate';
			fromTableNames += ' left join '+otherTable+' on '+commomtable+'.patient_id='+otherTable+'.patient_id';
		}
		//限手术
		var isOper = $("#isOper").val();
		if(isOper != '' && isOper == 1){
			name = 'is_oper';
			whereNames += commomtable+"."+name+" = '有' AND ";
		}
		//拼接院内感染表
		var taint_name = $("#taint_name").val();
		if(taint_name != ''){
			otherTable = 't_taint';
			fromTableNames += ' left join '+otherTable+' on '+commomtable+'.patient_id='+otherTable+'.patient_id';
			name = 'taint_name';
			whereNames += otherTable+".taint_type='1' AND "+otherTable+"."+name+" LIKE '%"+$("#"+name).val()+"%' AND ";
		}
		//拼接archive_master表，查询终审时间
		otherTable = 'archive_master';
		fromTableNames += ' left join '+otherTable+' on '+commomtable+'.patient_id='+otherTable+'.id';
		//console.log(selectNames);
		//console.log(fromTableNames);
		//console.log(whereNames);
		if(whereNames != ' where '){
			whereNames = whereNames.substring(0,whereNames.length - 4);
			var orderBys = " ORDER BY "+commomtable+".inpatient_no,"+commomtable+".admiss_times";
			var sql =  selectNames + fromTableNames + whereNames;
			$("#sql").val(sql);
			$("#orderBys").val(orderBys);
		}
		//console.log(sql);
	}else{
		$("#sql").val("");
	}
}
//搜索功能
function search() {
	var inpatient_no = $("#inpatient_no").val();
	if(inpatient_no != '' && (inpatient_no.indexOf(",")==-1 || inpatient_no.indexOf("，")==-1) && inpatient_no.length > 16){
		toastr.warning("病案号的长度太长!");
		return false;
	}
	getSql();
	freshTable();
}
//查看详情
function showDetail(patientId){
	//隐藏模板选项
	//window.location.href=path+"/commom/showRecord?patientId="+patientId;
}
//导出excel功能
function exportExcel(){
	getChecked();
	//var isInputValue = getInputValue();
	   var checks = $("#checks").val();
	/*if(isInputValue == '' && checks == ''){
		toastr.warning("请至少选择一个!")
	}else{
		*/
		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.admiss_times,commomtable.name,commomtable.sex,commomtable.age,commomtable.age_month,commomtable.home_addr,commomtable.admiss_date,commomtable.dis_date,commomtable.dis_dept,commomtable.main_diag_name,commomtable.main_dis_thing,commomtable.admiss_days,commomtable.attending,commomtable.is_oper 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";
}