//@ sourceURL=hospitalized.js

var LODOP; //声明为全局变量
//默认打印机下标
var printIndex = -1;


$(function () {
    initMaritalStatusSelect();
    initGenderSelect();


    //设置挂号窗口的高度
    var width = $('#confirmFee').css("width");
    var widthNum = parseInt(width);
    widthNum -= 24;
    $("#confirmFee").css("width", widthNum + "px");

    init_daterangepicker();


    formatCheck();

    //默认光标在卡号输入框
    $("#cardNo").focus();

    //卡号输入改变事件
    cardNoChange();


    //数据校验
    init_validator();


    /**
     * 清空
     */
    $("#clearRegistration").on("click", function (t) {
        clearInput();
    });


    /**
     * 保存入院登记
     */
    $("#confirmFee").on("click", function (t) {
        saveZyPatient(true);
    });


    /**
     * 修改住院号
     */
    $("#updateInpatientNo").on("click", function (t) {
        $("#new_inpatientNo").val(null);
        $("#new_name").val($("#userName").val());
        $("#birthDayNew").val($("#birthDayReadonly").val());
        $("#updateInpatientNoModal").modal("show");
    });


    /**
     * 上传身份证
     */
    $("#uploadIdCard").on("click", function (t) {
        $.ajax({
            type: "POST",
            url: '/thmz/savePatientMiSfz',
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            async: false,
            data: JSON.stringify({
                "socialNo": $("#idCard").val(),
                "name": $("#userName").val(),
                "sex": $("#gender").val(),
                "nation": $("#nationToUpload").val(),
                "birthDay": $("#birthDay").val(),
                "address": $("#address").val(),
                "agency": $("#idIssued").val(),
                "expirestart": $("#issuedData").val(),
                "expireend": $("#validDate").val(),
                "txImageBase64": $("#imageIdCard").val(),
                "inpatientNo": $("#admissionNumber").val(),
                "patientId": $("#patientId").val()
            }),
            headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
            success: function (res) {
                if (res == '401' || res == 401) {
                    window.location.href = '/thmz/login/view'
                    return;
                }
                if (res.code == 0) {
                    successMesage(res);
                } else {
                    errorMesage(res);
                }
            }
        });
    });


    /**
     * 查看身份证
     */
    $("#seeIdCard").on("click", function (t) {
        $.ajax({
            type: "GET",
            url: '/thmz/getPatientMiSfzByPatientId?patientId='+$("#patientId").val(),
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
            success: function (res) {
                if (res == '401' || res == 401) {
                    window.location.href = '/thmz/login/view'
                    return;
                }
                if (res.code == 0) {
                 $("#seeIdCardModal").modal("show");
                 $("#idCardImage").attr("src","data:image/jpeg;base64,"+res.data.sfzImage);
                } else {
                    errorMesage(res);
                }
            }
        });
    });

    /**
     * 初始化病区与小科室
     */
    initListSelect();


    //每隔三秒读一次身份证
    setInterval(function () {
        new Device().startFun();
    }, 5000);


    $("#birthDay").change(function (e) {
        var birthDay = $("#birthDay").val();
        if (birthDay.length == 8 && birthDay.indexOf("-") <= 0) {
            birthDay = birthDay.substring(0, 4) + "-" + birthDay.substring(4, 6) + "-" + birthDay.substring(6);
            $("#birthDay").val(birthDay);
        }
        var dateFormat = /^(\d{4})-(\d{2})-(\d{2})$/;
        if (!dateFormat.test(birthDay)) {
            new PNotify({
                title: '错误提示',
                text: '生日日期错误',
                type: 'error',
                hide: true,
                styling: 'bootstrap3'
            });
        }
        var arr = birthDay.split("-");
        if (!checkDate(arr[0], arr[1], arr[2])) {
            new PNotify({
                title: '错误提示',
                text: '生日日期错误',
                type: 'error',
                hide: true,
                styling: 'bootstrap3'
            });
        }
        var returnAge = jsGetAge(birthDay);
        $("#age").val(returnAge);
        $("#age").blur();
    });
    //默认入院日期是当天
    var now = nowString();
    $("#admissionDayReadonly").val(now);
    $("#admissionDayReadonly").attr("title", now);
    $("#admissionDay").val(now);


    $("#admissionDay").change(function (e) {
        var admissionDay = $("#admissionDay").val();
        if (admissionDay.length == 8 && admissionDay.indexOf("-") <= 0) {
            admissionDay = admissionDay.substring(0, 4) + "-" + admissionDay.substring(4, 6) + "-" + admissionDay.substring(6);
            $("#admissionDay").val(admissionDay);
        }
        var dateFormat = /^(\d{4})-(\d{2})-(\d{2})$/;
        if (!dateFormat.test(admissionDay)) {
            new PNotify({
                title: '错误提示',
                text: '入院日期错误',
                type: 'error',
                hide: true,
                styling: 'bootstrap3'
            });
        }
        var arr = admissionDay.split("-");
        if (!checkDate(arr[0], arr[1], arr[2])) {
            new PNotify({
                title: '错误提示',
                text: '入院日期错误',
                type: 'error',
                hide: true,
                styling: 'bootstrap3'
            });
        }
    });


    $("#idCard").change(function (e) {
        queryUserInfoBySocialNo();
    });

    $("#phoneNum").change(function (e) {
        queryUserInfoByphoneNo();
    });
    $("#userName").change(function (e) {
        queryUserInfoByName();
    });


    postCMD("login", localStorage.getItem("userID"), '000000', '收费项目', 0, 0, 0, '', '祝您早日康复', 0, 0, 0);
    setTimeout(function () {
        getLodop();
    }, 800);


    /**
     * 保存住院号修改
     */
    $("#saveEdit").on("click", function (t) {
        var new_inpatientNo = $("#new_inpatientNo").val();
        var newName = $("#new_name").val();
        $.ajax({
            type: "POST",
            url: '/thmz/modifyInpatientNo',
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            async: false,
            data: JSON.stringify({
                "name": newName,
                "inpatientNo": new_inpatientNo,
                "oldInpatientNo": $("#admissionNumber").val()
            }),
            headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
            success: function (res) {
                if (res == '401' || res == 401) {
                    window.location.href = '/thmz/login/view'
                    return;
                }
                if (res.code == 0) {
                    successMesage(res);
                    $("#admissionNumber").val(new_inpatientNo);
                    $("#userName").val(newName);
                    $("#updateInpatientNoModal").modal("hide");
                } else {
                    errorMesage(res);
                }
            }
        });
    });


    //回车键事件
    $(document).keyup(function (event) {
        if (event.keyCode == 13) {
            //当光标在新住院号的时候触发
            if ($("input:focus,textarea:focus").attr("id") == "new_inpatientNo") {
                queryZyUserByZyNo();
            }
        }
    });
    //新住院号失去光标事件
    $("#new_inpatientNo").blur(function () {
        queryZyUserByZyNo();
    });


});


