
var recordIds = [];
var isDataLoadSuccess = false;
var element,laydate;
//通知弹窗ID，用于关闭
var layerDemorb = 0;
var tipsNum;
//缺陷项集
var allDefect;
if (inpatientAreaInputName != '') {
	$("#inpatientAreaInputName").text(inpatientAreaInputName + "：");
}
if (departmentInputName != '') {
	$("#departmentInputName").text(departmentInputName + "：");
}

$(function() {
	init();
	layui.use(['laydate','element'], function () {
		element = layui.element;
		date = new Date();
		var max = date.getFullYear() + '-' + (date.getMonth() + 1);
		var laydate = layui.laydate;
		/*病区时间选择器*/
		var qcMonth = laydate.render({
			elem: '#hospitDate',
			theme: 'molv',
			max: max,
			type: 'month',
			trigger: 'click',
			btns: ['clear', 'confirm'],
			done: function (value, date) {
			},
			change: function (value, date, endDate) {
				if ($(event.target).hasClass("layui-this")) {
					$(this.elem).val(value);
					$(".layui-laydate").remove();
				}
			}
		});
	});
});

/**
 * 查询
 */
function query(){
	isDataLoadSuccess = false;
	getSelect2Checked();

	$.table.search()
}

/**
 * 页面初始化
 */
function init(){
	//隐藏selec2搜索框
	hiddenSelect2Search();

	//初始化科室,病区和医生
	initInpatientArea();
	initDepartmentSel(allDepartment);
	initDoctor(allDoctor);
	//默认登录用户所在科室
	if(deptName != null && deptName != ''){
		if($.inArray(deptName, allInpatientArea) === -1){
			var html = $("#inpatientAreaSel").html();
			html += "<option value='" + deptName + "'>" + deptName + "</option>"
			$("#inpatientAreaSel").html(html);
		}
		$("#inpatientArea").val(deptName);
		$("#inpatientAreaSel").val(deptName).trigger('change');
		$("#inpatientAreaSel").attr("disabled","disabled").css("background","rgba(0,0,0,.075)");
	}
	//默认病区
	if(inpatientAreaName != null && inpatientAreaName != ''){
		var areaNames = inpatientAreaName.split(",");
		for (var i = 0; i < areaNames.length; i++) {
			areaNames[i] = areaNames[i].substring(0,areaNames[i].indexOf("病区")+2)
		}
		$("#departmentName").val(areaNames);
		$("#departmentSel").val(areaNames).trigger('change');
		$("#departmentSel").attr("disabled","disabled");
		setTimeout(function () {
			$("#departmentSel").next().find("li.select2-selection__choice").css("color","#0e0e0e")
		},100);
	}
	/*//默认大部门
	if(inpatientAreaName != null && inpatientAreaName !== ''){
		if($.inArray(inpatientAreaName, allInpatientArea) === -1){
			var html = $("#inpatientAreaSel").html();
			html += "<option value='" + inpatientAreaName + "'>" + inpatientAreaName + "</option>"
			$("#inpatientAreaSel").html(html);
		}
		$("#inpatientArea").val(inpatientAreaName);
		$("#inpatientAreaSel").val(inpatientAreaName);
		$("#inpatientAreaSel").trigger('change');
		$("#inpatientAreaSel").attr("disabled","disabled").css("background","rgba(0,0,0,.075)");
	}
	//默认小部门
	if(deptName != null && deptName !== ''){
		var deptNames = deptName.split(",")
		for (var i = 0; i < deptNames.length; i++) {
			deptNames[i] = deptNames[i].substring(0,deptNames[i].indexOf("病区")+2)
		}
		$("#departmentName").val(deptNames);
		$("#departmentSel").val(deptNames).trigger('change');
		$("#departmentSel").attr("disabled","disabled");
		setTimeout(function () {
			$("#departmentSel").next().find("li.select2-selection__choice").css("color","#0e0e0e")
		},100);
	}*/

	// 如果大部门锁定了，可以调整小部门，
	// 如果小部门锁定了，那么大部门也要锁定
	if ($("#departmentSel").attr('disabled') == 'disabled')	{
		$("#inpatientAreaSel").attr("disabled","disabled").css("background","rgba(0,0,0,.075)");
	}


	var panehHidden = false;
	if ($(this).width() < 769) {
		panehHidden = true;
	}
	$('body').layout({
		initClosed : panehHidden,
		west__size : 185
	});
	//获取重点指标
	queryKeyIndicesOption();
	//初始列表
	queryUserList();

	$('#search').slideToggle(200);

	$('#remindAllBtn').click(function () {
		var rows = $('#bootstrap-table').bootstrapTable('getSelections');
		sendRemind(rows);
	});
}

