$(function () {
    //百叶窗风格
    $('.collapse').collapse({
        toggle: false
    })
    //加载表格
    freshTableSouth();
    //加载时间控件1
    initDateInput(1);
    //加载时间控件2
    initDateInput(2);
    //加载性别
    loadSex();
    //加载科室
    loadDept();
    //加载转归情况
    loadDiagStatus();
    //权限控制按钮
    permissionControlButton();
});

//加载性别
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" id="' + data[i].name + '" name="sex" value="' + data[i].name + '" class="sexInput"><label class="checkBoxClass" for="' + data[i].name + '">' + data[i].name + '</label></div>';
                    } else {
                        html += '<div class="col-sm-2 radioDiv">'
                            + '<input type="radio" id="' + data[i].name + '"  name="sex" value="' + data[i].name + '" class="sexInput"><label class="checkBoxClass" for="' + data[i].name + '">' + data[i].name + '</label></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 != '') {
                        var name = data[i].name;
                        var py = makePy(name);
                        var pingyin = ConvertPinyin(name);
                        html += '<option data-tokens="' + name + '|' + py[0] + '|' + pingyin + '" value="' + name + '">' + name + '</option>';
                    }
                }
                $("#dis_dept").append(html);
                $("#dis_dept").selectpicker('refresh');
            }
        }
    })
}