/**
 * 初始化婚姻状态下拉选
 */
function initMaritalStatusSelect() {
    $(".selectpicker").selectpicker({
        dropuAuto: false
    });
    $.ajax({
        type: "GET",
        url: '/thmz/queryAllMaritalStatus',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                res.data.forEach(function (item, index) {
                    var html = '<option value="' + item.code + '">' + item.name + '</option>';
                    $('#maritalStatus').append(html);
                    //$('#editUserPatientsNature').append(html);
                });
                $('#maritalStatus').selectpicker('refresh');
                // $('#editUserPatientsNature').selectpicker('refresh');
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
        }
    });
}

/**
 * 初始化性别下拉选
 */
function initGenderSelect() {
    $(".selectpicker").selectpicker({
        //设置菜单的上浮或者下浮
        dropuAuto: false
    });
    var gender = '<option value="1">男</option><option value="2">女</option><option value="0">未知</option>';
    $('#gender').html(gender);
    $('#gender').selectpicker('refresh');
    $('#editUserGender').html(gender);
    $('#editUserGender').selectpicker('refresh');
}


/**
 * 列表类型按钮切换事件
 * @param object
 */
function titleButtonChange(object) {
    $("#regi_List_btn_group").find("button").each(function (index, element) {
        if ($(element).hasClass("btn-primary")) {
            $(element).removeClass("btn-primary").addClass("btn-default");
        }
    });
    $(object).removeClass("btn-default").addClass("btn-primary");
}


/**
 * checkBox样式
 */
function formatCheck() {
    if ($("input.flat")[0]) {
        $(document).ready(function () {
            $('input.flat').iCheck({
                checkboxClass: 'icheckbox_flat-blue',
                radioClass: 'iradio_flat-blue'
            });
        });
    }
}

/**
 * 卡号有变化后查询病人信息
 */
