/***********************************************表格操作*****************************************************************/
var userName = "'" + $("#userName").val() + "'";
/*
var initSql = "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,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_code,commomtable.main_diag_name,commomtable.main_dis_thing,commomtable.admiss_days,commomtable.attending,commomtable.other_diag_name,commomtable.pathology_name,commomtable.poisoning_name,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+ " and emr_apply_approve.apply_type != 3 left join emr_apply_approve emr_apply_approve1 on commomtable.patient_id = emr_apply_approve1.patient_id and emr_apply_approve1.approve_state = 1 and emr_apply_approve1.effe_time > GETDATE()-1 and emr_apply_approve1.applyer = " +userName+ " and emr_apply_approve1.apply_type = 3 left join emr_lock on commomtable.patient_id = emr_lock.patient_id and emr_lock.lock_state = 1 ";
*/
//定义查看详情的请求地址url
function returnShowDetailUrl(patientId,fileSource,name,disDate){
	if (fileSource==3 && fileSource!="") {
		// var print = $("#print").val();
		return 'http://172.18.0.227:91/LZ_API.aspx?patientId=' + patientId+"&name="+name+"&disDate="+disDate+"&isPrint="+1;
	}else {
		return path + '/commom/showRecord174?patientId=' + patientId;
	}
}
//TODO 添加需要格式化日期格式的字段
var dateFields = 'disDate,admissDate,birthday,affirmDate';
var pageNumber;
$(function(){
	//根据窗口调整表格高度
	/*$(window).resize(function() {
        $('#mytab').bootstrapTable('resetView', {
            height: tableHeight()
        })
    })*/
	//加载通过审批且未过期的patientId集合
	getApproves(1);
	//加载通过审批且可下载的patientId集合
	getApproves(3);
	//查询已锁定的集合
	getLocks();
	//可预览信息
	showRecord = $("#showRecord").val();
	//可下载信息
	downloadRecord = $("#downloadRecord").val();
})
//加载通过审批且未过期的patientId集合:type：1借阅申请，type:2下载申请
function getApproves(type){
	$.ajax({
		type:'get',
		url:path+'/template/getApproves',
		data:{type:type},
		dataType:'json',
		success:function (data) {
			if(null != data && data != ''){
				if(type == 1){
					$("#approves").val(data);
				}else{
					$("#loads").val(data);
				}
			}
		}
	})
}
//查询已锁定的集合
function getLocks(){
	$.ajax({
		type:'get',
		url:path+'/template/getLocks',
		dataType:'json',
		success:function (data) {
			if(null != data && data != ''){
				$("#locks").val(data);
			}
		}
	})
}
function tableHeight() {
	return $(window).height() - 50;

}
$(document).keydown(function (event) {
	if (event.keyCode == 13) {
		search();
	}
});
function freshTable(){
	var powerMenus = $("#powerMenus").val().substring(1,$("#powerMenus").val().length-1);
	var powerMenusArr = powerMenus.split(", ");
	for (var i = 0; i < powerMenusArr.length; i++){
		var strs = powerMenusArr[i];
		if (strs == '/commom/updateCommomInfo') {
			$("#powerMenu").val("true");
		}
	}
	var str = $("#powerMenu").val();
	$("#mytab").bootstrapTable('destroy');
	$("#checks").val('');
	var columns = [];
	var map1 = {};
	map1['title'] = '操作';
	map1['field'] = 'Button';
	map1['align'] = 'center';
	map1['formatter'] = 'AddFunctionAlty';
	columns.push(map1)
	var flag = $("#showPrint").val();
	//固定列标识
	var mixFlag = false;
	if(flag == 1){
		flag = true;
	}else{
		flag = false;
		mixFlag = true;
	}
	columns.push({
			title:'全选',
			field:'select',
			checkbox:true,
			width:25,
			valign:'middle',
		},
		{
			title:'ID',
			field:'patientId',
			visible:false
		})
	var tableThNames = $("#tableThNames").val();
	if(tableThNames != ''){
		var fieldCns = '';
		var fields = $("#fields").val().split(",");
		tableThNames = tableThNames.split(",");
		for(var i = 0;i<tableThNames.length;i++){
			if(tableThNames[i] != ''){
				var map = {};
				if(fields[i] != ''){
					map['title'] = tableThNames[i];
					//重新组织选项
					//转换RH
					if(fields[i] == 'RH'){
						map['field'] = 'rh';
						fields[i] = 'rh';
					}/*if(fields[i] == 'ChosSurg'){
						map['field'] = 'chossurg';
						fields[i] = 'chossurg';
					}*/else{
						map['field'] = fields[i];
					}
					fieldCns += fields[i] + ",";
					if (fields[i]== 'disDate'){
						map["sortable"]=true;
					}
					if (fields[i]== 'admissDate'){
						map["sortable"]=true;
					}
					if (fields[i]== 'admissId'){
						map["sortable"]=true;
					}
					if (fields[i]== 'inpatientNo'){
						map["sortable"]=true;
					}

				}
				if(dateFields.indexOf(fields[i]) != -1){
					map['formatter'] = function (value, row, index) {return formatTime(value,'yyyy-MM-dd')};
				}
				columns.push(map);
			}
		}
		$("#fieldCns").val(fieldCns);
	}


		//生成用户数据
	$('#mytab').bootstrapTable({
		method: 'post',
		contentType:'application/x-www-form-urlencoded; charset=UTF-8',
		toolbar: '#toolbar',    			//工具按钮用哪个容器
		striped: true,                      //是否显示行间隔色
		cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
		pagination: true,                   //是否显示分页（*）
		sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
		paginationPreText : '上一页',
		paginationNextText : '下一页',
		paginationFirstText: '<',
		paginationLastText: '>',
		detailView: flag,
		pageNumber: 1,                       //初始化加载第一页，默认第一页
		pageSize: 5,
		sortName: 'inpatientNo',
		sortable: true,
		sortOrder: 'desc',
		search: true,
		//每页的记录行数（*）
		pageList: [5,10,20,50,100,500,1000],//可供选择的每页的行数（*）
		height: 400,//高度调整                 //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
		buttonsAlign: "left",//按钮对齐方式
		columns:columns,
		fixedColumns: mixFlag,//固定列
		fixedNumber:5,//固定前七列
		locale:'zh-CN',//中文支持,
		url:path+'/template/cutomSearchTable',//排序方式
		queryParams: function (params) {
			const param = {
				selectSql:$("#englishFields").val(),
				fromTableSql:$("#fromTableSql").val(),
				whereSql:$("#whereSql").val(),
				orderBys:$("#orderBys").val(),
				limit : params.limit, // 每页显示数量
				offset : params.offset, // SQL语句起始索引
				page : (params.offset / params.limit) + 1, //当前页码
				sortNames: this.sortName,
				sortOrder:this.sortOrder
			}
			return param
		},
		responseHandler:function(res){
			//在ajax获取到数据，渲染表格之前，修改数据源
			var nres = [];
			nres.push({total:res.total,rows:res.list});
			return nres[0];
		},
		onLoadSuccess:function(res){
			$(".clearfix").height(0);
			$(".page-list").show();
			$(".fixed-table-body").css("overflow","auto");
			//赋值总数
			$("#rows").val(res.total);
			//全选
			$('.fixed-table-container').on('click','input[name="btSelectAll"]',function(){
				if($(this).is(':checked')){
					$('input[name="btSelectItem"]').prop('checked',true);
				}else{
					$('input[name="btSelectItem"]').prop('checked',false);
				}
			})
			//逐个选择
			$('.fixed-table-container').on('click','input[name="btSelectItem"]',function(){
				var inputs = $(this).parents('.fixed-table-body-columns').find('input[name="btSelectItem"]')
				var num = 0;
				inputs.each(function(){
					if($(this).is(':checked')){
						num++;
					}
				});
				if(num==inputs.length){
					$('input[name="btSelectAll"]').prop('checked',true);
				}else{
					$('input[name="btSelectAll"]').prop('checked',false);
				}
				var index = $(this).parents('tr').index();
				$('#Table1').find('input[name="btSelectItem"]').eq(index).click();
			});
		},

		//监听分页点击事件
		onPageChange: function(num, type) {
			pageNumber = num;
		},
		//选中单个复选框
		onCheck:function(row){
			var checks = $("#checks").val();
			$("#checks").val(checks+="'"+row.patientId + "',");
		},
		onUncheck: function (row, $element) {
			chosenGroupId = "";
			$mytab.bootstrapTable("removeAll");
			$mytab.bootstrapTable("refresh");
			//EditViewById(id, 'view');
		},
		onUncheck:function(row){
			var checks = $("#checks").val();
			checks = checks.replace("'"+row.patientId + "',","");
			$("#checks").val(checks);
		},
		//全选
		onCheckAll:function(rows){
			$("#checks").val("");
			var checks = '';
			for(var i=0;i<rows.length;i++)
			{
				checks += "'"+rows[i].patientId + "',"
			}
			$("#checks").val(checks);
		},
		//全不选
		onUncheckAll: function (rows) {
			$("#checks").val("");
		},

		//双击事件
		onDblClickRow: function (row) {
			//是否可查看
			var isShowDetail = row.isShowDetail;
			var lockStatus = row.lockStatus;
			var unlockOper = row.unlockOper;
			if(lockStatus != '' && lockStatus == 1 && unlockOper == 1){
				toastr.warning("不可查看,已被锁定!")
			}else {
				if (null != isShowDetail && isShowDetail == 1 || showRecord == "1") {
					window.open(returnShowDetailUrl(row.patientId,row.fileSource,row.name,row.disDate));
				} else {
					toastr.warning("不可查看,必须申请通过!")
				}
			}
		},
		//展开详情事件
		onExpandRow: function (index, row, $detail) {//點擊datagrid 展開按鈕事件
			var patientId = row.patientId;
			//查询打印简要
			$.ajax({
				type:'get',
				url:path+'/printInfoList/getPrintCount',
				dataType:'json',
				data:{patientId:patientId},
				success:function(data){
					if(data.code == 0){
						var result = data.data;
						var str = "";
						if(result != null && result != ''){
							for(var i = 0;i < result.length;i++){
								str += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
								str += "打印张数:<span style='color: red'>"+result[i].printCount+"</span>;打印时间:<span style='color: red'>"+result[i].createTime+"</span>;" +
									"打印用途:<span style='color: red'>"+result[i].typeName+"</span>;打印者:<span style='color: red'>"+result[i].creater+"</span>";
							}
							$detail.html(str+'<button onclick="javascrtpt:btn()">查看打印详情</button>');
						}else{
							$detail.html('未曾打印');
						}
					}else{
						toastr.error(data.msg);
					}
				}
			})
		}
	})
}
//导出excel功能
function exportExcel() {
	getChecked();
	var checks = $("#checks").val();
	if ($("#rows").val() > 5000 && checks == '') {
		toastr.warning("数据量大,暂提供5000条以内数据导出!");
	} else {
		getSql();
		var tableThNames = $("#tableThNames").val();
		var fieldCns = $("#fieldCns").val();
		if (checks != '') {
			//按选择框选择导出
			checks = checks.substring(0, checks.length - 1);
			var whereSql = ' WHERE ' + commomtable + '.patient_id IN (' + checks + ')';
			var url = path + "/template/exportExcel";
			post(url, {
				"selectSql": $("#englishFields").val(),
				"fromTableSql": $("#fromTableSql").val(),
				"whereSql": whereSql,
				"tableThNames": tableThNames,
				orderBys: $("#orderBys").val(),
				"fieldCns": fieldCns
			});
		} else {
			Common.confirm({
				title: "提示",
				message: "没有选中，您确定要按搜索栏条件导出?",
				operate: function (reselt) {
					if (reselt) {
						var url = path + "/template/exportExcel";
						post(url, {
							"selectSql": $("#englishFields").val(),
							"fromTableSql": $("#fromTableSql").val(),
							"whereSql": $("#whereSql").val(),
							"orderBys": $("#orderBys").val(),
							"tableThNames": tableThNames,
							"fieldCns": fieldCns
						});
					}
				}
			})
		}
	}
}
function btn(){
	var url = path + "/printInfoList/pageUI174";
	window.location.href = url;
}

