$(function () {
    //权限控制按钮
    permissionControlButton();
});

//权限控制按钮
function permissionControlButton() {
    var show = $("#showRecord").val();
    var load = $("#downloadRecord").val();
    //批量借阅申请权限判断
    if (show == 1){
        $("#borrowingsBox").hide();
    } else {
        $("#borrowingsBox").show();
    }
    //批量下载申请权限判断
    if (load == 1){
        $("#downBorrowingsBox").hide();//批量下载申请按钮不显示
        $("#downBorrowingBox").show();//下载按钮显示
    } else {
        $("#downBorrowingsBox").show();//批量下载申请按钮显示
        $("#downBorrowingBox").hide();//下载按钮不显示
    }
}

//时间正则验证
var date_format= /^(\d{4})-(0\d{1}|1[0-2])-(0\d{1}|[12]\d{1}|3[01])$/;
//时间格式列名集合
//时间格式属性名集合
var commomtable = 'commomtable';
//拼接sql
function getSql() {

    //表头集合
    var tableThNames = '';
    //select语句字符串
    var selectNames = '';
    //from语句字符串
    var fromTableNames = '';
    //数据字典转换语句
    var dictionaryConvertStr = '';
    //on语句字符串
    var onNames = '';
    //公共表名
    var basicTable = '';
    //查询字段数组
    var selectArray = new Array();
    var array = new Array();
    //选中个数
    var checks = 0;
    //拼接显示字段
    $("input[class=check]").each(function () {
        //拼接表头集合
        tableThNames += $(this).next('span').text() + ",";
        var val = $(this).val();
        //添加不重复的表名
        if ($.inArray(val.split(".")[0], array) < 0) {
            if (val.split(".")[0] != commomtable) {
                array.push(val.split(".")[0]);
            }
        }
        //转换数据字典
        if (val == 't_diag.dis_thing') {
            //转归情况
            val = 't_dictionary_1.NAME AS dis_thing';
            dictionaryConvertStr += " LEFT JOIN dbo.emr_dictionary AS t_dictionary_1 ON dbo.t_diag.dis_thing = t_dictionary_1.CODE AND t_dictionary_1.parent_id = 'dis_diag_status'";
        }
        if (val == 't_operate.operate_class') {
            //手术级别
            val = 't_dictionary_2.NAME AS operate_class';
            dictionaryConvertStr += " LEFT JOIN dbo.emr_dictionary AS t_dictionary_2 ON t_operate.operate_class = t_dictionary_2.CODE AND t_dictionary_2.parent_id = 'operate_class'";
        }
        if (val == 't_operate.cut') {
            //切口愈合等级
            val = 't_dictionary_3.NAME AS cut';
            dictionaryConvertStr += " LEFT JOIN dbo.emr_dictionary AS t_dictionary_3 ON t_operate.cut = t_dictionary_3.CODE AND t_dictionary_3.parent_id = 'cut_heal_grade'";
        }
        if (val == 't_operate.anaesthesia_type') {
            //麻醉方式
            val = 't_dictionary_4.NAME AS anaesthesia_type';
            dictionaryConvertStr += " LEFT JOIN dbo.emr_dictionary AS t_dictionary_4 ON t_operate.anaesthesia_type = t_dictionary_4.CODE AND t_dictionary_4.parent_id = 'anaesthesia'";
        }
        /*if (val == 't_operate.ChosSurg') {
            //是否择期手术
            val = 't_dictionary_5.NAME AS chossurg';
            dictionaryConvertStr += " LEFT JOIN dbo.emr_dictionary AS t_dictionary_5 ON t_operate.ChosSurg = t_dictionary_5.CODE AND t_dictionary_5.parent_id = 'whether'";
        }*/
        if (val == 't_baby.babySex') {
            //婴儿性别
            val = 't_dictionary_6.NAME AS babySex';
            dictionaryConvertStr += " LEFT JOIN dbo.emr_dictionary AS t_dictionary_6 ON t_baby.sex = t_dictionary_6.CODE AND t_dictionary_6.parent_id = 'sex_code'";
        }
        if (val == 't_baby.childbirth_mothed') {
            //分娩结果
            val = 't_dictionary_7.NAME AS childbirthMothed';
            dictionaryConvertStr += " LEFT JOIN dbo.emr_dictionary AS t_dictionary_7 ON t_baby.childbirth_mothed = t_dictionary_7.CODE AND t_dictionary_7.parent_id = 'childbirthResult_code'";
        }
        if (val == 't_baby.diag_type') {
            //婴儿转归
            val = 't_dictionary_8.NAME AS diagType';
            dictionaryConvertStr += " LEFT JOIN dbo.emr_dictionary AS t_dictionary_8 ON t_baby.diag_type = t_dictionary_8.CODE AND t_dictionary_8.parent_id = 'childStatus_code'";
        }
        if (val == 't_baby.breathing') {
            //婴儿呼吸
            val = 't_dictionary_9.NAME AS breathing';
            dictionaryConvertStr += " LEFT JOIN dbo.emr_dictionary AS t_dictionary_9 ON t_baby.breathing = t_dictionary_9.CODE AND t_dictionary_9.parent_id = 'breath_code'";
        }
        if (val == 't_diag.diag_type') {
            //诊断类型
            val = 't_dictionary_10.NAME AS diagType';
            dictionaryConvertStr += " LEFT JOIN dbo.emr_dictionary AS t_dictionary_10 ON t_diag.diag_type = t_dictionary_10.CODE AND t_dictionary_10.parent_id = 'dis_diag_type'";
        }
        if (push_unique(val, selectArray)){
            selectArray.push(val);
        }
        if ($(this).is(':checked')) {
            checks++;
        }
    })
    //拼接select语句
    for (var i = 0; i < selectArray.length; i++){
        //拼接select语句
        selectNames += selectArray[i] + ",";
    }
    //where语句字符串
    var whereNames = ' where ';
    //拼接条件前括号
    for (var i = 0; i < checks; i++) {
        whereNames += "(";
    }
    //多表查询的情况
    if (array.length != 0) {
        basicTable = commomtable + '.patient_id = ';
    }
    var age = '';
    var age_month = '';
    var age_day = '';
    var inpatientNo = '';
    $("#block").children().find('div').each(function () {
        var val = $(this).children().val();
        var className = $(this).children().attr('class');
        if (className == 'select2') {
            //like 的情况
            var isLike = whereNames.substring(whereNames.length - 5, whereNames.length);
            if (isLike == 'LIKE ') {
                if (val.indexOf('*') != -1) {
                    whereNames += "'" + val.replace('*', '_') + "') ";
                } else {
                    whereNames += "'%" + val + "%') ";
                }
            } else {
                whereNames += "'" + val + "') ";
            }
        } else if (className == 'select21') {
            //双选的情况
            var select22Val = $(this).children().eq(2).val();
            //删除前面等号
            whereNames = whereNames.substring(0, whereNames.length - 3);
            //验证时间格式
            if (date_format.test(val)) {
                val += ' 00:00:00';
                select22Val += ' 23:59:59';
                whereNames += "between '" + val + "' and '" + select22Val + "') ";
            } else {
                //数字
                if(inpatientNo != '' && inpatientNo == commomtable+'.inpatient_no'){
                    whereNames += "between '" + val + "' and '" + select22Val + "'))";
                } else if(age != '' && age == commomtable+'.age'){
                    whereNames += "between " + val + " and " + (select22Val-1) + " OR ("+commomtable+".age = "+select22Val+" AND "+commomtable+".age_month = 0 AND "+commomtable+".age_day = 0))) ";
                }else if(age_month != '' && age_month == commomtable+'.age_month'){
                    whereNames += "between " + val + " and " + (select22Val-1) + " AND "+commomtable+".age = 0 OR ("+commomtable+".age = 0 AND "+commomtable+".age_month = "+select22Val+" AND "+commomtable+".age_day = 0))) ";
                }else if(age_day != '' && age_day == commomtable+'.age_day'){
                    whereNames += "between " + val + " and " + select22Val + " AND "+commomtable+".age = 0 AND "+commomtable+".age_month = 0)) ";
                }else{
                    whereNames += "between " + val + " and " + select22Val + ") ";
                }
            }
        } else {
            //转换字段
            if (val == 't_baby.babySex') {
                val = 't_baby.sex';
            }
            if(val == commomtable+'.age'){
                age = val;
                whereNames += "(";
            }
            if(val == commomtable+'.age_month'){
                age_month = val;
                whereNames += "(";
            }
            if(val == commomtable+'.age_day'){
                age_day = val;
                whereNames += "(";
            }
            if (val == commomtable+'.inpatient_no') {
                inpatientNo = val;
                whereNames += "(";
            }
            if (val == 'and') {
                age = '';
                age_month = '';
                age_day = '';
                inpatientNo = '';
            }
            whereNames += val + ' ';
        }
    })
    for (var i = 0; i < array.length; i++) {
        //拼接from语句
        if (array.length != 0) {
            fromTableNames += ' left join ' + array[i] + " on " + basicTable + array[i] + ".patient_id"
            //查询结果均是诊断手术第一条
            if (array[i] == 't_diag') {
                fromTableNames += ' and t_diag.diag_no = 1 ';
            } else if (array[i] == 't_operate') {
                fromTableNames += ' and t_operate.operate_no = 1 ';
            }
        }
    }

    //拼接转换字典关联表语句
    if (array.length != 0) {
        fromTableNames += dictionaryConvertStr;
    }
    selectNames = selectNames.substring(0, selectNames.length - 1);
    $("#tableThNames").val(tableThNames);
    $("#englishFields").val(selectNames);
    $("#fromTableSql").val(fromTableNames);
    if (tableThNames != '') {
        var fieldCns = '';
        var fields = $("#fields").val().split(",");
        tableThNames = tableThNames.split(",");
        for (var i = 0; i < tableThNames.length; i++) {
            if (fields[i] != '') {
                //重新组织选项
                //转换RH
                if (fields[i] == 'RH') {
                    fields[i] = 'rh';
                }
                /*if (fields[i] == 'ChosSurg') {
                    fields[i] = 'chossurg';
                }*/
                fieldCns += fields[i] + ",";
            }
        }
        $("#fieldCns").val(fieldCns);
    }
	var blockVal = $("#block").text();
	if($.trim(blockVal) != '') {
		//搜索框值不能为空
		var flag = true;
		$("#block").children().find('[class=inputDiv]').find('input').each(function(){
			if($(this).val() == ''){
				flag = false;
				return false;
			}
		})
		if(flag){
            $("#whereSql").val(whereNames);
		}
	}
}