function queryUserInfoByCardNo() {
    var cardNo = $("#cardNo").val();
    var index = cardNo.indexOf("-");
    if ((index > 0 && index == cardNo.length - 2) || cardNo.length == 8) {
        $("#cardNo").attr("title", cardNo);
        $.ajax({
            type: "GET",
            url: '/thmz/getByIcCardNo?icCardNo=' + cardNo,
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
            success: function (res) {
                if (res == '401' || res == 401) {
                    window.location.href = '/thmz/login/view'
                    return;
                }
                if (res.code == 0) {
                    if (res.data != null) {
                        $("#cardNo").blur();
                        $("#userName").val(res.data.name);
                        $("#userName").blur();
                        $("#userNameReadOnly").val(res.data.name);
                        var age = jsGetAge(res.data.birthDayStr);
                        if (age == null) {
                            age = res.data.age;
                        }
                        $("#age").val(age);
                        $("#age").blur();
                        $("#gender").selectpicker('val', res.data.sex);
                        $("#gender").selectpicker('refresh');
                        $("#gender").blur();
                        $("#birthDayReadonly").val(res.data.birthDayStr);
                        $("#birthDayReadonly").attr("title", res.data.birthDayStr);
                        $("#birthDay").val(res.data.birthDayStr);
                        $("#birthDay").blur();
                        $("#phoneNum").val(res.data.phoneNo);
                        $("#phoneNum").attr("title", res.data.phoneNo);
                        $("#phoneNum").blur();
                        $("#patientsNature").selectpicker('val', res.data.responseType);//默认选中
                        $('#patientsNature').selectpicker('refresh');
                        $("#patientsNature").blur();
                        $("#idCard").val(res.data.socialNo);
                        $("#idCard").attr("title", res.data.socialNo);
                        $("#idCard").blur();
                        $("#address").val(res.data.address);
                        $("#address").blur();
                        $("#patientId").val(res.data.patientId);
                        if (res.data.name != null && res.data.name != "") {
                            $("#saveUser").show();
                            $("#clearRegistration").show();
                        }
                        //根据病人门诊id查询病人的入院申请
                        $.ajax({
                            type: "GET",
                            url: '/thmz/getMzZyReqByPatientId?patientId=' + res.data.patientId,
                            contentType: "application/json;charset=UTF-8",
                            dataType: "json",
                            headers: {
                                'Accept': 'application/json',
                                'Authorization': 'Bearer ' + localStorage.getItem("token")
                            },
                            success: function (resZyz) {
                                if (resZyz == '401' || resZyz == 401) {
                                    window.location.href = '/thmz/login/view'
                                    return;
                                }
                                if (resZyz.code == 0) {
                                    $("#reqDoctor").selectpicker('val', resZyz.data.doctorCode);
                                    $("#reqDoctor").selectpicker('refresh');
                                    $("#clinicDiagnosisCode").val(resZyz.data.icdCode);
                                    $("#clinicDiagnosis").val(resZyz.data.icdText);
                                    $("#hospitalDiagnosisCode").val(resZyz.data.icdCode);
                                    $("#hospitalDiagnosis").val(resZyz.data.icdText);
                                    $("#inpatientWard").selectpicker('val', resZyz.data.reqDept);
                                    $("#inpatientWard").selectpicker('refresh');
                                    initSmallDeptByDept();
                                    $("#smallWard").selectpicker('val', resZyz.data.smallDept);
                                    $("#smallWard").selectpicker('refresh');
                                }
                            }
                        });
                        //根据病人门诊id查询住院病人id
                        $.ajax({
                            type: "GET",
                            url: '/thmz/getAPatientByMzNo?mzNo=' + res.data.patientId,
                            contentType: "application/json;charset=UTF-8",
                            dataType: "json",
                            headers: {
                                'Accept': 'application/json',
                                'Authorization': 'Bearer ' + localStorage.getItem("token")
                            },
                            success: function (resAp) {
                                if (resAp == '401' || resAp == 401) {
                                    window.location.href = '/thmz/login/view'
                                    return;
                                }
                                if (resAp.code == 0) {
                                    $("#bornAddress").selectpicker('val', resAp.data.birthPlace);
                                    $("#bornAddress").selectpicker('refresh');
                                    $("#permanentAddress").val(resAp.data.accountStreet);
                                    $("#address").val(resAp.data.homeStreet);
                                    $("#unitAddress").val(resAp.data.employerStreet);
                                    $("#contractName").val(resAp.data.relationName);
                                    $("#relationship").selectpicker('val', resAp.data.relationCode);
                                    $("#relationship").selectpicker('refresh');
                                    $("#contractPhone").val(resAp.data.relationTel);
                                    $("#contractAddress").val(resAp.data.relationStreet);
                                    $("#profession").selectpicker('val', resAp.data.occupationCode);
                                    $("#profession").selectpicker('refresh');
                                    $("#maritalStatus").selectpicker('val', resAp.data.marryCode);
                                    $("#maritalStatus").selectpicker('refresh');
                                    $('#nationality').selectpicker('val', resAp.data.country);
                                    $('#nationality').selectpicker('refresh');
                                    $('#nation').selectpicker('val', resAp.data.nationCode);
                                    $('#nation').selectpicker('refresh');
                                    $("#idCard").val(resAp.data.socialNo);
                                    $("#idCard").attr("title", resAp.data.socialNo);
                                    $("#idCard").blur();
                                    $("#admissionNumber").val(resAp.data.inpatientNo);
                                    //验证当前病人是不是在院病人
                                    if(resAp.data.inpatientNo!=null && resAp.data.inpatientNo!=""){
                                        $.ajax({
                                            type: "GET",
                                            url: '/thmz/getCountByInpatientNo?inpatientNo=' + resAp.data.inpatientNo,
                                            contentType: "application/json;charset=UTF-8",
                                            dataType: "json",
                                            headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
                                            success: function (res) {
                                                if (res == '401' || res == 401) {
                                                    window.location.href = '/thmz/login/view'
                                                    return;
                                                }
                                                if (res.code == 0) {
                                                    if (res.data > 0) {
                                                        new PNotify({
                                                            title: '错误提示',
                                                            text: '当前办理入院的病人是在院病人，请不要重复操作！',
                                                            type: 'error',
                                                            hide: false,
                                                            styling: 'bootstrap3'
                                                        });
                                                    }
                                                } else {
                                                    errorMesage(res);
                                                }
                                            }
                                        });
                                    }
                                }
                            }
                        });
                    }
                } else {
                    new PNotify({
                        title: '错误提示',
                        text: res.message,
                        type: 'error',
                        hide: true,
                        styling: 'bootstrap3'
                    });
                }
            }
        });
    }
}

