//@ sourceURL=registration.js
var $dataTableHot;
//病人下拉选当前页记录
var pageIndex = 0;
//判断病人列表是否在加载中，防止重复加载
var msg_list_loading = false;
var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $dataTableHot = $('#tb_fee_info').bootstrapTable({
            url: '',         //请求后台的URL（*）
            method: 'post',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: false,                   //是否显示分页（*）
            sortable: true,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: true,
            showColumns: false,                  //是否显示所有的列
            showRefresh: false,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
            showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,
            ajaxOptions: {
                headers: {
                    'Accept': 'application/json',
                    'Authorization': 'Bearer ' + localStorage.getItem("token")
                }
            },
            columns: [
                {
                    checkbox: true
                }, {
                    field: 'name',
                    title: '名称',
                    align: "center",
                    valign: 'middle',
                    sortable: true
                }, {
                    field: 'money',
                    title: '金额（元）',
                    align: "center",
                    valign: 'middle',
                    sortable: true
                }, {
                    field: 'moneyReceived',
                    title: '实收金额（元）',
                    align: "center",
                    valign: 'middle',
                    sortable: true
                }],
            responseHandler: function (res) {
                if (res == '401' || res == 401) {
                    window.location.href = '/thmz/login/view'
                    return;
                }
                var ress = eval(res);
                if (ress.code == -1) {
                    new PNotify({
                        title: '错误提示',
                        text: ress.message,
                        type: 'error',
                        hide: false,
                        styling: 'bootstrap3'
                    });
                    return {
                        "total": 0,//总页数
                        "rows": {}   //数据
                    };
                }
                return {
                    "total": ress.pageViewVO.total,//总页数
                    "rows": ress.pageViewVO.data   //数据
                };
            },
        });
    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            pageSize: params.limit,   //页面大小
            pageIndex: params.offset / params.limit,  //页码
            orderByCase: $("#orderByCase").val()
        };
        return temp;
    };
    return oTableInit;
};


$(function () {
    initGenderSelect();
    initResponceTypeSelect();
    var birthDay = $('#birthDayGroup').datetimepicker({
        format: 'yyyy-mm-dd',
        language: 'zh-CN',
        minView: "month",
    }).on('changeDate', changeDate);

    var editUserBirthDay = $('#editUserBirthDayGroup').datetimepicker({
        format: 'yyyy-mm-dd',
        language: 'zh-CN',
        minView: "month",
    });

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

    init_daterangepicker();

    //1.初始化Table
    var oTable = new TableInit();
    oTable.Init();

    formatCheck();
    //默认光标在卡号输入框
    $("#cardNo").focus();
    //根据病人姓名输入框内容动态加载病人列表
    initUserList();
    //卡号输入改变事件
    cardNoChange();

    //卡号输入改变事件
    userNameChange();
    //数据校验
    init_validator();
    //时间区间
    initMzWorkTime();
    //初始门诊收银方式下拉选
    initChequeType("payType");

    /**
     * 清空
     */
    $("#clearRegistration").on("click", function (t) {
        $("#cardNo").val(null);
        $("#cardNo").attr("title", null);
        $("#userName").val(null);
        $("#age").val(null);
        $("#gender").selectpicker('val', 1);
        $("#gender").selectpicker('refresh');
        $("#birthDay").val(null);
        $("#birthDay").attr("title", null);
        $("#phoneNum").val(null);
        $("#phoneNum").attr("title", null);
        $("#patientsNature").selectpicker('val', '01');//默认选中
        $('#patientsNature').selectpicker('refresh');
        $("#idCard").val(null);
        $("#idCard").attr("title", null);
        $("#address").val(null);
        $("#editUser").hide();
        //默认光标在卡号输入框
        $("#cardNo").focus();
        initMzWorkTime();
        readonlyOrNot(false);
    });
    /**
     * 增加收款方式按钮事件
     */
    $("#addPayType").on("click", function (t) {
        var payTypeIndex = $("#payTypeIndex").val();
        var payTypeId = "payType_" + payTypeIndex;
        var html = '<div class="item form-group"><div class="col-md-12 col-sm-12 col-xs-12"><div class="col-md-2 col-sm-2 col-xs-12"></div><label class="col-md-3 col-sm-3 col-xs-12"><select class="form-control selectpicker show-tick" required="true" id="' + payTypeId + '"></select></label><div class="col-md-3 col-sm-3 col-xs-12"><input class="form-control col-md-5 col-xs-12" type="number" data-placement="bottom-right" min="0"></div><a style="line-height: 34px;cursor: pointer;" onclick="closeThisParent(this)"><i class="fa fa-close"></i></a></div></div>';
        $("#changeAmountParent").before(html);
        initChequeType(payTypeId)
        payTypeIndex = payTypeIndex + 1;
        $("#payTypeIndex").val(payTypeIndex);
    });
    // //当ic卡号输入框失去光标后，重置光标到卡号输入框
    // $("#cardNo").blur(function () {
    //     var focus = !($("#userName").is(":focus") || $("#age").is(":focus") || $("#birthDay").is(":focus") || $("#phoneNum").is(":focus") || $("#idCard").is(":focus") || $("#address").is(":focus"));
    //     if (focus && $("#cardNo").val() == null || $("#cardNo").val() == "") {
    //         //默认光标在卡号输入框
    //         $("#cardNo").focus();
    //     }
    // });
});