/**
 * 判断是否有使用固定列获取选中多行数据
 * @param tableId
 * @returns {*}
 */
function getSelectedRow_st(tableId) {
	//解決固定列导致选择复选框选不中的问题
	//首先判断表格是否为固定列表格，使用bootstrapTable('getOptions')获取表格的所有配置项，fixedColumns字段判断是否为固定列
	if($("#"+tableId).bootstrapTable('getOptions').fixedColumns){
		var selectCheckbox = [];
		//循环表格的所有行，判断被选中的行，并且push进入selectCheckbox数组
		for(var i=0;i<$("tbody tr").length;i++){
			if($(".fixed-table-body-columns tbody tr:nth-child("+(i+1)+") td:first input[name='btSelectItem']").prop("checked")){
				// console.log($("#table").bootstrapTable("getData")[i]);//输出选中行的所有数据bootstrapTable("getDate"),获取表格的所有数据
				selectCheckbox.push($("#"+tableId).bootstrapTable("getData")[i]);
			}
		}
		return selectCheckbox;
	}else{
		return $("#"+tableId).bootstrapTable('getSelections');
	}
}

/**
 * 获取选中行
 */
function getChecked(){
	var idlist = getSelectedRow_st("mytab");
	if(idlist.length > 0){
		var checks = '';
		for (var i = 0; i < idlist.length; i++) {
			checks+="'"+idlist[i].patientId + "',";
		}
		$("#checks").val(checks);
	}else{
		$("#checks").val("");
	}
}