//加载科室
function loadDeptDefault(defaultDeptName){
    $.ajax({
        type:'get',
        url:path+'/commom/getDept',
        dataType:'json',
        success:function (data) {
            if(null != data){
                $("#disDept").empty();
                var html = '<option value="">请选择</option>';
                for (var i = 0; i < data.length; i++) {
                    if (data[i].name != '' && data[i].name == defaultDeptName) {
                        var name = data[i].name;
                        var py = makePy(name);
                        var pingyin = ConvertPinyin(name);
                        html += '<option data-tokens="' + name + '|' + py[0] + '|' + pingyin + '" value="' + name + '" selected>' + name + '</option>';
                    } else {
                        var name = data[i].name;
                        var py = makePy(name);
                        var pingyin = ConvertPinyin(name);
                        html += '<option data-tokens="' + name + '|' + py[0] + '|' + pingyin + '" value="' + name + '">' + name + '</option>';
                    }
                }
                $("#disDept").append(html);
                $("#disDept").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';
var commomtable1 = 'commomtable1';

//拼接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 = searchName.replace(/\*/g, "_");
                                whereNames += commomtable + "." + name + " 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 = searchName.replace(/\*/g, "_");
                                whereNames += commomtable + "." + name + " 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(/\*/g, "_");
                whereNames += commomtable + "." + name + " 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 = 'main_diag_code';
            whereNames += commomtable + "." + name + " LIKE '%" + $("#diag_code").val() + "%' AND ";
        }
        //全部诊断
        if($("#all_diag_name").val() != ''){
            name = 'diag_name';
            whereNames += "t_diag."+name+" LIKE '%"+$("#all_diag_name").val()+"%' AND ";
        }
        //其他诊断
        if($("#other_diag_name").val() != ''){
            name = 'other_diag_name';
            whereNames += commomtable + "." + name + " LIKE '%" + $("#other_diag_name").val() + "%' AND ";
        }
        //病理诊断
        if($("#pathology_name").val() != ''){
            name = 'pathology_name';
            whereNames += commomtable + "." + name + " LIKE '%" + $("#pathology_name").val() + "%' AND ";
        }
        //损伤中毒
        if($("#poisoning_name").val() != ''){
            name = 'poisoning_name';
            whereNames += commomtable + "." + name + " LIKE '%" + $("#poisoning_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 ";
        }
        //主诊编码范围
        if ($("#diag_code1").val() != '' && $("#diag_code2").val() != '') {
            name = 'main_diag_code';
            whereNames += commomtable + "." + name + " BETWEEN '" + $("#diag_cod下·下·e1").val() + "' AND '" + $("#diag_code2").val() + "' AND ";
        }
        //手术编码范围
        if ($("#operate_code1").val() != '' && $("#operate_code2").val() != '') {
            name = 'operate_code';
            whereNames += "t_operate." + name + " BETWEEN '" + $("#operate_code1").val() + "' AND '" + $("#operate_code2").val() + "' AND ";
        }
        //其他诊断编码范围
        if ($("#other_diag_name1").val() != '' && $("#other_diag_name2").val() != '') {
            name = 'other_diag_name';
            whereNames += commomtable + "." + name + " BETWEEN '" + $("#other_diag_name1").val() + "' AND '" + $("#other_diag_name2").val() + "' AND ";
        }
        //科主任
        if ($("#dept_director").val() != '') {
            name = 'dept_director';
            whereNames += commomtable1 + "." + name + " LIKE '%" + $("#dept_director").val() + "%' AND ";
        }
        //主任(副主任)
        if ($("#director").val() != '') {
            name = 'director';
            whereNames += commomtable1 + "." + name + " LIKE '%" + $("#director").val() + "%' AND ";
        }
        //住院医师
        if ($("#admiss_doctor").val() != '') {
            name = 'admiss_doctor';
            whereNames += commomtable1 + "." + name + " LIKE '%" + $("#admiss_doctor").val() + "%' AND ";
        }
        var userName = "'" + $("#userName").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 + ' and emr_apply_approve.apply_type != 3 ' +
            ' left join emr_apply_approve emr_apply_approve1 on ' + commomtable + '.patient_id = emr_apply_approve1.patient_id \n' +
            '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';
        //拼接诊断表
        //全部诊断
        if($("#all_diag_name").val() != ''){
            fromTableNames += ' left join t_diag on '+commomtable+'.patient_id=t_diag.patient_id';
        }
        if ($("#admiss_doctor").val() != '' || $("#director").val() != '' || $("#dept_director").val() != '') {
            fromTableNames += ' left join ' + commomtable1 + ' on ' + commomtable1 + '.patient_id = ' + commomtable + '.patient_id';
        }
        //拼接手术表
        var operFlag = false;
        $(".operTable").each(function () {
            if ($(this).val() != '' && $(this).val() != 'on') {
                operFlag = true;
                return false;
            }
        })
        if (operFlag || $("#operate_code1").val() != '' || $("#operate_code2").val() != '') {
            otherTable = 't_operate';
            fromTableNames += ' left join ' + otherTable + ' on ' + commomtable + '.patient_id = ' + otherTable + '.patient_id';
        }
        //拼接主治医生
        if ($("#attending").val() != '') {
            name = 'attending';
            whereNames += commomtable + "." + name + " LIKE '%" + $("#" + name).val() + "%' AND ";
        }
        //限手术
        var isOper = $("#isOper").val();
        if (isOper != '' && isOper == 1) {
            name = 'is_oper';
            whereNames += commomtable + "." + name + " = '1' AND ";
        }
        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);
        }
        if (whereNames == ' where ') {
            var orderBys = " ORDER BY " + commomtable + ".inpatient_no," + commomtable + ".admiss_times";
            var sql = selectNames + fromTableNames;
            $("#sql").val(sql);
            $("#orderBys").val(orderBys);
        }
        //console.log(sql);
    } else {
        $("#sql").val("");
    }
}

function freshTableSouth(){
    var powerMenus = $("#powerMenus").val();
    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 = [];
    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';
                    }else{
                        map['field'] = fields[i];
                    }
                    fieldCns += fields[i] + ",";
                }
                if(dateFields.indexOf(fields[i]) != -1){
                    map['formatter'] = function (value, row, index) {return formatTime(value,'yyyy-MM-dd')};
                }
                columns.push(map);
            }
        }
        $("#fieldCns").val(fieldCns);
    }
    var map1 = {};
    map1['title'] = '权限';
    map1['field'] = 'Button';
    map1['align'] = 'center';
    map1['formatter'] = 'AddFunctionAltyFont';
    columns.push(map1)
    var sql = $("#sql").val();
    if(sql == ''){
        sql = initSql;
    }
    var orderBys = $("#orderBys").val();
    sql += orderBys;
    //console.log(sql)
    var flag = $("#showPrint").val();
    //固定列标识
    var mixFlag = false;
    if(flag == 1){
        flag = true;
    }else{
        flag = false;
        mixFlag = true;
    }
    //生成用户数据
    $('#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,                       //每页的记录行数（*）
        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/cutomSearchTableSouth',//排序方式
        queryParams: function (params) {
            return{
                sql:sql,
                limit : params.limit, // 每页显示数量
                offset : params.offset, // SQL语句起始索引
                page : (params.offset / params.limit) + 1 //当前页码
            }
        },
        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){
            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 borrowingOper = row.borrowingOper;
            if (null != borrowingOper && borrowingOper == 1) {
                window.open(returnShowDetailUrl(row.patientId));
            }else {
                toastr.warning("不可查看,必须申请通过!")
            }
        },
    })
}

//定义查看详情的请求地址url
function returnShowDetailUrl(patientId) {
    return path + '/font/showRecordFontSouth?patientId=' + patientId;
}

/**
 * 单个借阅申请
 * @param patientId
 */
function borrowingFont(patientId){
    pickTime("effeTime", null);
    $("#typeId").val('approves');
    $("#checks").val("'"+patientId+"',");
    $("#approveId").val("");
    setFormToken();
}

/**
 * 借阅申请列表提交
 */
function addApprove() {
    if($("#effeTime").val() != ''){
        var patientIds = $("#checks").val();
        if(patientIds != '' && patientIds != undefined) {
            var id = $("#approveId").val();
            var effeTime = $("#effeTime").val();
            var effeDays = $("#effeDays").val();
            var applyType = 4;
            var applyState = 2;
            var applyReason = $("#applyReason").val();
            $.ajax({
                type:'post',
                url:path+'/font/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){
                        toastr.success("申请成功，目前审核中，请耐心等待!");
                        $('#myModal1').modal('hide');
                        reLoadFontTable();
                    }else{
                        toastr.error(data.msg);
                    }
                }
            })
        }
    } else {
        toastr.warning("有效时间不能为空!");
        $("#effeTime").focus();
    }
}