/**
 * 初始化性别下拉选
 */
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');
}


/**
 * 初始化病人身份类别下拉选
 */
function initResponceTypeSelect() {
    $(".selectpicker").selectpicker({
        dropuAuto: false
    });
    $.ajax({
        type: "GET",
        url: '/thmz/getMzResponceType',
        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>';
                    $('#patientsNature').append(html);
                    $('#editUserPatientsNature').append(html);
                });
                $('#patientsNature').selectpicker('refresh');
                $('#editUserPatientsNature').selectpicker('refresh');
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: false,
                    styling: 'bootstrap3'
                });
            }
        }
    });
}


/**
 * 初始科室下拉选
 * @param ampm 时间段区间
 */
function initDeptPlus() {
    //科室列表
    $.ajax({
        type: "GET",
        url: '/thmz/getUnitCodeByRequestDay?ampm=' + $("#ampm").val(),
        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 + '</option>';
            });
            $('#deptNo').empty();
            $('#deptNo').html(html);
            $('#deptNo').selectpicker('refresh');

            $('#chargeType').empty();
            $('#chargeType').selectpicker('refresh');
            emptyInput();
        }
    });
}


/**
 * 初始医生下拉选
 * @param ampm 时间段区间
 */
function initEmployee() {
    //科室列表
    $.ajax({
        type: "GET",
        url: '/thmz/getDoctorCodeByRequestDay?unitCode=' + $('#deptNo').val() + "&ampm=" + $("#ampm").val() + "&chargeType=" + $("#chargeType").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 = '';
            var flag = false;
            $.each(res.data, function (commentIndex, comment) {
                html += '<option value="' + comment.employeeCode + '" data-chargeType="' + comment.chargeType + '"  data-checkFee="' + comment.checkFee + '">' + comment.employeeName + '</option>';
                if (comment.employeeCode == -1) {
                    flag = true;
                }
            });
            $('#doctor').empty();
            $('#doctor').html(html);
            $('#doctor').selectpicker('refresh');
            validator.checkAll($("#regi_form"));
            if (flag) {
                //如果有无需选择医生的选项，默认选择
                $('#doctor').selectpicker('val', -1);
                $('#doctor').selectpicker('refresh');
                fitFee();
            }
        }
    });
}


/**
 * 初始门诊时间区间下拉选
 */
function initMzWorkTime() {
    $.ajax({
        type: "GET",
        url: '/thmz/getMzWorkTime',
        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 = '';
            var ampm = null;
            $.each(res.data, function (commentIndex, comment) {
                html += '<option value="' + comment.code + '">' + comment.name + '</option>';
                if (ampm == null || (ampm != "a" && ampm != "p")) {
                    var startTime = paseToFullTime(comment.startTime);
                    var endTime = paseToFullTime(comment.endTime);
                    if (range(startTime, endTime)) {
                        ampm = comment.code;
                    }
                }
            });
            $('#ampm').empty();   //清空resText里面的所有内容
            $('#ampm').html(html);
            $('#ampm').selectpicker('refresh');
            $("#ampm").selectpicker('val', ampm);
            $('#ampm').selectpicker('refresh');
            initDeptPlus();
        }
    });
}


/**
 * 初始门诊号别下拉选
 */
function initChargeType() {
    $.ajax({
        type: "GET",
        url: '/thmz/getChargeTypeByRequestDay?unitCode=' + $('#deptNo').val() + "&ampm=" + $("#ampm").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.code + '">' + comment.name + '</option>';
            });
            $('#chargeType').empty();   //清空resText里面的所有内容
            $('#chargeType').html(html);
            $('#chargeType').selectpicker('refresh');
            validator.checkAll($("#regi_form"));
            emptyInput();
        }
    });
}