function reLoadTable(){
	$("#mytab").bootstrapTable('refresh',path+'/template/cutomSearchTable?sql'+$("#sql").val());
	$('#mytab').bootstrapTable('selectPage', pageNumber);
	$("#checks").val("");
	$("#check").val("");
}

/**
 * 列表行‘操作’按钮
 * @param value
 * @param row
 * @param index
 * @returns {string}
 * @constructor
 */
function AddFunctionAlty(value, row, index) {
	var patientId = "'" + row.patientId + "'";
	var updatePower = $("#powerMenu").val();
	var userId = $("#userId").val();
	//是否可查看
	var isShowDetail = row.isShowDetail;
	var lockStatus = row.lockStatus;
	var lockOper = row.lockOper;
	var unlockOper = row.unlockOper;
	var borrowingOper = row.borrowingOper;
	var downloadOper = row.downloadOper;
	var isDownload = row.isDownload;
	var str = '';
	if(lockStatus != '' && lockStatus == 1 && unlockOper == 1){
		str += '<button type="button" class="btn btn-sm btn-success" onclick="unlock('+patientId+')">解锁</button>';
	}else{
		if (userId == 1 || updatePower == 'true'){
			str += '<button type="button" class="btn btn-sm btn-info TableView btn-sm" data-toggle="modal" data-target="#myModal2" onclick="getUpdateCommomInfo('+patientId+')">修改</button>';
		}
		if((null != isShowDetail && isShowDetail == 1) || showRecord == "1"){
			str += '<a type="button" href="'+returnShowDetailUrl(row.patientId,row.fileSource,row.name,row.disDate)+'" class="btn btn-danger TableView btn-sm" target="_blank">查看详情</a>';
		}else{
			if(borrowingOper == 1){
				str += '<button type="button" class="btn btn-primary TableView btn-sm" onclick="borrowing('+patientId+')"  data-toggle="modal" data-target="#myModal1">借阅申请</button>';
			}
		}
		//判断可否下载
		if(downloadOper == 1){
			if((null != isDownload && isDownload == 1) || downloadRecord == '1'){
				str += '<button type="button" class="btn btn-sm btn-info TableView btn-sm" onclick="downloadPdf('+patientId+')">下载PDF</button>';
			}else{
				str += '<button type="button" class="btn btn-success TableView btn-sm" onclick="downBorrowing('+patientId+')"  data-toggle="modal" data-target="#myModal1">下载申请</button>';
			}
		}
		if(lockOper == 1){
			str += '<button type="button" class="btn btn-warning TableView btn-sm" onclick="lock('+patientId+')">锁定</button>';
		}
	}
	return str;
}