/**
 * 初始化数据列表
 */
function queryUserList() {

	if(doctorName != null){
		$("#mainDoctor").val(doctorName);
		$("#div11").hide();
		$("#div22").hide();
	}
	isDataLoadSuccess = false;
	var options = {
		url : prefix + "/list",
		exportUrl: prefix + "/export",
		modalName : "过程质控",
		showSearch : false,
		sortName: "in_time",
		sortOrder: "desc",
		columns : [
			// {
			// 	checkbox : true,
			// 	visible: hasRemind
			// },
			{
				field : 'recordId'
				,title : '记录编号'
				,visible: false
			},
			{
				field : 'hospitNum'
				,title : '病案号'
				//,align : 'center'
				,sortable : false
				,formatter : function(value, row, index) {
					recordIds.push(row.recordId);
					return '<a href="javascript:void(0)" style="color: #080bea;" onclick="mrqcDetial(\''+ row.recordId +'\')"> '+ value +' </a> '
				}
			},
			{
				field : 'patientName',
				title : '患者',
				sortable : false
			},
			{
				field : 'mainDoctor',
				title : '主治医生',
				sortable : true
			},
			{
				field : 'diagnosis',
				title : '诊断',
				sortable : false
				,formatter : function(value, row, index) {
					if(value != null && value.length > 7 ){
						return "<div title='"+ value +"'> "+ value.substring(0,7) +"... </div>";
					}else{
						return value;
					}
				}
			},
			{
				field : 'inNum',
				title : '住院天数',
				align : 'center',
				sortable : true
			},
			{
				field : 'inTime',
				title : '入院时间',
				align : 'center',
				sortable : true
			},
			{
				field : 'timeoutItemNum',
				title : '超时项目',
				align : 'center',
				sortable : false
				,formatter : function(value, row, index) {
					if(value == null || value == undefined || value === ""){
						value = 0;
					}
					return "<div style='width: 100%; height: 100%' id='div_" + row.recordId +"1' " +
						"onmouseover=\"showTips('"+ value +"','"+ row.recordId +"',1)\" onmouseleave='closeLayTips()'>"+ value +"</div>";
				}
			},
			/*{
                field : 'missingItemNum',
                title : '漏缺项目',
                align : 'center',
                sortable : true
            },*/
			{
				field : 'keyItemNum',
				title : '重点项目',
				align : 'center',
				sortable : false
				,formatter : function(value, row, index) {
					if(value == null || value == undefined || value === ""){
						value = 0;
					}
					return "<div style='width: 100%; height: 100%' id='div_" + row.recordId +"2' " +
						"onmouseover=\"showTips('"+ value +"','"+ row.recordId +"',2)\" onmouseleave='closeLayTips()'>"+ value +"</div>";
				}
			},
			{
				field : 'contentNum',
				title : '缺失文书',
				align : 'center',
				sortable : true
			},
			{
				field: 'homepageScore',
				title: '首页结果',
				align: 'center',
				sortable: true
				, formatter: function (value, row, index) {
					if (value > lvYTopScore) {
						return '甲（' + value + '分）';
					} else if (value > lvBTopScore) {
						return '乙（' + value + '分）';
					} else {
						return '丙（' + value + '分）';
					}
				}
			},
			{
				field: 'recordScore',
				title: '全病历结果',
				align: 'center',
				sortable: true
				, formatter: function (value, row, index) {
					if (value > lvYTopScore) {
						return '甲（' + value + '分）';
					} else if (value > lvBTopScore) {
						return '乙（' + value + '分）';
					} else {
						return '丙（' + value + '分）';
					}
				}
			},
			{
				field : 'messageNum',
				title : '提醒/已读',
				align : 'center',
				sortable : true
			},{
				title : '操作',
				align : 'center',
				formatter : function(value, row, index) {
					var actions = [];
					actions.push('<a class="btn btn-info btn-xs '
						+ '" href="javascript:void(0)" onclick="showMrqcHistory(\''+ row.recordId +'\')"><i class="fa fa-map" style="margin-right: 2px;"></i>提醒历史</a> ');
					actions.push('<a class="btn btn-success btn-xs '
						+ '" href="javascript:void(0)" onclick="showDefect(this,\''+ row.recordId +'\')"><i class="fa fa-edit" style="margin-right: 2px;"></i>缺陷项</a> ');
					/*actions.push('<a class="btn btn-primary btn-xs '
                            + '" href="javascript:void(0)" onclick="refreshEmrScore(\''+ row.recordId +'\')"><i class="fa fa-refresh"></i>刷新</a> ');*/
					if(hasRemind){
						actions.push('<a class="btn btn-warning btn-xs '
							+ '" href="javascript:void(0)" onclick="remind(\''+ index +'\')"><i class="fa fa-bell" style="margin-right: 2px;"></i>提醒</a> ');
					}

					return actions.join('');
				}
			} ],
		onLoadSuccess: function (data) {
			isDataLoadSuccess = true;
			if(recordIds.length > 0){
				//列表加载完成后，加载缺陷项
				findAllDefects();
			}
		}
	};
	$.table.init(options);
}