/**
 * 排重
 * @param val
 * @param selectArray
 * @returns {boolean}
 */
function push_unique(val, selectArray) {
	var i = selectArray.length;
    while (i--) {
        if (selectArray[i] === val) {
            return false; // 返回的这个 i 就是元素的索引下标，
        }
    }
    return true;
}
//搜索功能
function search(){
	var blockVal = $("#block").text();
	if($.trim(blockVal) != ''){
		//搜索框值不能为空
		var flag = true;
		$("#block").children().find('[class=inputDiv]').find('input').each(function(){
			if($(this).val() == ''){
				flag = false;
				return false;
			}
		})
		if(!flag){
			toastr.warning("不能为空值，如不需要请取消选项!");
		}else{
			getSql();
			freshTable();
		}
	}else{
		toastr.warning("搜索条件不能为空!");
	}
}
//查看详情
function showDetail(patientId){
	//隐藏模板选项
	parent.hideSelectDiv();
	window.location.href=path+"/commom/showRecordqf?patientId="+patientId;
}
/***********************************************搜索选项操作**************************************************************/
//百叶窗风格
$(function () {
	$('.collapse').collapse({
		toggle: false
	})
});
//全选全不选
$("#checkAll").change(function () {
	$('[class=check]:checkbox').prop('checked', $(this).prop("checked"));
});
$('.check').on('click', function () {
	/*//操作全选按钮
	if ($('.check').length == $('.check:checked').length) {
		$('#checkAll').prop('checked', true);
	} else {
		$('#checkAll').prop('checked', false);
	}*/
	//动态操作搜索栏
	var checked = $(this).is(':checked');
	var val = $(this).val();
	//字段类型
	var columnType = $(this).parent().prev('input').val();
	var idVal = val.replace(".","");
	//字段名name,sex
	var column = val.split(".")[1].replace(/(^\s*)|(\s*$)/g, "");
	var name = $(this).next('span').text();
	//需要模糊查询字段
	var options = '';
	var inputs = '';
	//判断条件等于、模糊等于，字符串等于模糊等于，其余等于
	if(columnType == '' || columnType == '1'){
		options = '<option value="=">等于</option><option value="LIKE">模糊等于</option>';
	}else{
		options = '<option value="=">等于</option>';
	}

	if(columnType != '' && columnType != '1' && columnType != '2' && columnType != '3'){
		//关联字典表
		var selectOptions = '';
		$.ajax({
			type:'post',
			url:path+'/dictionary/selectDictionaryByTypeCode',
			data:{typeCode:columnType},
			dataType:'json',
			success:function(data){
				if(data!= null){
					for (var i = 0;i < data.length;i++){
						if(column == 'babySex' || column == 'childbirth_mothed' || column == 'diag_type' ||  column == 'breathing' ||  column == 'dis_thing' || column == 'operate_class' ||  column == 'anaesthesia_type'){
							selectOptions += '<option value='+data[i].code+'>'+data[i].name+'</option>';
						}else{
							selectOptions += '<option value='+data[i].name+'>'+data[i].name+'</option>';
						}
					}
				}
				inputs ='<select class="select2">'+selectOptions+'</select>'
				dynamicCheck(checked,idVal,val,name,options,inputs);
			}
		})
	}else if(columnType == '3'){
		//时间格式
		inputs = '<input type="text" autocomplete="off" class="select21" name="tableName" id="startTime'+idVal+'" placeholder="起始值">'
			+ '<span style="float:left">-</span>'
			+ '<input type="text" autocomplete="off" class="select22" name="tableName" id="endTime'+idVal+'" placeholder="结束值">';
		dynamicCheck(checked,idVal,val,name,options,inputs);
	}else if(columnType == '2'){
		//整型
		inputs = '<input type="number" autocomplete="off" class="select21" min="0" name="tableName" placeholder="起始值" oninput="if(value.length>9)value=value.slice(0,9)">'
			+ '<span style="float:left">-</span>'
			+ '<input type="number" autocomplete="off" min="0" class="select22" name="tableName" placeholder="结束值" oninput="if(value.length>9)value=value.slice(0,9)">';
		dynamicCheck(checked,idVal,val,name,options,inputs);
	}else{
		inputs = '<input type="text" autocomplete="off" class="select2" name="tableName" maxlength="16">';
		dynamicCheck(checked,idVal,val,name,options,inputs);
	}
})
//封装动态添加删除方法
function dynamicCheck(checked,idVal,val,name,options,inputs){
	if(!checked){
		//如果删除的是最后一个，则连上一个的并且下拉框一起删除
		if($("#div"+idVal).text() == ($("#div"+idVal).parent().find('>div:last').text())){
			$("#div"+idVal).prev("div").children("div:last-child").remove();
		}
		$("#div"+idVal).remove();
		if(!$("#block").html().trim().length){
			$("#blockDiv").hide();
		}
	}else{
		//拼接
		var html = '<div id="div'+idVal+'" style="clear:both;" class="divClass">'
			+ '<div><input type="hidden" class="select0" value="'+val+'"></div>'
			+ '<div class="labelDiv"><label>'+name+'：</label></div>'
			+ '<div class="whereDiv"><select class="select1">'
			+  options
			+ '</select></div>'
			+ '<div class="inputDiv">'
			+ inputs
			+ '</div>'
			+ '</div>';
		//拼接条件查询
		var whereHtml = '<div class="whereDiv"><select class="select3"><option value="and">并且</option><option value="or">或</option></select></div>'
		$("div[class=divClass]:last").append(whereHtml);
		$("#block").append(html);
		$("#blockDiv").show();
		//加载时间控件
		initDateInput(idVal)
	}
}

//全不选
function checkCancel(array, nameArray) {
    if (array.length){
		for (var i = 0; i < array.length; i++){
            document.getElementById(array[i]).checked = false;
		}
	}
    if (nameArray.length){
        for (var i = 0; i < nameArray.length; i++){
            var nameVal = nameArray[i].replace(".","");
            if($("#div"+nameVal).text() == ($("#div"+nameVal).parent().find('>div:last').text())){
                $("#div"+nameVal).prev("div").children("div:last-child").remove();
            }
            $("#div"+nameVal).remove();
		}
	}
    $("#checks").val('');
}