/***********************************************按钮功能*****************************************************************/
//清空功能
function clearForm(){
	document.forms[0].reset();
	$("#dis_dept").selectpicker("refresh");
}

/**
 * 获取修改的病案信息
 * @param patientId
 */
function getUpdateCommomInfo(patientId) {
	$.ajax({
		type:'get',
		url:path+'/commom/getCommomInfoById',
		data:{patientId:patientId},
		dataType:'json',
		success:function(data){
			if(null != data){
				$("#patientId").val(data.patientId);
				$("#inpatientNo").val(data.inpatientNo);
				$("#updateName").val(data.name);
				$("#admissTimes").val(data.admissTimes);
				$("#disDate").val(data.disDate);
				loadDeptDefault(data.disDept);
				$("#main_diag_name").val(data.mainDiagName);
			}
		}
	})
}

/**
 * 提交修改病案信息
 * @param patientId
 */
function updateCommomInfo() {
	$.ajax({
		type:'post',
		url:path+'/commom/updateCommomInfo',
		data:$("#form").serialize(),
		dataType:'json',
		success:function(data){
			if(data!=null && data.code == 0){
				toastr.success("修改成功!");
				freshTable();
				$('#myModal2').modal('hide');
			}else{
				toastr.warning(data.msg);
			}
		}
	})
}

/**
 * 批量下载功能
 * @param typeId
 */
function downloadZip(typeId){
	var patientIds = "";
	getChecked();
	var checks = $("#checks").val();
	if(checks != ''){
		patientIds = powerPotient(checks, true,typeId);
		if(patientIds != ''){
			patientIds = patientIds.substring(0,patientIds.length-1);
			post(path+'/template/downloadBloodZip',{"patientIds":patientIds,
				"flag":$("#flag").val()});
		}else{
			toastr.warning("必须申请通过!")
		}
	}else{
		var sql = $("#sql").val();
		if(sql != '') {
			var rows = $("#rows").val();
			if(rows != '' && rows <= 1000){
				Common.confirm({
					title: "提示",
					message: "没有选中，您确定要按搜索栏条件下载?",
					operate: function (reselt) {
						if (reselt) {
							getSql();
							var sql = $("#sql").val();
							if (sql != '') {
								$.ajax({
									type: 'post',
									url: path + '/template/getPatientIdsBySql',
									data: {sql: sql},
									dataType: 'json',
									success: function (data) {
										if (data != null) {
											patientIds = powerPotient(data, false,typeId);
											if (patientIds != '') {
												patientIds = patientIds.substring(0, patientIds.length - 1);
												//按整份下载
												post(path+'/template/downloadBloodZip',{"patientIds":patientIds,"flag":$("#flag").val()});
											}else {
												toastr.warning("必须申请通过!")
											}
										} else {
											toastr.warning("没有可下载的内容！")
										}
									}
								})
							}
						} else {
							toastr.warning("没有可下载的内容！")
						}
					}
				})
			}else{
				toastr.warning("为了用户体验，限制批量操作不超过1000条数据!");
			}
		}else{
			toastr.warning("搜索条件不可为空!");
		}
	}
}