/**
 * 重置页面
 */
function resetIndex() {
	window.location.reload();
}

/**
 * 发送提醒
 */
function sendRemind(rows) {
	if (rows.length == 0) {
		$.modal.alertWarning("请至少选择一条记录");
		return;
	}

	//暂时用不上，先注释，如果要使用，需要将住院号改成recordId
// 	var hospitNums = "";
// 	for(var i = 0; i < rows.length; i ++) {
// 		hospitNums += rows[i].hospitNum;
// 		hospitNums += ",";
// 	}
//	$.modal.open("确认发送质控消息", prefix + "/sendMessage?blhs=" + hospitNums.substring(0, hospitNums.length - 1), '500', '400');
	var recordIds = "";
	var mainDoctors = "";
	for(var i = 0; i < rows.length; i ++) {
		if(i==0){
			recordIds = rows[i].recordId;
			mainDoctors = rows[i].mainDoctor;
		}else{
			recordIds += ","+rows[i].recordId;
			mainDoctors += ","+rows[i].mainDoctor;
		}
	}
	$.modal.open("确认发送质控消息", prefixKqyy + "/sendMessage?recordId=" + recordIds+"&mainDoctors="+mainDoctors, '500', '400');


};

/**
 * 提醒
 */
function remind(index) {
	var row = $("#bootstrap-table").bootstrapTable("getData")[index];
	var rows = [];
	rows.push(row);
	sendRemind(rows);
}

/**
 * 展示病历详情
 */
function mrqcDetial(recordId) {
	var index = parent.layer.open({
		type : 2,
		title : '质控详情页面',
		content :  ctx + "mrqc/emrrecord/todetail/" + recordId,
		area : [ '100%', '100%' ],
		maxmin : true
	});
};

/**
 * 获取重点指标选择项
 */