/**
 * 设置挂号费等费用
 */
function fitFee() {
    var chargeType = $('#doctor').find("option:selected").attr('data-chargeType');
    var checkFee = $('#doctor').find("option:selected").attr('data-checkFee');
    $("#checkFee").val(checkFee);
    $("#amountMoney").text(checkFee);
    $("#amountMoneyConfirm").text(checkFee);
    $("#realMoney").val(checkFee);
    $.ajax({
        type: "GET",
        url: '/thmz/getMzChargeTypeByCode?code=' + chargeType,
        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;
            }
            $("#registrationFee").val(res.data.reqFee);
            $("#hospitalFee").val(res.data.clinicFee);
            checkFee = parseFloat(checkFee) + parseFloat(res.data.reqFee) + parseFloat(res.data.clinicFee);
            $("#amountMoney").text(checkFee);
            $("#amountMoneyConfirm").text(checkFee);
            $("#realMoney").val(checkFee);
        }
    });
}


/**
 * 初始门诊收银方式下拉选
 */
function initChequeType(payType) {
    $.ajax({
        type: "GET",
        url: '/thmz/getAllZdChequeTypeForMz',
        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>';
            });
            $('#' + payType).empty();
            $('#' + payType).html(html);
            $('#' + payType).selectpicker('refresh');
        }
    });
}


/**
 * 日期值改变修改年龄字段
 * @param ev
 */
function changeDate(ev) {
}

/**
 * 列表类型按钮切换事件
 * @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");
}


/**
 * 表格类型切换事件  卡片展示或者列表形式
 */
function listTypeChange(object) {
    var indexNum = 0;
    $("#regi_List_type").find("button").each(function (index, element) {
        if ($(element).hasClass("btn-primary")) {
            $(element).removeClass("btn-primary").addClass("btn-default");
        }
        if (object == element) {
            indexNum = index;
        }
    });
    $(object).removeClass("btn-default").addClass("btn-primary");
    if (indexNum == 1) {
        $('#tb_regi_list').bootstrapTable({
            url: '',         //请求后台的URL（*）
            method: 'post',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            sortable: true,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: this.queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: true,
            showColumns: false,                  //是否显示所有的列
            showRefresh: false,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
            showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,
            ajaxOptions: {
                headers: {
                    'Accept': 'application/json',
                    'Authorization': 'Bearer ' + localStorage.getItem("token")
                }
            },
            columns: [
                {
                    field: 'name',
                    title: '名称',
                    align: "center",
                    valign: 'middle',
                    sortable: true
                }, {
                    field: 'money',
                    title: '金额（元）',
                    align: "center",
                    valign: 'middle',
                    sortable: true
                }, {
                    field: 'moneyReceived',
                    title: '实收金额（元）',
                    align: "center",
                    valign: 'middle',
                    sortable: true
                }],
            responseHandler: function (res) {
                if (res == '401' || res == 401) {
                    window.location.href = '/thmz/login/view'
                    return;
                }
                var ress = eval(res);
                if (ress.code == -1) {
                    new PNotify({
                        title: '错误提示',
                        text: ress.message,
                        type: 'error',
                        hide: false,
                        styling: 'bootstrap3'
                    });
                    return {
                        "total": 0,//总页数
                        "rows": {}   //数据
                    };
                }
                return {
                    "total": ress.pageViewVO.total,//总页数
                    "rows": ress.pageViewVO.data   //数据
                };
            },
        });
    } else {

        $('#tb_regi_list').bootstrapTable("destroy");
    }

}


/**
 * 打开编辑挂号信息窗口
 * @param data
 */
function editRegistration(data) {
    $("#editRegiModal").modal();
}


/**
 * 打开编辑用户信息窗口
 * @param data
 */
function editUserModal(data) {
    $("#editUserModal").modal();
}

/**
 * 打开退费信息窗口
 * @param data
 */
function backNoModal(data) {
    $("#backNoModal").modal();
}

/**
 * 打开打印窗口
 * @param data
 */
function printOrPreviewModal(data) {
    $("#printOrPreviewModal").modal();
}

/**
 * 打开打印内容窗口
 * @param data
 */
function printModal(data) {
    $("#printOrPreviewModal").modal("hide");
    $("#printModal").modal();
}