/**
 * 下载pdf功能
 * @param patientId
 */
function downloadPdf(patientId){
	//查询是否有图片
	$.ajax({
		type:'get',
		url:path+'/template/getScanCountByPatientId',
		data:{patientId:patientId,flag:$("#flag").val()},
		success:function(data){
			if(data == 1){
				post(path + '/template/downloadPdfBlood', {"patientIds": patientId,
					"flag":$("#flag").val()});
			}else{
				toastr.warning("找不到影像资料!");
			}
		}
	})
}


function post(url, params) {
	// 创建form元素
	var temp_form = document.createElement("form");
	// 设置form属性
	temp_form .action = url;
	temp_form .target = "_self";
	temp_form .method = "post";
	temp_form .style.display = "none";
	// 处理需要传递的参数
	for (var x in params) {
		var opt = document.createElement("textarea");
		opt.name = x;
		opt.value = params[x];
		temp_form .appendChild(opt);
	}
	document.body.appendChild(temp_form);
	// 提交表单
	temp_form .submit();
}

/**
 * 定义空的inputValue方法
 * @returns {boolean}
 */
function getInputValue(){
	//判断是否有搜索条件
	//所有input
	var isInputValue = false;
	$('.inputValue').each(function(){
		var val = $(this).val();
		if(val != ''){
			isInputValue = true;
			return;
		}
	})
	//性别
	if(!isInputValue){
		$('input[class=sexInput]:checked').each(function(){
			var val = $(this).val();
			if(val != ''){
				isInputValue = true;
				return;
			}
		})
		//限手术
		var isOperInput = $('.isOperInput').val();
		if(isOperInput == 1){
			isInputValue = true;
		}
	}
	return isInputValue;
}

/**
 * 加载申请借阅类型
 * @param type
 */
function loadApplyType(type){
	$.ajax({
		type:'get',
		url:path+'/template/getLoadApplyType',
		dataType:'json',
		success:function (data) {
			if(null != data){
				$("#applyType").empty();
				var html = '';
				for (var i = 0; i < data.length; i++) {
					if(data[i].code != ''){
						if(type == 1 && data[i].code != 3){
							html += '<option value="'+data[i].code+'">'+data[i].name+'</option>';
						}
						if(type == 2 && data[i].code == 3){
							html += '<option value="'+data[i].code+'">'+data[i].name+'</option>';
						}
						if(type == 4 && data[i].code == 4){
							html += '<option value="'+data[i].code+'">'+data[i].name+'</option>';
						}
					}
				}
				$("#applyType").append(html);
			}
		}
	})
}

/**
 * 单个申请借阅
 * @param patientId
 */
function borrowing(patientId){
	pickTime("effeTime", null);
	$("#typeId").val('approves');
	//加载申请借阅类型
	loadApplyType(1);
	setFormToken();
	document.forms[1].reset();
	$("#approveId").val("");
	$("#check").val("'"+patientId+"',");
	//查询该记录是否有保存未提交的记录
	$.ajax({
		type:'post',
		url:path+'/approve/approveListByAppleStatus?patientId='+patientId+'&type=1',
		dataType:'json',
		success:function(data){
			if(data != null || data != ''){
				$("#approveId").val(data.id);
				$("#effeTime").val(data.effeTime);
				$("#applyType").val(data.applyType);
				$("#effeDays").val(data.effeDays);
				$("#applyReason").val(data.applyReason);
			}
		}
	})
}

/**
 * 批量申请借阅
 */
function borrowings(){
	pickTime("effeTime", null);
	$("#typeId").val('approves');
	//加载申请借阅类型
	loadApplyType(1);
	$("#name1").val("");
	setFormToken();
	document.forms[1].reset();
	$("#approveId").val("");
	getChecked();
	if($("#checks").val() == ''){
		//搜索框值不能为空
		var flag = true;
		$("#block").children().find('[class=inputDiv]').find('input').each(function(){
			var val = $(this).val();
			if(val == ''){
				flag = false;
				return false;
			}
		})
		var isInputValue = getInputValue();
		if(!flag && isInputValue==''){
			toastr.warning("搜索条件不能为空!");
		}else {
			getSql();
			var sql = $("#sql").val();
			if (sql != '') {
				var rows = $("#rows").val();
				if(rows != '' && rows <= 5000){
					if (confirm('没有选中，您确定要按搜索栏条件申请?')) {
						$.ajax({
							type: 'post',
							url: path + '/template/getPatientIdsBySql',
							data: {sql: sql},
							dataType: 'json',
							async:false,
							success: function (data) {
								if (data != null) {
									$("#patientIds").val(data);
								}
							}
						})
						$('#borrowings').attr("data-toggle", "modal");
						$('#borrowings').attr("data-target", "#myModal1");
					}else{
						$('#borrowings').removeAttr("data-toggle", "modal");
						$('#borrowings').removeAttr("data-target", "#myModal1");
					}
				}else{
					toastr.warning("为了用户体验，限制批量操作不超过5000条数据!");
				}
			} else {
				toastr.warning("至少选中一条!");
			}
		}
	}else{
		$('#borrowings').attr("data-toggle", "modal");
		$('#borrowings').attr("data-target", "#myModal1");
	}
}