function getSelect2Checked() {
	var keyIndices = new Array();
	var departmentNames = new Array();
	var doctors = new Array();
	$("#keyIndices option:selected").each(function () {
		if ($(this).val() != null && $(this).val() != '')
			keyIndices.push($(this).val())
	});
	$("#keyIndiceVals").val(keyIndices.join(','));

	$("#departmentSel option:selected").each(function () {
		if ($(this).val() != null && $(this).val() != '')
			departmentNames.push($(this).val())
	});
	$("#departmentName").val(departmentNames.join(','));

	if(doctorName != null){
		$("#mainDoctor").val(doctorName);
		$("#div11").hide();
		$("#div22").hide();
	}else{
		$("#mainDoctorSel option:selected").each(function () {
			if ($(this).val() != null && $(this).val() != '')
				doctors.push($(this).val())
		});
		$("#mainDoctor").val(doctors.join(','));
	}
}

/**
 * 获取重点监控指标
 */
function queryKeyIndicesOption() {
	$.ajax({
		url: ctx + 'userMrqc/loadKeyIndices',
		type: 'get',
		success: function (res) {
			if (res && res.length > 0) {
				var html = "";
				for (var i = 0; i < res.length; i++) {
					html += "<option value='"+res[i].code+"'>" + res[i].desc + "</option>"
				}
				$("#keyIndices").html(html);
			}
		}
	});
}

/**
 * 初始化科室
 */
function initInpatientArea() {
	$("#inpatientAreaSel").html("");
	var html = "<option value=''>全部</option>";

	for (var i = 0; i < allInpatientArea.length; i++) {
		var inpatientAreaElement = allInpatientArea[i];
		html += "<option value='" + inpatientAreaElement + "'>" + inpatientAreaElement + "</option>"
	}
	$("#inpatientAreaSel").html(html);
}

/**
 * 初始化病区
 */
function initDepartmentSel(departments) {
	$("#departmentSel").html("");
	var html = "";
	for (var i = 0; i < departments.length; i++) {
		var department = departments[i];
		if(department.search("病区") != -1){
			department = department.substring(0,department.indexOf("病区")+2)
		}
		html += "<option value='" + department + "'>" + department + "</option>"
	}
	$("#departmentSel").html(html);
}

/**
 * 初始化医师
 */
function initDoctor(doctors) {
	$("#mainDoctorSel").html("");
	var html = "";

	for (var i = 0; i < doctors.length; i++) {
		html += "<option value='" + doctors[i] + "'>" + doctors[i] + "</option>"
	}
	$("#mainDoctorSel").html(html);
}

/**
 * 科室选择，联动医生
 */
$("#inpatientAreaSel").on("change",function(){
	var inpatientArea = $(this).val();
	$("#inpatientArea").val(inpatientArea);
	if(inpatientArea === ''){
		initDepartmentSel(allDepartment);
		initDoctor(allDoctor);
	}else{
		if(doctorMapByArea[inpatientArea]){
			initDoctor(doctorMapByArea[inpatientArea]);
		}else{
			initDoctor(allDoctor);
		}
		if(allAreaAndDepatment[inpatientArea]){
			initDepartmentSel(allAreaAndDepatment[inpatientArea]);
		}else{
			initDepartmentSel(allDepartment);
		}

	}
});

/**
 * 医生选择，赋值input
 */
$("#mainDoctorSel").on("select2:select",function(){
	var inpatientArea = $(this).val();
	if(inpatientArea === ''){
		initDoctor(allDoctor)
	}else{
		for(var p in doctorMapByArea){
			if(p === inpatientArea){
				initDoctor(doctorMapByArea[p])
			}
		}
	}
});

/**
 * 切换在院/出院
 */
function changeStatus() {

	if(isDataLoadSuccess){
		var status = $("#status").val();
		$("#changeStatusBox").removeClass("class");
		if(status === "0"){
			$("#mouth").html("出院月份：");
			$("#status").val("1");
			$("#changeStatusBox").removeClass("fa-toggle-off");
			$("#changeStatusBox").addClass("fa-toggle-on");
		}else{
			$("#mouth").html("入院月份：");
			$("#status").val("0");
			$("#changeStatusBox").removeClass("fa-toggle-on");
			$("#changeStatusBox").addClass("fa-toggle-off");
		}

		getSelect2Checked();
		$.table.search();
	}else{
		layer.msg("请在列表数据加载完成后切换！")
	}
	isDataLoadSuccess = false;
}