/**
 * 卡号输入改变事件
 */
function cardNoChange() {
    if (window.ActiveXObject || "ActiveXObject" in window) {
        $("#cardNo").on('input propertychange', function () {
            queryUserInfoByCardNo();
        });
    } else {
        $("#cardNo").on('input οninput', function () {
            queryUserInfoByCardNo();
        });
    }
}


/**
 * 给某些域增加title或者清除title
 * @param obj
 */
function clearTextOrTitle(obj) {
    if ($(obj).val() == null || $(obj).val().length == 0) {
        $(obj).attr("title", null);
    } else {
        $(obj).attr("title", $(obj).val());
        if ($(obj).attr("id") == "birthDay") {
            $(obj).blur()
        }
    }

}


/**
 * 查询默认打印机
 */
function setPrint() {
    if (printIndex >= 0) {
        return;
    }
    $.ajax({
        type: "GET",
        url: '/thmz/getLastWindowsByCurrentUser',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        async: false,
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                printIndex = res.data.printIndex;
            } else {
                printIndex = -1;
            }
        }
    });
}


/**
 * 保存住院信息
 */
function saveZyActpatient() {
    $.ajax({
        type: "POST",
        url: '/thmz/saveZyActpatient',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        data: JSON.stringify({
            "mzNo": $("#patientId").val(),
            "admissDate": $("#admissionDay").val(),
            "admissPhysician": $("#reqDoctor").val(),
            "clinicDiag": $("#clinicDiagnosisCode").val(),
            "clinicDiagStr": $("#clinicDiagnosis").val(),
            "admissDiag": $("#hospitalDiagnosisCode").val(),
            "admissDiagStr": $("#hospitalDiagnosis").val(),
            "admissDept": $("#inpatientWard").val(),
            "admissWard": $("#inpatientWard").val(),
            "smallDept": $("#smallWard").val(),
            "bedNo": $("#bedNum").val(),
            "admissStatus": $("#admissStatus").val()
        }),
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                new PNotify({
                    title: '操作提示',
                    text: res.message,
                    type: 'success',
                    hide: true,
                    styling: 'bootstrap3'
                });
                clearInput();
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
            $("#confirmFee").attr("disabled", false);
        }
    });
}

/**
 * 科室和医生列表初始化
 */
function initListSelect() {
    initListDeptSelect();
    initReqDoctorSelect()
    initCountrySelect();
    initNationSelect();
    initDistrictSelect();
    initRelationSelect();
    initOccupationSelect();
    iniAdmissStatus();
}

/**
 * 入院登记的病区列表
 */