/**
 * 单个下载申请
 * @param patientId
 */
function downBorrowing(patientId){
	pickTime("effeTime", null);
	$("#typeId").val('loads');
	//加载申请借阅类型
	loadApplyType(2);
	setFormToken();
	document.forms[1].reset();
	$("#approveId").val("");
	$("#check").val("'"+patientId+"',");
	//查询该记录是否有保存未提交的记录
	$.ajax({
		type:'post',
		url:path+'/approve/approveListByAppleStatus?patientId='+patientId+'&type=1',
		dataType:'json',
		success:function(data){
			if(data != null || data != ''){
				$("#approveId").val(data.id);
				$("#effeTime").val(data.effeTime);
				$("#applyType").val(data.applyType);
				$("#effeDays").val(data.effeDays);
				$("#applyReason").val(data.applyReason);
			}
		}
	})
}

/**
 * 批量下载借阅
 */
function downBorrowings(){
	pickTime("effeTime", null);
	$("#typeId").val('loads');
	//加载申请借阅类型
	loadApplyType(2);
	$("#name1").val("");
	setFormToken();
	document.forms[1].reset();
	$("#approveId").val("");
	getChecked();
	if($("#checks").val() == ''){
		//搜索框值不能为空
		var flag = true;
		$("#block").children().find('[class=inputDiv]').find('input').each(function(){
			var val = $(this).val();
			if(val == ''){
				flag = false;
				return false;
			}
		})
		var isInputValue = getInputValue();
		if(!flag && isInputValue==''){
			toastr.warning("搜索条件不能为空!");
		}else {
			getSql();
			var sql = $("#sql").val();
			if (sql != '') {
				var rows = $("#rows").val();
				if(rows != '' && rows <= 5000){
					if (confirm('没有选中，您确定要按搜索栏条件申请?')) {
						$.ajax({
							type: 'post',
							url: path + '/template/getPatientIdsBySql',
							data: {sql: sql},
							dataType: 'json',
							async:false,
							success: function (data) {
								if (data != null) {
									$("#patientIds").val(data);
								}
							}
						})
						$('#downBorrowings').attr("data-toggle", "modal");
						$('#downBorrowings').attr("data-target", "#myModal1");
					}else{
						$('#downBorrowings').removeAttr("data-toggle", "modal");
						$('#downBorrowings').removeAttr("data-target", "#myModal1");
					}
				}else{
					toastr.warning("为了用户体验，限制批量操作不超过5000条数据!");
				}
			} else {
				toastr.warning("至少选中一条!");
			}
		}
	}else{
		$('#downBorrowings').attr("data-toggle", "modal");
		$('#downBorrowings').attr("data-target", "#myModal1");
	}
}

/**
 * 模态框保存操作
 */
function save(){
	var typeId = $("#typeId").val();
	saveMethod(1,"保存",typeId);
}

/**
 * 模态框提交操作
 */
function add(){
	var typeId = $("#typeId").val();
	saveMethod(2,"提交",typeId);
}

//封装模态框保存公共方法，applyState:提交状态1保存未提交2已提交.msg:操作后提示信息
function saveMethod(applyState,msg,typeId){
	if($("#effeTime").val() != ''){
		var patientIds = $("#check").val();
		if(patientIds == '' || patientIds == undefined) {
			patientIds = $("#checks").val();
		}
		if(patientIds == '' || patientIds == undefined){
			patientIds = $("#patientIds").val();
		}
		if (patientIds != '' || patientIds == undefined) {
			//过滤已可查阅的patientId集合;
			patientIds = powerPotient(patientIds,false,typeId);
			if(patientIds != ''){
				patientIds = patientIds.substring(0, patientIds.length - 1);
				var id = $("#approveId").val();
				var effeTime = $("#effeTime").val();
				var effeDays = $("#effeDays").val();
				var applyType = $("#applyType").val();
				var applyReason = $("#applyReason").val();
				if (applyReason==""){
					return toastr.warning("申请理由不能为空!");
				}
				$.ajax({
					type:'post',
					url:path+'/approve/addApplyApprove',
					data:{id:id,applyState:applyState,effeTime:effeTime,effeDays:effeDays,applyType:applyType,applyReason:applyReason,patientIds:patientIds,formToken:$("#formToken").val()},
					dataType:'json',
					success:function(data){
						if(data!=null && data.code == 0){
							if(applyState == 1){
								toastr.success("保存成功!");
							}else if(applyState == 2){
								toastr.success("申请成功，目前审核中，请耐心等待!");
								document.forms[1].reset();
							}
							$('#myModal1').modal('hide');
							reLoadTable();
						}else{
							toastr.error(data.msg);
						}
					}
				})
			}else{
				toastr.warning("没有可申请的记录")
			}
		} else {
			toastr.warning("请至少选中一条记录")
		}
	}else{
		toastr.warning("有效时间不能为空!");
		$("#effeTime").focus();
	}
}