/**
 * 打开收费窗口
 * @param data
 */
function confirmFeeModal() {
    var validatorResult = validator.checkAll($("#regi_form"));
    if (!validatorResult) {
        return;
    }
    var prevAll = $("#changeAmountParent").prevAll();
    while (prevAll.length > 2) {
        $("#changeAmountParent").prev().remove();
        prevAll = $("#changeAmountParent").prevAll();
    }
    $("#realMoney").val($("#amountMoneyConfirm").text());
    $("#cash").val(null);
    $("#confirmFeeModal").modal();
}

/**
 * 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();
    if (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);
                        $("#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);
                        $("#birthDay").val(res.data.birthDayStr);
                        $("#birthDay").blur();
                        $("#phoneNum").val(res.data.phoneNo);
                        $("#phoneNum").attr("title", res.data.phoneNo);
                        $("#phoneNum").blur();
                        $("#patientsNature").selectpicker('val', res.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();
                        if (res.data.name != null && res.data.name != "") {
                            $("#editUser").show();
                        }
                        readonlyOrNot(true);
                    } else {
                        $("#newCardModal").modal();
                    }
                } else {
                    new PNotify({
                        title: '错误提示',
                        text: res.message,
                        type: 'error',
                        hide: false,
                        styling: 'bootstrap3'
                    });
                }
            }
        });
    }
}

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

/**
 * 病人姓名输入改变事件
 */
function userNameChange() {
    if (window.ActiveXObject || "ActiveXObject" in window) {
        $("#userName").on('input propertychange', function () {
            refeshPatinetList(true);
        });
    } else {
        $("#userName").on('input οninput', function () {
            refeshPatinetList(true);
        });
    }
}


/**
 * 校验收款金额
 */
function checkFee() {
    var cash = parseFloat($("#cash").val());
    var realMoney = parseFloat($("#realMoney").val());
    realMoney = realMoney.toFixed(2);
    $("#realMoney").val(realMoney)
    if (cash < realMoney) {
        new PNotify({
            title: '错误提示',
            text: "收款金额不能少于实收金额！",
            type: 'error',
            hide: true,
            styling: 'bootstrap3'
        });
    } else if (cash > realMoney) {
        if ($("#payType").val() == 1) {
            var changeAmount = cash - realMoney;
            $("#changeAmount").val(changeAmount.toFixed(2));
        } else {
            new PNotify({
                title: '错误提示',
                text: "非现金收款金额不能大于实收金额！",
                type: 'error',
                hide: true,
                styling: 'bootstrap3'
            });
        }
    }
    //计算和设置折扣比例
    var amountMoneyConfirm = parseFloat($("#amountMoneyConfirm").text());
    var discount = realMoney / amountMoneyConfirm * 100;
    $("#discount").text(discount.toFixed(2))
}

/**
 * 根据病人姓名输入框内容动态加载病人列表
 */
function initUserList() {
    //var width=$("#userName").css("width");
    var settings = {
        trigger: 'click',
        content: '',
        width: 170,
        multi: true,
        closeable: false,
        style: '',
        delay: 300,
        padding: true,
        height: 300
    };
    var webuiPopover = $('#userName').webuiPopover('destroy').webuiPopover(settings);
    //用户姓名选中事件
    $("#userName").on("click", function (t) {
        if ($(webuiPopover).css("display") == "block") {
            refeshPatinetList(true);
        }
    });


}

/**
 * 刷新病人列表
 */