function initListDeptSelect() {
    //科室列表
    $.ajax({
        type: "GET",
        url: '/thmz/allInpatientWard',
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (data) {
            if (data == '401' || data == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var html = '';
            $.each(data.data, function (commentIndex, comment) {
                html += '<option value="' + comment.code + '">' + comment.name + '(' + comment.pyCode + ')</option>';
            });
            $('#inpatientWard').empty();
            $('#inpatientWard').html(html);
            $('#inpatientWard').selectpicker('refresh');
            initSmallDeptByDept();
        }
    });
}


/**
 * 小科室列表
 */
function initSmallDeptByDept() {
    //小科室列表
    $.ajax({
        type: "GET",
        url: '/thmz/getSmallDeptByDept?code=' + $('#inpatientWard').val(),
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        async: false,
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var html = '';
            $.each(res.data, function (commentIndex, comment) {
                html += '<option value="' + comment.code + '">' + comment.name + '</option>';
            });
            $('#smallWard').empty();
            $('#smallWard').html(html);
            $('#smallWard').selectpicker('destroy').selectpicker('refresh');
        }
    });

    //病床列表
    $.ajax({
        type: "GET",
        url: '/thmz/getBedNumByDept?code=' + $('#inpatientWard').val(),
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var html = '';
            $.each(res.data, function (commentIndex, comment) {
                html += '<option value="' + comment + '">' + comment + '</option>';
            });
            $('#bedNum').empty();
            $('#bedNum').html(html);
            $('#bedNum').selectpicker('destroy').selectpicker('refresh');
        }
    });
}


/**
 * 入院医生列表初始化
 */
function initReqDoctorSelect() {
    //医生列表
    $.ajax({
        type: "GET",
        url: '/thmz/listEmployeeByDepts?depts=',
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var html = '';
            $.each(res.data, function (commentIndex, comment) {
                html += '<option value="' + comment.employeeCode + '">' + comment.employeeName + '</option>';
            });
            $('#reqDoctor').empty();
            $('#reqDoctor').html(html);
            $('#reqDoctor').selectpicker('destroy').selectpicker('refresh');
        }
    });
}


/**
 * 国籍列表初始化
 */
function initCountrySelect() {
    //医生列表
    $.ajax({
        type: "GET",
        url: '/thmz/getCountry',
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var html = '';
            $.each(res.data, function (commentIndex, comment) {
                html += '<option value="' + comment.code + '">' + comment.name + '</option>';
            });
            $('#nationality').empty();
            $('#nationality').html(html);
            $('#nationality').selectpicker('destroy').selectpicker('refresh');
            $('#nationality').selectpicker('val', 'cn');
            $('#nationality').selectpicker('refresh');

        }
    });
}


/**
 * 民族列表初始化
 */
function initNationSelect() {
    //医生列表
    $.ajax({
        type: "GET",
        url: '/thmz/getNation',
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var html = '';
            $.each(res.data, function (commentIndex, comment) {
                html += '<option value="' + comment.code + '">' + comment.name + '</option>';
            });
            $('#nation').empty();
            $('#nation').html(html);
            $('#nation').selectpicker('destroy').selectpicker('refresh');
            $('#nation').selectpicker('val', 'HA');
            $('#nation').selectpicker('refresh');
        }
    });
}


/**
 * 省份列表初始化
 */
function initDistrictSelect() {
    //医生列表
    $.ajax({
        type: "GET",
        url: '/thmz/getDistrict',
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var html = '';
            $.each(res.data, function (commentIndex, comment) {
                html += '<option value="' + comment.code + '">' + comment.name + '</option>';
            });
            $('#bornAddress').empty();
            $('#bornAddress').html(html);
            $('#bornAddress').selectpicker('destroy').selectpicker('refresh');
            $('#bornAddress').selectpicker('val', '430000');
            $('#bornAddress').selectpicker('refresh');
        }
    });
}


/**
 * 关系列表初始化
 */
function initRelationSelect() {
    //医生列表
    $.ajax({
        type: "GET",
        url: '/thmz/getRelation',
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var html = '';
            $.each(res.data, function (commentIndex, comment) {
                html += '<option value="' + comment.code + '">' + comment.name + '</option>';
            });
            $('#relationship').empty();
            $('#relationship').html(html);
            $('#relationship').selectpicker('destroy').selectpicker('refresh');
        }
    });
}


/**
 * 职业列表初始化
 */
function initOccupationSelect() {
    //医生列表
    $.ajax({
        type: "GET",
        url: '/thmz/getOccupation',
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var html = '';
            $.each(res.data, function (commentIndex, comment) {
                html += '<option value="' + comment.code + '">' + comment.name + '</option>';
            });
            $('#profession').empty();
            $('#profession').html(html);
            $('#profession').selectpicker('destroy').selectpicker('refresh');
        }
    });
}