//单个锁定
function lock(patientId){
	patientId = "'"+patientId+"'";
	lockMethod(patientId);
}

//批量锁定
function blocks(){
	var locks = $("#locks").val();
	getChecked();
	var checks = $("#checks").val();
	if(checks != ''){
		//过滤已锁定的
		if(locks != ''){
			locks = locks.split(",");
			for (var i = 0; i < locks.length; i++) {
				if(locks[i] != '' && checks.indexOf(locks[i]) != -1){
					checks = checks.replace(locks[i]+",","");
				}
			}
		}
		if(checks != ''){
			checks = checks.substring(0,checks.length-1);
			lockMethod(checks);
		}else{
			toastr.warning("没有可锁定的对象！")
		}
	}else{
		if($("#rows").val() > 1000){
			toastr.warning("数据量大,暂支持1000条内数据批量锁定");
		}else {
			getSql();
			var sql = $("#sql").val();
			if (sql != '') {
				Common.confirm({
					title: "提示",
					message: "没有选中，您确定要按搜索栏条件锁定?",
					operate: function (reselt) {
						if (reselt) {
							$.ajax({
								type: 'post',
								url: path + '/template/getPatientIdsBySql',
								data: {sql: sql},
								dataType: 'json',
								success: function (data) {
									if (data != null) {
										var patientIds = data;
										if (locks != '') {
											locks = locks.split(",");
											for (var i = 0; i < locks.length; i++) {
												if (locks[i] != '' && patientIds.indexOf(locks[i]) != -1) {
													patientIds = patientIds.replace(locks[i] + ",", "");
												}
											}
										}
										if (patientIds != '') {
											patientIds = patientIds.substring(0, patientIds.length - 1);
											lockMethod(patientIds);
										}
									} else {
										toastr.warning("没有可锁定的对象！")
									}
								}
							})
						}
					}
				})
			} else {
				toastr.warning("搜索内容不能为空!")
			}
		}
	}
}

//解锁
function unlock(patientId){
	$.ajax({
		type:'post',
		url:path+'/template/updateLockByPatientId?patientId='+patientId,
		dataType:'json',
		success:function(data){
			if(data.code == 0){
				toastr.success("解锁成功!");
				getLockPatientIds();
				reLoadTable();
			}else{
				toastr.error("解锁失败！")
			}
		}
	})
}

//批量解锁
function unlocks(){
	var locks = $("#locks").val();
	getChecked();
	var checks = $("#checks").val();
	if(checks != ''){
		//过滤已锁定的
		if(locks != ''){
			locks = locks.split(",");
			var newChecks = "";
			for (var i = 0; i < locks.length; i++) {
				if(locks[i] != '' && checks.indexOf(locks[i]) != -1){
					newChecks += locks[i]+",";
				}
			}
			if(newChecks != ''){
				newChecks = newChecks.substring(0,newChecks.length-1);
				//解锁的方法
				unlocksMethods(newChecks);
			}else{
				toastr.warning("没有可解锁的对象!");
			}
		}else{
			toastr.warning("没有可解锁的对象!");
		}
	}else{
		if($("#rows").val() > 1000){
			toastr.warning("数据量大,暂支持1000条内数据批量解锁");
		}else {
			getSql();
			var sql = $("#sql").val();
			if (sql != '') {
				Common.confirm({
					title: "提示",
					message: "没有选中，您确定要按搜索栏条件批量解锁?",
					operate: function (reselt) {
						if (reselt) {
							$.ajax({
								type: 'post',
								url: path + '/template/getPatientIdsBySql',
								data: {sql: sql},
								dataType: 'json',
								success: function (data) {
									if (data != null) {
										var patientIds = data;
										if (locks != '') {
											locks = locks.split(",");
											for (var i = 0; i < locks.length; i++) {
												if (locks[i] != '' && patientIds.indexOf(locks[i]) == -1) {
													patientIds = patientIds.replace(locks[i] + ",", "");
												}
											}
										}
										if (patientIds != '') {
											patientIds = patientIds.substring(0, patientIds.length - 1);
											//批量解锁的方法
											unlocksMethods(patientIds);
										}
									} else {
										toastr.warning("没有可解锁的对象！")
									}
								}
							})
						}
					}
				})
			} else {
				toastr.warning("搜索内容不能为空!")
			}
		}
	}
}