function refeshPatinetList(flag) {
    //如果是重新加载病人列表，需要重置下标
    if (flag) {
        //重置下标
        pageIndex = 0;
        msg_list_loading = true;
    }
    var userName = $('#userName').val();
    if (!(userName == null || userName == "" || isChinese(userName))) {
        return;
    }
    $.ajax({
        type: "GET",
        url: '/thmz/getPatientMiByName?name=' + userName + "&pageIndex=" + pageIndex,
        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) {
                    $("#webuiPopover0").css("display", "block");
                    var html = '<div class="list-group">';
                    for (var i = 0; i < res.data.length; i++) {
                        var mzPatientMi = res.data[i];
                        html += '<a href="#" class="list-group-item list-group-item-action" onclick="fillPatinet(\'' + mzPatientMi.patientId + '\')">';
                        var sex = "未知";
                        if (mzPatientMi.sex == 1) {
                            html += '<img src="/thmz/images/boy.png"/>'
                            sex = "男";
                        } else if (mzPatientMi.sex == 2) {
                            html += '<img src="/thmz/images/girl.png"/>'
                            sex = "女";
                        } else if (mzPatientMi.sex == 0 || mzPatientMi.sex == null) {
                            html += '<img src="/thmz/images/girl_or_boy.png"/>'
                            sex = "未知";
                        }
                        html += '<div>' + mzPatientMi.name + '&nbsp;' + sex + '&nbsp;';
                        if (mzPatientMi.age != null && mzPatientMi.age != "") {
                            html += mzPatientMi.age + '岁';
                        } else {
                            html += '**岁';
                        }
                        if (mzPatientMi.phoneNo != null && mzPatientMi.phoneNo != "") {
                            html += '<span>' + mzPatientMi.phoneNo + '</span>';
                        }
                        html += '</div></a>';
                    }
                    html += '</div>';
                    if (flag) {
                        $("div.webui-popover-content").html("");
                    }
                    $("div.webui-popover-content").append(html);
                    $("div.arrow").css("left", "23px");
                    refeshPatinetListScrollEvent();
                } else {
                    $("#webuiPopover0").css("display", "none");
                }
            }
            //查询完成，设置加载完成
            msg_list_loading = false;
        }
    });
}

/**
 * 病人下拉列表滚动条滚动到底部时继续加载新纪录
 */
function refeshPatinetListScrollEvent() {
    $('.webui-popover-content').scroll(function (event) {
        var top = $(this).scrollTop();
        var height = $(this).height();
        var scrollHeight = $(this).get(0).scrollHeight;
        if (scrollHeight <= top + height) {
            if (!msg_list_loading) {
                msg_list_loading = true;
                pageIndex = pageIndex + 1;
                refeshPatinetList(false);
            }
        }
    });
}

/**
 * 按照病人id查询病人信息
 * @param patientId
 */
function fillPatinet(patientId) {
    $.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.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();
                    if (res.data.name != null && res.data.name != "") {
                        $("#editUser").show();
                    }
                    readonlyOrNot(true);
                }
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: false,
                    styling: 'bootstrap3'
                });
            }
        }
    });
}


/**
 * 关闭当前这个付款方式
 */
function closeThisParent(obj) {
    $(obj).parent().parent().remove();
}

/**
 * 科室与时间区间下拉选改变时清空输入框内容
 */
function emptyInput() {
    $('#doctor').empty();
    $('#doctor').selectpicker('refresh');
    $("#registrationFee").val(0.00);
    $("#hospitalFee").val(0.00);
    $("#checkFee").val(0.00);
    $("#amountMoney").text(0.00);
    $("#amountMoneyConfirm").text(0.00);
    $("#realMoney").val(0.00);
}

/**
 * 给某些域增加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());
    }
}

/**
 * 当按照卡号查询时，病人信息输入框不可编辑，当清空输入框时可编辑
 * @param flag
 */
function readonlyOrNot(flag) {
    if (flag) {
        $("#cardNo").attr("readonly", "readonly");
        $("#userName").attr("readonly", "readonly");
        $("#age").attr("readonly", "readonly");
        $("#gender").attr("disabled", "disabled");
        $("#phoneNum").attr("readonly", "readonly");
        $("#patientsNature").attr("disabled", "disabled");
        $("#idCard").attr("readonly", "readonly");
        $("#address").attr("readonly", "readonly");
        $("#birthDayReadonly").removeClass("hide").addClass("in");
        $("#birthDayGroup").removeClass("in").addClass("hide");
        $("#userName").removeClass("in").addClass("hide");
        $("#userNameReadOnly").removeClass("hide").addClass("in");
        $("#webuiPopover0").css("display", "none");
    } else {
        $("#cardNo").removeAttr("readonly");
        $("#userName").removeAttr("readonly");
        $("#age").removeAttr("readonly");
        $("#gender").removeAttr("disabled");
        $("#gender").next().removeClass("disabled");
        $("#phoneNum").removeAttr("readonly");
        $("#patientsNature").removeAttr("disabled");
        $("#patientsNature").next().removeClass("disabled");
        $("#idCard").removeAttr("readonly");
        $("#address").removeAttr("readonly");
        $("#birthDayReadonly").removeClass("in").addClass("hide");
        $("#birthDayGroup").removeClass("hide").addClass("in");
        $("#userName").removeClass("hide").addClass("in");
        $("#userNameReadOnly").removeClass("in").addClass("hide");
        $("#webuiPopover0").css("display", "block");
    }

}