/**
 * 所有的入院状态
 */
function iniAdmissStatus() {
    //医生列表
    $.ajax({
        type: "GET",
        url: '/thmz/getAdmissStatus',
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var html = '';
            $.each(res.data, function (commentIndex, comment) {
                html += '<option value="' + comment.code + '">' + comment.name + '</option>';
            });
            $('#admissStatus').empty();
            $('#admissStatus').html(html);
            $('#admissStatus').selectpicker('destroy').selectpicker('refresh');
        }
    });
}


/**
 * 清空信息
 */
function clearInput() {
    $("#userName").val(null);
    $("#gender").selectpicker('val', null);
    $('#gender').selectpicker('destroy').selectpicker('refresh');
    $("#birthDay").val(null);
    $("#cardNo").val(null);
    $("#phoneNum").val(null);
    $("#maritalStatus").selectpicker('val', null);
    $('#maritalStatus').selectpicker('destroy').selectpicker('refresh');
    $("#profession").selectpicker('val', null);
    $('#profession').selectpicker('destroy').selectpicker('refresh');
    $("#nationality").selectpicker('val', 'cn');
    $('#nationality').selectpicker('destroy').selectpicker('refresh');
    $("#nation").selectpicker('val', 'HA');
    $('#nation').selectpicker('destroy').selectpicker('refresh');
    $("#bornAddress").selectpicker('val', '430000');
    $('#bornAddress').selectpicker('destroy').selectpicker('refresh');
    $("#permanentAddress").val(null);
    $("#idCard").val(null);
    $("#address").val(null);
    $("#admissionNumber").val(null);
    $("#unitAddress").val(null);
    $("#contractName").val(null);
    $("#relationship").selectpicker('val', null);
    $('#relationship').selectpicker('destroy').selectpicker('refresh');
    $("#contractPhone").val(null);
    $("#contractAddress").val(null);
    $("#admissionDay").val(null);
    $("#reqDoctor").selectpicker('val', null);
    $('#reqDoctor').selectpicker('destroy').selectpicker('refresh');
    $("#clinicDiagnosisCode").val(null);
    $("#clinicDiagnosis").val(null);
    $("#hospitalDiagnosisCode").val(null);
    $("#hospitalDiagnosis").val(null);
    $("#inpatientWard").selectpicker('val', null);
    $('#inpatientWard').selectpicker('destroy').selectpicker('refresh');
    $("#smallWard").selectpicker('val', null);
    $('#smallWard').selectpicker('destroy').selectpicker('refresh');
    $("#bedNum").selectpicker('val', null);
    $('#bedNum').selectpicker('destroy').selectpicker('refresh');
    $("#admissStatus").val(null);
}


/**
 * 直接打印发票
 * @param patientId
 */