/**
 * 关闭缺陷项弹窗
 */
function closeLayOpen() {
	layer.close(layerDemorb);
	$('#defectDiv').css("left","").css("top","");
}

/**
 * 关闭悬浮窗
 */
function closeLayTips() {
	layer.close(tipsNum);
}

/**
 * 悬浮窗
 */
function showTips(value,id,type) {
	if(value != '0' && allDefect){
		var allDefectElement = allDefect[id];
		var tipHtml = [];
		var count = 1;
		var countRemarks = [];
		for (var i = 0; i < allDefectElement.length; i++) {
			var defect = allDefectElement[i];
			var resultRemark = defect.resultRemark;
			resultRemark = resultRemark == "" ? defect.ruleRemark : resultRemark
			if($.inArray(resultRemark,countRemarks) < 0){
				if(type == 1){
					if(defect.ruleType === '及时性'){
						tipHtml.push("<p>"+ count +"."+ resultRemark +"</p>");
						count++;
					}
				}else if(type == 2 ){
					if(defect.ruleScore >= 5){
						tipHtml.push("<p>"+ count +"."+ resultRemark +"</p>");
						count++;
					}
				}
			}
			countRemarks.push(resultRemark);
		}
		var y = 'auto';
		var x = 'auto';
		var newTipHtml = [];
		if(count > 10){
			y = '245px';
			newTipHtml.push("<div style='height:235px;overflow:auto'>");
		}else{
			newTipHtml.push("<div>");
		}
		newTipHtml.push(tipHtml.join(''))
		newTipHtml.push("</div>");
		tipsNum = layer.tips(newTipHtml.join(''), '#div_'+ id + type, {
			tips: [3, 'rgba(0,0,0,0.6)']
			,time: 0
			,area: [x, y]
		});
	}

}

/**
 * 加载缺陷项数据
 */
function findAllDefects() {
	$.ajax({
		url : prefix + "/findAllDefectsByRecordIds",
		method : "get",
		data : {
			"recordIds" : recordIds
		},
		success : function(ret) {
			if(ret.code == '0'){
				allDefect = ret.data;
				recordIds = [];
			}
		}
	});
}

/**
 * 展示缺陷项
 */