/**
 * 列表行‘操作’按钮
 * @param value
 * @param row
 * @param index
 * @returns {string}
 * @constructor
 */
function AddFunctionAltyFont(value, row, index) {
    var borrowingOper = row.borrowingOper;
    var str = '';
    if (borrowingOper == 1) {
        str = '<a type="button" href="' + path + '/font/showRecordFontSouth?patientId=' + row.patientId + '" class="btn btn-danger TableView btn-sm" target="_blank">查看详情</a>';
    }
    if (borrowingOper == 2) {
        str = '<p style="color:grey">正在等待审批</p>';
    }
    if (borrowingOper == 0) {
        var patientId = "'" + row.patientId + "'";
        str = '<button type="button" class="btn btn-primary TableView btn-sm" onclick="borrowingFont('+patientId+')"  data-toggle="modal" data-target="#myModal1">借阅申请</button>';
    }
    return str;
}

/**
 * 刷新表格
 */
function reLoadFontTable(){
    $("#mytab").bootstrapTable('refresh',path+'/template/cutomSearchTableSouth');
    $('#mytab').bootstrapTable('selectPage', pageNumber);
    $("#checks").val("");
}

//搜索功能
function search() {
    var startTime1 = $("#startTime1").val();
    var endTime1 = $("#endTime1").val();
    var startTime2 = $("#startTime2").val();
    var endTime2 = $("#endTime2").val();
    var age1 = $("#age1").val();
    var age2 = $("#age2").val();
    var diag_code1 = $("#diag_code1").val();
    var diag_code2 = $("#diag_code2").val();
    var operate_code1 = $("#operate_code1").val();
    var operate_code2 = $("#operate_code2").val();
    var other_diag_name1 = $("#other_diag_name1").val();
    var other_diag_name2 = $("#other_diag_name2").val();
    if ((age1 != '' && age2 == '') || (age1 == '' && age2 != '')) {
        toastr.warning("请输入完整年龄段!");
        return false;
    }
    if ((startTime1 != '' && endTime1 == '') || (startTime1 == '' && endTime1 != '')) {
        toastr.warning("请输入完整的入院日期时间段!");
        return false;
    }
    if ((startTime2 != '' && endTime2 == '') || (startTime2 == '' && endTime2 != '')) {
        toastr.warning("请输入完整的出院日期时间段!");
        return false;
    }
    if ((diag_code1 != '' && diag_code2 == '') || (diag_code1 == '' && diag_code2 != '')) {
        toastr.warning("请输入完整的主诊编码范围!");
        return false;
    }
    if ((operate_code1 != '' && operate_code2 == '') || (operate_code1 == '' && operate_code2 != '')) {
        toastr.warning("请输入完整的手术编码范围!");
        return false;
    }
    if ((other_diag_name1 != '' && other_diag_name2 == '') || (other_diag_name1 == '' && other_diag_name2 != '')) {
        toastr.warning("请输入完整的其他诊断编码范围!");
        return false;
    }
    getSql();
    freshTableSouth();
}

/*****************************************输入框边输入内容边搜索功能方法*************************************************/
//级联病案号，且长度超过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 getDiagNameContents(id) {
    var code = "";
    var name = document.getElementById(id).value;
    if (name.length > 2) {
        var ajax = new XMLHttpRequest();
        var url = path + "/commom/getDiagCodeContents?code=" + code + "&name=" + name;
        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 {
        return;
    }
    clearContent('main_diag_name')
}

//级联手术编码
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;
    }
}

//级联手术名称
function getOperateNameContents(id) {
    var name = document.getElementById(id).value;
    var code = "";
    if (name.length > 2) {
        var ajax = new XMLHttpRequest();
        var url = path + "/commom/getOperateCodeContents?code=" + code + "&name=" + name;
        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 td4 = document.createElement("td");
        tr.setAttribute("bgcolor", "#FFFAFA");
        tr.setAttribute("border", "0");
        if (id == 'main_diag_name'){
            td1.innerHTML = json[key];
            tr.appendChild(td1);
        } else {
            if (id == 'inpatient_no' || id == 'diag_code' || id == 'operate_code') {
                td2.innerHTML = key;
            } else {
                td2.innerHTML = json[key];
                td4.innerHTML = key;
            }
            tr.appendChild(td2);
            tr.appendChild(td4);
        }
        document.getElementById(id + "Content").appendChild(tr);
        tr.onmouseover = function () {
            this.className = 'mouseOver';
            document.getElementById(id).value = $(this).children("td").eq(0).html();
        };
        tr.onmouseout = function () {
            this.className = 'mouseOut';
        };
        tr.onclick = function () {
            clearContent(id);
        }
    }
}

//清楚内容方法
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";
}