function prn1Print(patientId, times) {
    setPrint();
    var height = "93.15mm";
    // if(countReceiot%2==0){
    //     height ="93.2mm";
    // }
    $.ajax({
        type: "GET",
        url: '/thmz/printMzyReqrecRecept?patientId=' + patientId + "&times=" + times,
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                if (res.data == null || res.data.length == 0) {
                    return;
                }
                //   countReceiot++;
                LODOP = getLodop();
                var temp = res.data;
                LODOP.PRINT_INITA(6, 0, "120mm", height, "泰和门诊发票打印");
                //设置默认打印机
                LODOP.SET_PRINTER_INDEX(printIndex);
                LODOP.SET_SHOW_MODE("BKIMG_WIDTH", "120mm");
                LODOP.SET_SHOW_MODE("BKIMG_HEIGHT", height);
                LODOP.SET_PRINT_PAGESIZE(1, "120mm", height, "CreateCustomPage");
                LODOP.SET_PRINT_MODE("CREATE_CUSTOM_PAGE_NAME", "门诊发票");//对新建的纸张重命名
                LODOP.SET_PRINT_STYLE("FontSize", 11); //字体大小
                LODOP.ADD_PRINT_TEXT("6mm", "0mm", "45mm", "3mm", "湖南泰和医院管理有限公司");
                LODOP.ADD_PRINT_TEXT("6mm", "59mm", "30mm", "3mm", "流水号:");
                LODOP.ADD_PRINT_TEXT("6mm", "72mm", "20mm", "3mm", temp.serialNo);
                LODOP.ADD_PRINT_TEXT("19mm", "0mm", "35mm", "3mm", temp.receiptBill);
                LODOP.ADD_PRINT_TEXT("25mm", "7mm", "50mm", "3mm", temp.name);
                LODOP.ADD_PRINT_TEXT("25mm", "61mm", "27mm", "3mm", patientId);
                LODOP.ADD_PRINT_TEXT("32mm", "6mm", "50mm", "3mm", "就诊科室:" + temp.unitCode);
                LODOP.ADD_PRINT_TEXT("32mm", "56mm", "50mm", "3mm", "地点:" + res.officePos == null ? "" : res.officePos);
                LODOP.ADD_PRINT_TEXT("37mm", "6mm", "50mm", "3mm", "看诊医生:" + temp.doctorCode);
                LODOP.ADD_PRINT_TEXT("37mm", "56mm", "50mm", "3mm", "号段:" + temp.ampm);
                LODOP.ADD_PRINT_TEXT("42mm", "6mm", "50mm", "3mm", "号别:" + temp.chargeType);
                LODOP.ADD_PRINT_TEXT("42mm", "56mm", "50mm", "3mm", "挂号费:" + temp.reqFee);
                LODOP.ADD_PRINT_TEXT("47mm", "6mm", "50mm", "3mm", "诊查费:" + temp.clinicFee);
                LODOP.ADD_PRINT_TEXT("47mm", "56mm", "50mm", "3mm", "其他:" + temp.othFee);
                LODOP.ADD_PRINT_TEXT("52mm", "6mm", "50mm", "3mm", "工本费:" + temp.brochureFee);
                LODOP.ADD_PRINT_TEXT("65mm", "21mm", "60mm", "3mm", res.totalFee + " 元");
                LODOP.ADD_PRINT_TEXT("72mm", "19mm", "60mm", "3mm", res.totalFeeStr);
                LODOP.ADD_PRINT_TEXT("79mm", "0mm", "15mm", "3mm", res.year);//年
                LODOP.ADD_PRINT_TEXT("79mm", "13mm", "10mm", "3mm", res.month);//月
                LODOP.ADD_PRINT_TEXT("79mm", "25mm", "10mm", "3mm", res.day);//日
                LODOP.ADD_PRINT_TEXT("79mm", "53mm", "23mm", "3mm", res.user.userName);//收费员
                //LODOP.PREVIEW();
                LODOP.PRINT();
                if (times > 0) {
                    loadRegistrationList(true);
                }
            } else if (res.code == -2) {
                new PNotify({
                    title: '操作提示',
                    text: res.message,
                    type: 'success',
                    hide: true,
                    styling: 'bootstrap3'
                });
            } else if (res.code == -1) {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
        }
    });
};


/**
 * 保存病人信息
 * @param flag true 调用保存入院信息  false 不保存入院信息
 */
function saveZyPatient(flag) {
    $("#confirmFee").attr("disabled", true);
    $.ajax({
        type: "POST",
        url: '/thmz/saveZyPatient',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        data: JSON.stringify({
            "name": $("#userName").val(),
            "sex": $("#gender").val(),
            "birthDate": $("#birthDay").val(),
            "mzNo": $("#patientId").val(),
            "homeTel": $("#phoneNum").val(),
            "marryCode": $("#maritalStatus").val(),
            "occupationCode": $("#profession").val(),
            "country": $("#nationality").val(),
            "nationCode": $("#nation").val(),
            "birthPlace": $("#bornAddress").val(),
            "accountStreet": $("#permanentAddress").val(),
            "socialNo": $("#idCard").val(),
            "homeStreet": $("#address").val(),
            "inpatientNo": $("#admissionNumber").val(),
            "employerStreet": $("#unitAddress").val(),
            "relationName": $("#contractName").val(),
            "relationCode": $("#relationship").val(),
            "relationTel": $("#contractPhone").val(),
            "relationStreet": $("#contractAddress").val(),
            "inpatientNoType": getIndex("regi_List_btn_group")
        }),
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                $("#admissionNumber").val(res.data.inpatientNo);
                if (flag) {
                    saveZyActpatient();
                } else {
                    successMesage(res);
                    $("#confirmFee").attr("disabled", false);
                }
            } else {
                $("#confirmFee").attr("disabled", false);
                errorMesage(res);
            }
        }
    });
}


/**
 * 根据手机号码查询病人信息
 */
function queryUserInfoByphoneNo() {
    var phoneNo = $("#phoneNum").val();
    if (phoneNo.length == 11) {
        $.ajax({
            type: "GET",
            url: '/thmz/getByPhoneNo?phoneNo=' + phoneNo,
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
            success: function (res) {
                if (res == '401' || res == 401) {
                    window.location.href = '/thmz/login/view'
                    return;
                }
                if (res.code == 0) {
                    fitPatient(res);
                }
            }
        });
    }

}