function showDefect(btn,recordId) {
	$('#defectContentDiv').html('');
	if(!allDefect){
		layer.msg("正在加载数据，请稍后...");
		return;
	}
	var defectElement = allDefect[recordId];
	if(defectElement){
		// layer.close(layerDemorb);
		$('#defectDiv').css("left","").css("top","");
		var defectContents = {};
		var resultRemarks = [];
		for (var i = 0; i < defectElement.length; i++) {
			var elementData = defectElement[i];
			var emrName = elementData.emrName;
			/* 重复规则移除操作*/
			var remark = elementData.resultRemark == "" ? elementData.ruleRemark : elementData.resultRemark;
			if($.inArray(remark, resultRemarks) < 0){
				if(defectContents.hasOwnProperty(emrName)){
					var content = defectContents[emrName];
					content.push(elementData);
					defectContents[emrName] = content;
				}else{
					var content = [];
					content.push(elementData);
					defectContents[emrName] = content;
				}
			}
			resultRemarks.push(remark)
		}
		var defectHtml = [];
		var topImageSrc = $('#topImage').attr("src");
		var warnImageUrl  = topImageSrc.substring(0,topImageSrc.lastIndexOf('/')+1) + "warn.png";
		$.each(defectContents,function (key, value) {
			defectHtml.push('<div class="layui-colla-item">');
			defectHtml.push('<h2 class="layui-colla-title">'+ key +'('+ value.length +')</h2>');
			defectHtml.push('<div class="layui-colla-content layui-show" style="padding: 0px 5px;">');
			for (var i = 0; i < value.length; i++) {
				var valueElement = value[i];
				var stdScore = valueElement['stdScore'];
				var stdScoreUnit = valueElement['stdScoreUnit'];

				if(stdScoreUnit.indexOf("丙") != -1){
					stdScore = stdScoreUnit;
				}else if(!stdScore || typeof (stdScore) == 'undefined'){
					stdScore = '';
				}else{
					stdScore = "-" + stdScore + "/" + stdScoreUnit;
				}

				defectHtml.push('<li style="border-radius: 5px;margin-bottom: 2px; padding-left: 5px; background: #ffffffff; margin-top: 4px; background: url('+ warnImageUrl +') left 5px' +
					' no-repeat;">');
				defectHtml.push('<div class="zkFirst" style="height: 40px;margin-left: 20px;font-family:\'微软雅黑\';font-size: 14px;color: #333;" title="条款：'+ valueElement['ruleName'] +'&#10;扣分：'+ stdScore +'&#10;缺陷：'+ valueElement['resultRemark'] +'">');
				defectHtml.push('<div><div style="width:95%;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;">')
				defectHtml.push(valueElement['ruleName']);

				defectHtml.push('</div></div><div style="height:10px"><span class="" style="height: 20px; line-height: 20px;color:red;">');

				defectHtml.push('<b>-'+ stdScore !=null && typeof (stdScore) != "undefined" ? stdScore : '' + '</b>')
				defectHtml.push('</span></div>');
				defectHtml.push('</div>');
				defectHtml.push('</li>');
			}
			defectHtml.push('</div></div>');
		});
		$('#defectContentDiv').html(defectHtml.join(''));
		element.init();

		var y = ($(btn).offset().top - 100);
		var x = ($(btn).offset().left - 340);

		var outerWidth = $(document).width();
		var outerHeight = $(document).height();

		var windowHeigth = outerHeight / 2 - 100;
		if(y >= windowHeigth){
			y = windowHeigth - 100;
			if(y < 0){
				y = 0;
			}
		}

		layerDemorb = layer.open({
			type: 1
			,title: false
			,area: ['350px', '475px']
			,offset: [y + 'px', x + 'px']
			,skin: 'layer-ext-myskin'
			,content: $('#defectDiv')
			,shade: 0 //不显示遮罩
			,closeBtn: 0
			,shadeClose: true
		});
	}
}

function showMrqcHistory(recordId){
	var index = parent.layer.open({
		type : 2,
		title : '质控提醒历史页面',
		content :  ctx + "mrqc/histoty/timeline/" + recordId,
		area : [ '100%', '100%' ],
		maxmin : true
	});
}

/**
 * 隐藏select2搜索框
 */
function hiddenSelect2Search() {
	$("#recordLevel").select2({
		minimumResultsForSearch: Infinity // 隐藏搜索框
	});
	// $("#inpatientAreaSel").select2({
	// 	minimumResultsForSearch: Infinity // 隐藏搜索框
	// });
	// $("#machineOrLabor").select2({
	// 	minimumResultsForSearch: Infinity // 隐藏搜索框
	// });
	// $("#departmentSel").select2({
	// 	minimumResultsForSearch: Infinity // 隐藏搜索框
	// });
}
//管理员或质控员刷新在院病历
function refreshAllKqyy(){

	layer.confirm("刷新在院病历可能需要十分钟左右，您确定要继续吗？", function(confirmWnd){
		layer.close(confirmWnd);
		var loading = layer.load();
		$.ajax({
			url : prefixKqyy + "/refreshAllEmrScoreZy",
			method : "post",
			data : {
				"department" : $("#inpatientAreaSel").val()
			},
			success : function(ret) {
				if(ret == null){
					return;
				}
				layer.close(loading);
				if(ret.code == '0'){
					$.modal.alertSuccess("刷新在院病历成功");
					layer.close(confirmWnd);
				}
			}
		});

	});

}