//封装锁定方法
function lockMethod(patientId){
	Common.confirm({
		title: "提示",
		message: "请确认是否锁定该数据?",
		operate: function (reselt) {
			if (reselt) {
				$.ajax({
					type: 'post',
					url: path + '/template/addLockByPatientId',
					data: {patientIds: patientId},
					dataType: 'json',
					success: function (data) {
						if (data.code == 0) {
							toastr.success("锁定成功!");
							getLockPatientIds();
							reLoadTable();
						} else {
							toastr.error("锁定失败！")
						}
					}
				})
			}
		}
	})
}

//封装批量解锁方法
function unlocksMethods(patientIds){
	$.ajax({
		type:'post',
		url:path+'/template/updateLockByPatientIds',
		data:{patientIds:patientIds},
		async:false,
		dataType:'json',
		success:function(data){
			if(data.code == 0){
				toastr.success("解锁成功!");
				getLockPatientIds();
				reLoadTable();
			}else{
				toastr.error("解锁失败！")
			}
		}
	})
}

//查询被锁定的patienId集合
function getLockPatientIds(){
	$("#locks").val("");
	$.ajax({
		type:'post',
		url:path+'/emrLock/getLoctPatientIds',
		dataType:'json',
		async:false,
		success:function(data){
			if(data != null && data != ''){
				$("#locks").val(data);
			}
		}
	})
}

//过滤下载，导出pdf，查看详情的patientId集合:typeId:已借阅审批病案id集合或已下载审批病案id集合
function powerPotient(patientIds,flag,typeId){
	//有权限的过滤
	//通过且未过期的可查看的
	var approves = $("#"+typeId).val();
	if(approves != '') {
		var patientIdList = patientIds.split(",");
		var approveList = approves.split(",");
		patientIds = '';
		for (var i = 0; i < patientIdList.length; i++) {
			if(patientIdList[i] != ''){
				//定义是否包含
				var flagPatinetId = false;
				for (var j = 0; j < approveList.length; j++) {
					//包含
					if (approveList[j] != '' && patientIdList[i].indexOf(approveList[j]) != -1) {
						flagPatinetId = true;
						break;
					}
				}
				if(flag){
					//系统管理员放过
					var roleId = $("#roleId").val();
					if(roleId == 0){
						patientIds  +=	patientIdList[i]+",";
					}else{
						if(flagPatinetId){
							patientIds  +=	patientIdList[i]+",";
						}
					}
				}else{
					if(!flagPatinetId){
						patientIds  +=	patientIdList[i]+",";
					}
				}
			}
		}
	}else{
		var downloadRecord  = $("#downloadRecord").val();
		if(downloadRecord != 1 && flag){
			patientIds = '';
		}
	}
	if(patientIds != ''){
		var patientIdList = patientIds.split(",");
		//锁定的
		var locks = $("#locks").val();
		if(locks != '') {
			var lockList = locks.split(",");
			for (var i = 0; i < patientIdList.length; i++) {
				for (var j = 0; j < lockList.length; j++) {
					if (lockList[j] != '' && patientIdList[i] == lockList[j]) {
						//包含
						patientIds = patientIds.replace(patientIdList[i]+',',"");
					}
				}
			}
		}
	}
	return patientIds;
}
/*********************************************************工具*************************************************************/
//格式化时间
function formatTime(datetime, fmt) {
	if (datetime == null || datetime == 0) {
		return "";
	}
	if (parseInt(datetime) == datetime) {
		if (datetime.length == 10) {
			datetime = parseInt(datetime) * 1000;
		} else if (datetime.length == 13) {
			datetime = parseInt(datetime);
		}
	}
	datetime = new Date(datetime.substring(0,datetime.replace(/-/g,'/').replace(/T|Z/g,' ').trim().length-11));
	var o = {
		"M+" : datetime.getMonth() + 1, //月份
		"d+" : datetime.getDate(), //日
		"h+" : datetime.getHours(), //小时
		"m+" : datetime.getMinutes(), //分
		"s+" : datetime.getSeconds(), //秒
		"q+" : Math.floor((datetime.getMonth() + 3) / 3), //季度
		"S" : datetime.getMilliseconds()
		//毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (datetime.getFullYear() + "")
			.substr(4 - RegExp.$1.length));
	for ( var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1,
				(RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k])
					.substr(("" + o[k]).length)));
	return fmt;
}