/**
 * 根据病人姓名查询病人信息
 */
function queryUserInfoByName() {
    var userName = $('#userName').val();
    // var cardNo=$("#cardNo").val();
    if (userName == null || userName == "") {
        return;
    }
    if (userName.length > 0) {
        $.ajax({
            type: "GET",
            url: '/thmz/getPatientMiByName?name=' + userName,
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
            success: function (res) {
                if (res == '401' || res == 401) {
                    window.location.href = '/thmz/login/view'
                    return;
                }
                if (res.code == 0) {
                    fitPatient(res);
                }
            }
        });
    }

}


/**
 * 按照病人id查询病人信息
 * @param patientId
 */
function fillPatinet(patientId) {
    if (patientId == null || patientId == "") {
        return;
    }
    $.ajax({
        type: "GET",
        url: '/thmz/getByPatientId?patientId=' + patientId,
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                if (res.data != null) {
                    $("#cardNo").val(res.data.icCardNo);
                    $("#cardNo").attr("title", res.data.icCardNo);
                    $("#cardNo").blur();
                    $("#userName").val(res.data.name);
                    $("#userName").blur();
                    $("#userNameReadOnly").val(res.data.name);
                    $("#age").val(res.data.age);
                    $("#age").blur();
                    $("#gender").selectpicker('val', res.data.sex);
                    $("#gender").selectpicker('refresh');
                    $("#gender").blur();
                    $("#birthDayReadonly").val(res.data.birthDayStr);
                    $("#birthDayReadonly").attr("title", res.data.birthDayStr);
                    $("#birthDayReadonly").blur();
                    $("#birthDay").val(res.data.birthDayStr);
                    $("#birthDay").blur();
                    $("#phoneNum").val(res.data.phoneNo);
                    $("#phoneNum").attr("title", res.data.phoneNo);
                    $("#phoneNum").blur();
                    $("#patientsNature").selectpicker('val', res.data.responseType);//默认选中
                    $('#patientsNature').selectpicker('refresh');
                    $("#patientsNature").blur();
                    $("#idCard").val(res.data.socialNo);
                    $("#idCard").attr("title", res.data.socialNo);
                    $("#idCard").blur();
                    $("#address").val(res.data.address);
                    $("#address").blur();
                    $("#patientId").val(res.data.patientId);
                    if (res.data.name != null && res.data.name != "") {
                        $("#saveUser").show();
                        $("#clearRegistration").show();
                    }
                    queryUserInfoByCardNo();
                }
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
        }
    });
}


/**
 * 新住院号有变化后查询病人信息
 */
function queryZyUserByZyNo() {
    var newInpatientNo = $("#new_inpatientNo").val();
    if (newInpatientNo == null || newInpatientNo.length == 0 || newInpatientNo == "") {
        return;
    }
    $.ajax({
        type: "GET",
        url: '/thmz/getCountByInpatientNo?inpatientNo=' + newInpatientNo,
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                if (res.data > 0) {
                    new PNotify({
                        title: '错误提示',
                        text: '新住院号【' + newInpatientNo + '】对应的病人是在院病人，无法修改！',
                        type: 'error',
                        hide: false,
                        styling: 'bootstrap3'
                    });
                    $("#new_inpatientNo").val(null);
                } else {
                    $.ajax({
                        type: "GET",
                        url: '/thmz/getAPatientByNewInpatientNo?newInpatientNo=' + newInpatientNo,
                        contentType: "application/json;charset=UTF-8",
                        dataType: "json",
                        headers: {
                            'Accept': 'application/json',
                            'Authorization': 'Bearer ' + localStorage.getItem("token")
                        },
                        success: function (res) {
                            if (res == '401' || res == 401) {
                                window.location.href = '/thmz/login/view'
                                return;
                            }
                            if (res.code == 0) {
                                $("#new_name").val(res.data.name);
                                $("#birthDayNew").val(format(res.data.birthDate, "yyyy-MM-dd"));
                            } else {
                                errorMesage(res);
                            }
                        }
                    });
                }
            } else {
                errorMesage(res);
            }
        }
    });
}


/**
 * 获取按钮组选择的下标
 * @param id
 * @returns {number}
 */
function getIndex(id) {
    var index = 0;
    var item = $("#" + id).find("button");
    for (var i = 0; i <= item.length; i++) {
        if ($(item[i]).hasClass("btn-primary")) {
            index = i;
            break;
        }
    }
    return index;
}