//@ sourceURL=registration_list.js
var $dataTableHot;
//病人下拉选当前页记录
var pageIndex = 0;
//判断病人列表是否在加载中，防止重复加载
var msg_list_loading = false;
//挂号卡片列表页面下标
var pageIndex = 0;
//判断表格列表是否已经初始化
var isTableListInit = false;
var LODOP; //声明为全局变量
//默认打印机下标
var printIndex = -1;
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: true,
                        styling: 'bootstrap3'
                    });
                    return {
                        "total": 0,//总页数
                        "rows": {}   //数据
                    };
                }
                return {
                    "total": ress.pageViewVO.total,//总页数
                    "rows": ress.pageViewVO.data   //数据
                };
            },
        });
    };
    return oTableInit;
};


$(function () {
    initGenderSelect();
    initResponceTypeSelect();


    //设置挂号窗口的高度
    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");
    //初始修改收费方式 收银方式下拉选
    initChequeType("payTypeEditPayMode");

    /**
     * 清空
     */
    $("#clearRegistration").on("click", function (t) {
        clearRegistration();
    });
    /**
     * 增加收款方式按钮事件
     */
    $("#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();
    //     }
    // });


    // /**
    //  * 设置窗口号
    //  */
    // $("#editWindows").on("click", function (t) {
    //     $.ajax({
    //         type: "GET",
    //         url: '/thmz/getLastWindowsByCurrentUser',
    //         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) {
    //                 $("#windowsNum").val(res.data.windowsNo)
    //             } else {
    //                 new PNotify({
    //                     title: '错误提示',
    //                     text: res.message,
    //                     type: 'error',
    //                     hide: true,
    //                     styling: 'bootstrap3'
    //                 });
    //             }
    //         }
    //     });
    //     $("#editWindowsModal").modal();
    // });


    /**
     * 退费重收事件
     */
    $("#saveConfirmFee").on("click", function (t) {
        var serialNo = $("#serialNo").val();
        if (!confirm("确定要将流水号【"+serialNo+"】的挂号记录退费重收吗？")) {
            return;
        }
        $.ajax({
            type: "GET",
            url: '/thmz/chargeFeeForByjz?serialNo='+serialNo+"&paymode="+$("#payType").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) {
                    $('#confirmFeeModal').modal('hide');
                    $("#serialNo").val(null);
                    prn1Print(res.data.patientId, res.data.times);
                } else {
                    new PNotify({
                        title: '错误提示',
                        text: res.message,
                        type: 'error',
                        hide: true,
                        styling: 'bootstrap3'
                    });
                }
            }
        });
    });

    /**
     * 患者信息修改
     */
    $("#saveEditUser").on("click", function (t) {
        modifyPatient();
    });

    /**
     * 挂号列表中的科室和医生列表初始化
     */
    initListSelect();

    $("#queryListButton").on("click", function (t) {
        loadTableCount();
        loadRegistrationList(true);
    });
    loadTableCount();
    loadRegistrationList(true);

    // $("#editPrint").on("click", function (t) {
    //     CreatePrinterList();
    //     $("#editPrintModal").modal();
    // });

    //初始化页面上面的按钮事件
    $("#btn_excel").click(function (t) {
        exportExcel();
    });
});


// function CreatePageList() {
//     LODOP = getLodop();
//     LODOP.PRINT_INITA(6, 0, "92mm", "120mm", "泰和门诊发票打印");
//     //获取纸张大小数，用于进行遍历
//     var strPageSizeList = LODOP.GET_PAGESIZES_LIST($('#printSelect').val(), "\n");
//     var html = "";
//     var arr = strPageSizeList.split("\n");
//     for (var i = 0; i < arr.length; i++) {
//         html += "<option value='" + arr[i] + "'>" + arr[i] + "</option>";
//     }
//     $('#pageSelect').html(html);
//     $('#pageSelect').selectpicker('refresh');
// }


/**
 * 初始化性别下拉选
 */
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: true,
                    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 + '(' + comment.pyCode + ')</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 defaultCode = null;
            $.each(res.data, function (commentIndex, comment) {
                html += '<option value="' + comment.employee.employeeCode + '" data-chargeType="' + comment.chargeType + '"  data-checkFee="' + comment.checkFee + '" data-mzyRequestId="' + comment.mzyRequestId + '">' + comment.employee.employeeName + '</option>';
                if (res.data.length == 1) {
                    //如果只有一个号别，默认选中
                    defaultCode = comment.employee.employeeCode;
                }
            });
            $('#doctor').empty();
            $('#doctor').html(html);
            $('#doctor').selectpicker('refresh');
            validator.checkAll($("#regi_form"));
            if (defaultCode != null) {
                //如果有无需选择医生的选项，默认选择
                $('#doctor').selectpicker('val', defaultCode);
                $('#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 = '';
            var defaultCode = null;
            $.each(res.data, function (commentIndex, comment) {
                if (res.data.length == 1) {
                    //如果只有一个号别，默认选中
                    defaultCode = comment.code;
                }
                html += '<option value="' + comment.code + '">' + comment.name + '</option>';
            });
            $('#chargeType').empty();   //清空resText里面的所有内容
            $('#chargeType').html(html);
            $('#chargeType').selectpicker('refresh');
            if (defaultCode != null) {
                //如果有默认选项，默认选择
                $('#chargeType').selectpicker('val', defaultCode);
                $('#chargeType').selectpicker('refresh');
                initEmployee();
            }
            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);
    $("#cash").val(checkFee);
    $("#changeAmount").val(0);
    $.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);
            $("#cash").val(checkFee);
            validator.checkAll($("#regi_form"));
        }
    });
}


/**
 * 初始门诊收银方式下拉选
 */
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");
    loadRegistrationList(true);
}


/**
 * 表格类型切换事件  卡片展示或者列表形式
 */
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");
    loadRegistrationList(true);

}


/**
 * 打开编辑用户信息窗口
 * @param data
 */
function editUserModal(data) {
    $("#editUserModal").modal();
    if (data == null) {
        data = $("#patientId").val();
    }
    $.ajax({
        type: "GET",
        url: '/thmz/getByPatientId?patientId=' + data,
        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) {
                    //延时调用，因为当前弹框还没有加载出来，校验规则无法获取光标与模拟光标丢失事件，延时可以等弹框加载出来后模拟事件
                    setTimeout(function () {
                        fillPlusPatinet(res.data);
                    }, 400);
                }
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
        }
    });
}

/**
 * 打开退费信息窗口
 * @param patientId
 * @param times
 */
function backNoModal(patientId, times) {
    $.ajax({
        type: "POST",
        url: '/thmz/getMzyReqrecByPatientIdAndTimes',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        data: JSON.stringify({"patientId": patientId, "times": times}),
        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) {
                    $("#backNoPatientId").val(patientId);
                    $("#backNoTimes").val(times);
                    $("#backNoSickName").text(res.data.mzyReqrec.name);
                    $("#backNoPayType").text(res.data.mzyReqrec.paymode);
                    $("#backNoPhone").text(res.data.mzPatientMi.phoneNo);
                    $("#backNoAmpm").text(res.data.mzyReqrec.ampm);
                    $("#backNoDeptName").text(res.data.mzyReqrec.unitCode);
                    $("#backNoChargeType").text(res.data.mzyReqrec.chargeType);
                    $("#backNoDoctorName").text(res.data.mzyReqrec.doctorCode);
                    $("#backNoRegiDate").text(format(res.data.mzyReqrec.requestDay, "yyyy-MM-dd HH:mm:ss"));
                    var index = 0;
                    var trHtml = '';
                    if (res.data.mzyReqrec.reqFee != null && res.data.mzyReqrec.reqFee != "" && res.data.mzyReqrec.reqFee > 0) {
                        trHtml = '<tr data-index="' + index + '"><td style="text-align: center; vertical-align: middle; ">挂号费</td><td style="text-align: center; vertical-align: middle; ">' + res.data.mzyReqrec.reqFee + '</td><td style="text-align: center; vertical-align: middle; ">' + res.data.mzyReqrec.reqFee + '</td></tr>';
                        index++;
                    }
                    if (res.data.mzyReqrec.clinicFee != null && res.data.mzyReqrec.clinicFee != "" && res.data.mzyReqrec.clinicFee > 0) {
                        trHtml += '<tr data-index="' + index + '"><td style="text-align: center; vertical-align: middle; ">诊查费</td><td style="text-align: center; vertical-align: middle; ">' + res.data.mzyReqrec.clinicFee + '</td><td style="text-align: center; vertical-align: middle; ">' + res.data.mzyReqrec.clinicFee + '</td></tr>';
                        index++;
                    }
                    if (res.data.mzyReqrec.othFee != null && res.data.mzyReqrec.othFee != "" && res.data.mzyReqrec.othFee > 0) {
                        trHtml += '<tr data-index="' + index + '"><td style="text-align: center; vertical-align: middle; ">检查费</td><td style="text-align: center; vertical-align: middle; ">' + res.data.mzyReqrec.othFee + '</td><td style="text-align: center; vertical-align: middle; ">' + res.data.mzyReqrec.othFee + '</td></tr>';
                    }
                    $("#tb_fee_info").find("tbody").empty();
                    $("#tb_fee_info").find("tbody").append(trHtml);
                }
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
        }
    });
    $("#backNoModal").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($("#amountMoneyConfirm").text());
    $("#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();
    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);
                        $("#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.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 != "") {
                            $("#editUser").show();
                        }
                        readonlyOrNot(true);
                    } else {
                        $("#newCardModal").modal();
                    }
                } 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();
        });
    }
}

/**
 * 病人姓名输入改变事件
 */
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'
        });
        return;
    } 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'
            });
            return;
        }
    }
    //计算和设置折扣比例
    var amountMoneyConfirm = parseFloat($("#amountMoneyConfirm").text());
    var discount = 100;
    if (realMoney < amountMoneyConfirm) {
        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) {
    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 != "") {
                        $("#editUser").show();
                    }
                    readonlyOrNot(true);
                }
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
        }
    });
}


/**
 * 将病人信息填入患者信息修改form
 * @param patinet
 */
function fillPlusPatinet(patinet) {
    if (patinet != null) {
        $("#editUserCode").val(patinet.patientId);
        $("#editUserName").val(patinet.name);
        $("#editUserName").blur();
        $("#editUserAge").val(patinet.age);
        $("#editUserAge").blur();
        $("#editUserGender").selectpicker('val', patinet.sex);
        $("#editUserGender").selectpicker('refresh');
        $("#editUserGender").blur();
        $("#editUserBirthDay").val(patinet.birthDayStr);
        $("#editUserBirthDay").blur();
        $("#editUserCardNo").val(patinet.icCardNo);
        $("#editUserCardNo").attr("title", patinet.icCardNo);
        $("#editUserCardNo").blur();
        $("#editUserPhoneNum").val(patinet.phoneNo);
        $("#editUserPhoneNum").attr("title", patinet.phoneNo);
        $("#editUserPhoneNum").blur();
        $("#editUserPatientsNature").selectpicker('val', patinet.responseType);//默认选中
        $('#editUserPatientsNature').selectpicker('refresh');
        $("#editUserPatientsNature").blur();
        $("#editUserIdCard").val(patinet.socialNo);
        $("#editUserIdCard").attr("title", patinet.socialNo);
        $("#editUserIdCard").blur();
        $("#editUserAddress").val(patinet.address);
        $("#editUserAddress").blur();
        $("#editUserContact").val(patinet.relName);
        $("#editUserContactPhone").val(patinet.contractName);
    }
}

/**
 * 关闭当前这个付款方式
 */
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());
        if ($(obj).attr("id") == "birthDay") {
            $(obj).blur()
        }
    }
}

/**
 * 当按照卡号查询时，病人信息输入框不可编辑，当清空输入框时可编辑
 * @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");
    }

}


/**
 * 查询默认打印机
 */
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 savePatient() {
    $.ajax({
        type: "POST",
        url: '/thmz/savePatient',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        data: JSON.stringify({
            "name": $("#userName").val(),
            "age": $("#age").val(),
            "sex": $("#gender").val(),
            "birthDay": $("#birthDay").val(),
            "icCardNo": $("#cardNo").val(),
            "phoneNo": $("#phoneNum").val(),
            "responseType": $("#patientsNature").val(),
            "socialNo": $("#idCard").val(),
            "address": $("#address").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) {
                $("#patientId").val(res.data.patientId);
                saveMzyReqrec();
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
        }
    });
}


/**
 * 修改病人信息
 */
function modifyPatient() {
    $.ajax({
        type: "POST",
        url: '/thmz/modifyPatient',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        data: JSON.stringify({
            "name": $("#editUserName").val(),
            "age": $("#editUserAge").val(),
            "sex": $("#editUserGender").val(),
            "birthDay": $("#editUserBirthDay").val(),
            "icCardNo": $("#editUserCardNo").val(),
            "phoneNo": $("#editUserPhoneNum").val(),
            "responseType": $("#editUserPatientsNature").val(),
            "socialNo": $("#editUserIdCard").val(),
            "address": $("#editUserAddress").val(),
            "patientId": $("#editUserCode").val(),
            "relName": $("#editUserContact").val(),
            "contractName": $("#editUserContactPhone").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) {
                $('#editUserModal').modal('hide');
                fillPatinet($("#patientId").val());
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
        }
    });
}


/**
 * 保存挂号信息
 */
function saveMzyReqrec() {
    var mzyRequestId = $('#doctor').find("option:selected").attr('data-mzyRequestId');
    var patientId = $("#patientId").val();
    $.ajax({
        type: "POST",
        url: '/thmz/saveMzyReqrec',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        data: JSON.stringify({
            "mzyReqrec": {
                "patientId": patientId,
                "ampm": $("#ampm").val(),
                "unitCode": $("#deptNo").val(),
                "chargeType": $("#chargeType").val(),
                "paymode": $("#payType").val()
            }, "responceType": $("#patientsNature").val(), "mzyRequestId": mzyRequestId
        }),
        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'
                });
                $('#confirmFeeModal').modal('hide');
                prn1Print(patientId, -1);
                loadTableCount();
                loadRegistrationList(true);
                clearRegistration();
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
        }
    });
}

/**
 * 挂号列表中的科室和医生列表初始化
 */
function initListSelect() {
    initListDeptSelect();
    initListDoctorSelect();
}

/**
 * 挂号列表中的科室列表
 */
function initListDeptSelect() {
    //科室列表
    $.ajax({
        type: "GET",
        url: '/thmz/allMzUnitCode',
        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>';
            });
            $('#deptNoParam').empty();
            $('#deptNoParam').html(html);
            $('#deptNoParam').selectpicker('refresh');
        }
    });
}

/**
 * 挂号列表中的医生列表初始化
 */
function initListDoctorSelect() {
    //医生列表
    $.ajax({
        type: "GET",
        url: '/thmz/listEmployeeByDepts?depts=' + $('#deptNoParam').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.employeeCode + '">' + comment.employeeName + '</option>';
            });
            $('#doctorParam').empty();
            $('#doctorParam').html(html);
            // $("#doctorParam").selectpicker({
            //     size: 10
            // });
            $('#doctorParam').selectpicker('destroy').selectpicker('refresh');
        }
    });
}

/**
 * 加载挂号列表统计数据
 */
function loadTableCount() {
    var rePortRangeArr = getRePortRangeArr();
    $.ajax({
        type: "POST",
        url: '/thmz/getCountByParams',
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify({
            "mzyReqrec": {
                "unitCode": $("#deptNoParam").val(),
                "doctorCode": $("#doctorParam").val(),
                "name": $("#userNameParam").val(),
                "serialNo": $("#serialNoParams").val()
            },
            "beginTime": new Date(rePortRangeArr[0]),
            "endTime": new Date(rePortRangeArr[1]),
            "phoneNo": $("#phoneParam").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) {
                $("#registrationNum").text(res.registrationNum);
                $("#haveClinicalNum").text(res.haveClinicalNum);
                $("#backNoNum").text(res.backNoNum);
            }
        }
    });
}


/**
 * 加载挂号列表
 * @param flag 是否清空挂号卡片列表区域
 */
function loadRegistrationList(flag) {
    if (flag) {
        pageIndex = 0;
        $("#card_regi_list").empty();
        $("div.page").removeClass("in").addClass("hide");
    }
    var regiListType = getIndex("regi_List_type");
    if (regiListType == 0) {
        loadCardList();
    } else if (regiListType == 1) {
        loadTableList();
    }
}

/**
 * 加载卡片列表
 */
function loadCardList() {
    $('#tb_regi_list').bootstrapTable("destroy");
    isTableListInit = false;
    var rePortRangeArr = getRePortRangeArr();
    var regiListBtnGroup = getIndex("regi_List_btn_group");
    var dataParams = JSON.stringify({
        "mzyReqrec": {
            "unitCode": $("#deptNoParam").val(),
            "doctorCode": $("#doctorParam").val(),
            "name": $("#userNameParam").val(),
            "serialNo": $("#serialNoParams").val()
        },
        "beginTime": new Date(rePortRangeArr[0]),
        "endTime": new Date(rePortRangeArr[1]),
        "pageSize": 8,
        "pageIndex": pageIndex,
        "phoneNo": $("#phoneParam").val()
    });
    if (regiListBtnGroup == 1) {
        dataParams = JSON.stringify({
            "mzyReqrec": {
                "unitCode": $("#deptNoParam").val(),
                "doctorCode": $("#doctorParam").val(),
                "name": $("#userNameParam").val(),
                "serialNo": $("#serialNoParams").val(),
                "visitedMark": 0,
                "cancelMark": 0
            },
            "beginTime": new Date(rePortRangeArr[0]),
            "endTime": new Date(rePortRangeArr[1]),
            "pageSize": 8,
            "pageIndex": pageIndex,
            "phoneNo": $("#phoneParam").val()
        });
    } else if (regiListBtnGroup == 2) {
        dataParams = JSON.stringify({
            "mzyReqrec": {
                "unitCode": $("#deptNoParam").val(),
                "doctorCode": $("#doctorParam").val(),
                "name": $("#userNameParam").val(),
                "serialNo": $("#serialNoParams").val(),
                "visitedMark": 1,
                "cancelMark": 0
            },
            "beginTime": new Date(rePortRangeArr[0]),
            "endTime": new Date(rePortRangeArr[1]),
            "pageSize": 8,
            "pageIndex": pageIndex,
            "phoneNo": $("#phoneParam").val()
        });
    } else if (regiListBtnGroup == 3) {
        dataParams = JSON.stringify({
            "mzyReqrec": {
                "unitCode": $("#deptNoParam").val(),
                "doctorCode": $("#doctorParam").val(),
                "name": $("#userNameParam").val(),
                "serialNo": $("#serialNoParams").val(),
                "cancelMark": 1
            },
            "beginTime": new Date(rePortRangeArr[0]),
            "endTime": new Date(rePortRangeArr[1]),
            "pageSize": 8,
            "pageIndex": pageIndex,
            "phoneNo": $("#phoneParam").val()
        });
    }
    $.ajax({
        type: "POST",
        url: '/thmz/listMzyReqrec',
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: dataParams,
        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) {
                pageIndex++;
                $("#totalNum").text(res.pageViewVo.remainder);
                if (res.pageViewVo.remainder <= 0) {
                    $("div.page").removeClass("in").addClass("hide");
                } else {
                    $("div.page").removeClass("hide").addClass("in");
                }
                var data = res.pageViewVo.data;
                for (var i = 0; i < data.length; i++) {
                    var mzyReqrecVo = data[i];
                    var color = "registration-no-color";
                    var text = '挂号</label>/<label>挂号</label>';
                    if (mzyReqrecVo.mzyReqrec.cancelMark == 0) {
                        if (mzyReqrecVo.mzyReqrec.visitedMark == 1) {
                            text = '已诊</label>/<label>挂号</label>';
                            color = "haveClinical-no-color";
                        }
                    } else if (mzyReqrecVo.mzyReqrec.cancelMark == 1) {
                        text = '退号</label>/<label>挂号</label>';
                        color = "back-no-color";
                    }
                    var sex = "未知";
                    var html = '<div class="col-md-3 col-sm-3 col-xs-12 cardList"><div class="card__body"><div class="patient-card-main ' + color + '"><div class="patient-card-main-left"><div class="img-row">';
                    if (mzyReqrecVo.mzPatientMi.sex == 0) {
                        html += '<img src="/thmz/images/girl_or_boy.png"/>';
                    } else if (mzyReqrecVo.mzPatientMi.sex == 1) {
                        sex = "男";
                        html += '<img src="/thmz/images/boy.png"/>';
                    } else if (mzyReqrecVo.mzPatientMi.sex == 2) {
                        sex = "女";
                        html += '<img src="/thmz/images/girl.png"/>';
                    }
                    html += '</div><div class="el-row" title="' + mzyReqrecVo.mzyReqrec.name + '">' + mzyReqrecVo.mzyReqrec.name + '</div>';
                    if (mzyReqrecVo.mzPatientMi.responseType.length > 2) {
                        html += '<div class="el-row" style="font-size: 1px;height: 25%;">';
                    } else {
                        html += '<div class="el-row" style="font-size: 1px;">';
                    }
                    html += mzyReqrecVo.mzPatientMi.responseType + '</div></div><div class="patient-card-main-right"><div></div> <div class="el-row"><label>';
                    html += text;
                    html += '</div><div class="el-row" title="' + mzyReqrecVo.mzPatientMi.phoneNo + '">' + sex + ' / ' + mzyReqrecVo.mzPatientMi.age + '岁 / ' + mzyReqrecVo.mzPatientMi.phoneNo + '</div><div class="el-row" title="' + mzyReqrecVo.mzyReqrec.ampm + '">' + mzyReqrecVo.mzyReqrec.ampm + ' / ' + mzyReqrecVo.mzyReqrec.chargeType + '</div><div class="el-row" title="' + mzyReqrecVo.mzyReqrec.chargeType + '">' + mzyReqrecVo.mzyReqrec.unitCode + ' / ' + mzyReqrecVo.mzyReqrec.doctorCode + '</div><div class="el-row">' + format(mzyReqrecVo.mzyReqrec.requestDay, "yyyy-MM-dd HH:mm:ss") + '</div></div></div>';
                    if (mzyReqrecVo.mzyReqrec.cancelMark == 1) {
                        html += '<div class="patient-card-foot">' +
                            '                        <div class="col-md-3 col-sm-3 col-xs-12">' +
                            '                            <button type="button" class="can-not-used"' +
                            '                                    title="修改挂号">' +
                            '                                <i class="fa fa-edit"></i>' +
                            '                            </button>' +
                            '                        </div>' +
                            '                        <div class="col-md-3 col-sm-3 col-xs-12">' +
                            '                            <button type="button" class="registration-no-color-foot-button"' +
                            '                                    title="修改患者" onclick="editUserModal(\'' + mzyReqrecVo.mzyReqrec.patientId + '\')">' +
                            '                                <i class="fa fa-user"></i>' +
                            '                            </button>' +
                            '                        </div>' +
                            // '                        <div class="col-md-2 col-sm-2 col-xs-12">' +
                            // '                            <button type="button" class="registration-no-color-foot-button"' +
                            // '                                    title="修改收款方式" onclick="editPayMode(\'' + mzyReqrecVo.mzyReqrec.patientId + '\','+mzyReqrecVo.mzyReqrec.times+',\''+mzyReqrecVo.mzyReqrec.paymode+'\','+mzyReqrecVo.mzyReqrec.dcountNo+')">' +
                            // '                                <i class="fa fa-credit-card"></i>' +
                            // '                            </button>' +
                            // '                        </div>' +
                            '                        <div class="col-md-3 col-sm-3 col-xs-12">' +
                            '                            <button type="button" class="can-not-used"' +
                            '                                    title="退号">' +
                            '                                <i class="fa fa-minus-square-o"></i>' +
                            '                            </button>' +
                            '                        </div>' +
                            '                        <div class="col-md-3 col-sm-3 col-xs-12">' +
                            '                            <button type="button" class="can-not-used"' +
                            '                                    title="打印">' +
                            '                                <i class="fa fa-print"></i>' +
                            '                            </button>' +
                            '                        </div>' +
                            '                    </div>';
                    }
                    if (mzyReqrecVo.mzyReqrec.visitedMark == 1) {
                        html += '<div class="patient-card-foot">' +
                            '                        <div class="col-md-3 col-sm-3 col-xs-12">' +
                            '                            <button type="button" class="can-not-used"' +
                            '                                    title="修改挂号">' +
                            '                                <i class="fa fa-edit"></i>' +
                            '                            </button>' +
                            '                        </div>' +
                            '                        <div class="col-md-3 col-sm-3 col-xs-12">' +
                            '                            <button type="button" class="registration-no-color-foot-button"' +
                            '                                    title="修改患者" onclick="editUserModal(\'' + mzyReqrecVo.mzyReqrec.patientId + '\')">' +
                            '                                <i class="fa fa-user"></i>' +
                            '                            </button>' +
                            '                        </div>' +
                            // '                        <div class="col-md-2 col-sm-2 col-xs-12">' +
                            // '                            <button type="button" class="registration-no-color-foot-button"' +
                            // '                                    title="修改收款方式" onclick="editPayMode(\'' + mzyReqrecVo.mzyReqrec.patientId + '\','+mzyReqrecVo.mzyReqrec.times+',\''+mzyReqrecVo.mzyReqrec.paymode+'\','+mzyReqrecVo.mzyReqrec.dcountNo+')">' +
                            // '                                <i class="fa fa-credit-card"></i>' +
                            // '                            </button>' +
                            // '                        </div>' +
                            '                        <div class="col-md-3 col-sm-3 col-xs-12">' +
                            '                            <button type="button" class="can-not-used"' +
                            '                                    title="退号">' +
                            '                                <i class="fa fa-minus-square-o"></i>' +
                            '                            </button>' +
                            '                        </div>' +
                            '                        <div class="col-md-3 col-sm-3 col-xs-12">';
                        if (mzyReqrecVo.mzyReqrec.paymode == "本院记账") {
                            html += '                            <button type="button" class="registration-no-color-foot-button"  title="退记账重收" onclick="chargeFeeForByjz(\'' + mzyReqrecVo.mzyReqrec.serialNo + '\')">';
                            html += '                                <i class="fa fa-rmb"></i>';
                        } else {
                            var printFlag = isEmpty(mzyReqrecVo.mzyReqrec.printerId);
                            if (printFlag) {
                                html += '                            <button type="button" class="registration-no-color-foot-button"  title="打印" onclick="prn1Print(\'' + mzyReqrecVo.mzyReqrec.patientId + '\',' + mzyReqrecVo.mzyReqrec.times + ')">';
                            } else {
                                html += '                            <button type="button" class="can-not-used" title="打印">';
                            }
                            html += '                                <i class="fa fa-print"></i>';
                        }
                        html += '                            </button>' +
                            '                        </div>' +
                            '                    </div>';
                    } else {
                        html += '<div class="patient-card-foot">' +
                            '                        <div class="col-md-3 col-sm-3 col-xs-12">' +
                            '                            <button type="button" class="can-not-used"' +
                            '                                    title="修改挂号">' +
                            '                                <i class="fa fa-edit"></i>' +
                            '                            </button>' +
                            '                        </div>' +
                            '                        <div class="col-md-3 col-sm-3 col-xs-12">' +
                            '                            <button type="button" class="registration-no-color-foot-button"' +
                            '                                    title="修改患者" onclick="editUserModal(\'' + mzyReqrecVo.mzyReqrec.patientId + '\')">' +
                            '                                <i class="fa fa-user"></i>' +
                            '                            </button>' +
                            '                        </div>' +
                            // '                        <div class="col-md-2 col-sm-2 col-xs-12">' +
                            // '                            <button type="button" class="registration-no-color-foot-button"' +
                            // '                                    title="修改收款方式" onclick="editPayMode(\'' + mzyReqrecVo.mzyReqrec.patientId + '\','+mzyReqrecVo.mzyReqrec.times+',\''+mzyReqrecVo.mzyReqrec.paymode+'\','+mzyReqrecVo.mzyReqrec.dcountNo+')">' +
                            // '                                <i class="fa fa-credit-card"></i>' +
                            // '                            </button>' +
                            // '                        </div>' +
                            '                        <div class="col-md-3 col-sm-3 col-xs-12">' +
                            '                            <button type="button" class="registration-no-color-foot-button"' +
                            '                                    title="退号" onclick="backNoModal(\'' + mzyReqrecVo.mzyReqrec.patientId + '\',' + mzyReqrecVo.mzyReqrec.times + ')">' +
                            '                                <i class="fa fa-minus-square-o"></i>' +
                            '                            </button>' +
                            '                        </div>' +
                            '                        <div class="col-md-3 col-sm-3 col-xs-12">';
                        if (mzyReqrecVo.mzyReqrec.paymode == "本院记账") {
                            html += '                            <button type="button" class="registration-no-color-foot-button"  title="退记账重收" onclick="chargeFeeForByjz(\'' + mzyReqrecVo.mzyReqrec.serialNo + '\')">';
                            html += '                                <i class="fa fa-rmb"></i>';
                        } else {
                            var printFlag = isEmpty(mzyReqrecVo.mzyReqrec.printerId);
                            if (printFlag) {
                                html += '                            <button type="button" class="registration-no-color-foot-button"  title="打印" onclick="prn1Print(\'' + mzyReqrecVo.mzyReqrec.patientId + '\',' + mzyReqrecVo.mzyReqrec.times + ')">';
                            } else {
                                html += '                            <button type="button" class="can-not-used" title="打印">';
                            }
                            html += '                                <i class="fa fa-print"></i>';
                        }
                        html += '                            </button>' +
                            '                        </div>' +
                            '                    </div>';
                    }
                    html += '</div></div>';
                    $("#card_regi_list").append(html);
                }
            }
        }
    });
}

/**
 * 加载表格列表
 */
function loadTableList() {
    if (isTableListInit) {
        $('#tb_regi_list').bootstrapTable('refresh');
    } else {
        isTableListInit = true;
        $('#tb_regi_list').bootstrapTable({
            url: '/thmz/listMzyReqrec',         //请求后台的URL（*）
            method: 'post',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            sortable: true,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: 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,
            //rowStyle:rowStyle,//通过自定义函数设置行样式
            ajaxOptions: {
                headers: {
                    'Accept': 'application/json',
                    'Authorization': 'Bearer ' + localStorage.getItem("token")
                }
            },
            columns: [
                {
                    field: 'mzyReqrec.patientId',
                    title: '病人ID',
                    align: "center",
                    valign: 'middle',
                    // sortable: true
                },{
                    field: 'mzyReqrec.times',
                    title: '就诊次数',
                    align: "center",
                    valign: 'middle',
                    // sortable: true
                },{
                    field: 'mzyReqrec.name',
                    title: '病人姓名',
                    align: "center",
                    valign: 'middle',
                    // sortable: true
                }, {
                    field: 'mzPatientMi.responseType',
                    title: '病人性质',
                    align: "center",
                    valign: 'middle',
                    // sortable: true
                }, {
                    field: 'mzPatientMi.sex',
                    title: '性别',
                    align: "center",
                    valign: 'middle',
                    //sortable: true,
                    formatter: function (value, row, index) {
                        if (value == '1') {
                            return "男";
                        } else if (value == '2') {
                            return "女";
                        } else if (value == '0') {
                            return "未知";
                        }

                    }
                },
                // {
                //     field: 'mzPatientMi.age',
                //     title: '年龄',
                //     align: "center",
                //     valign: 'middle',
                //     //  sortable: true
                // }, {
                //     field: 'mzPatientMi.phoneNo',
                //     title: '电话',
                //     align: "center",
                //     valign: 'middle',
                //     // sortable: true,
                // },
                {
                    field: 'mzyReqrec.cancelMark',
                    title: '就诊状态',
                    align: "center",
                    valign: 'middle',
                    //  sortable: true,
                    formatter: function (value, row, index) {
                        var text = '<span style="color:#26c175">挂号</span>';
                        if (value == 0) {
                            if (row.mzyReqrec.visitedMark == 1) {
                                text = '<span style="color:#6778ed">已诊</span>';
                            }
                        } else if (value == 1) {
                            text = '<span style="color:#ff6b91">退号</span>';
                        }
                        return text;
                    }
                }, {
                    field: 'mzyReqrec.ampm',
                    title: '号段',
                    align: "center",
                    valign: 'middle',
                    // sortable: true
                }, {
                    field: 'mzyReqrec.unitCode',
                    title: '挂号科室',
                    align: "center",
                    valign: 'middle',
                    // sortable: true
                }, {
                    field: 'mzyReqrec.chargeType',
                    title: '号别',
                    align: "center",
                    valign: 'middle',
                    // sortable: true
                }, {
                    field: 'mzyReqrec.doctorCode',
                    title: '挂号医生',
                    align: "center",
                    valign: 'middle',
                    // sortable: true
                }, {
                    field: 'mzyReqrec.requestDay',
                    title: '挂号时间',
                    align: "center",
                    valign: 'middle',
                    // sortable: true,
                    formatter: function (value, row, index) {
                        return format(value, "yyyy-MM-dd HH:mm:ss");
                    }
                }, {
                    title: '操作',
                    align: "center",
                    valign: 'middle',
                    // sortable: true,
                    formatter: function (value, row, index) {
                        if (row.mzyReqrec.cancelMark == 1) {
                            return '<button type="button" class="can-not-used" title="修改挂号"><i class="fa fa-edit"></i></button><button type="button" class="registration-no-color-foot-button"title="修改患者" onclick="editUserModal(\'' + row.mzyReqrec.patientId + '\')"><i class="fa fa-user"></i></button>' +
                         //       '<button type="button" class="registration-no-color-foot-button" title="修改收款方式" onclick="editPayMode(\'' + row.mzyReqrec.patientId + '\','+row.mzyReqrec.times+',\''+row.mzyReqrec.paymode+'\','+row.mzyReqrec.dcountNo+')"><i class="fa fa-credit-card"></i></button>' +
                                '<button type="button" class="can-not-used" title="退号"><i class="fa fa-minus-square-o"></i></button><button type="button" class="can-not-used" title="打印" ><i class="fa fa-print"></i></button>';
                        }
                        if (row.mzyReqrec.visitedMark == 1) {
                            var html = '<button type="button" class="can-not-used" title="修改挂号"><i class="fa fa-edit"></i></button><button type="button" class="registration-no-color-foot-button"title="修改患者" onclick="editUserModal(\'' + row.mzyReqrec.patientId + '\')"><i class="fa fa-user"></i></button>' +
                               // '<button type="button" class="registration-no-color-foot-button" title="修改收款方式" onclick="editPayMode(\'' + row.mzyReqrec.patientId + '\',\''+row.mzyReqrec.times+','+row.mzyReqrec.paymode+'\','+row.mzyReqrec.dcountNo+')"><i class="fa fa-credit-card"></i></button>' +
                                '<button type="button" class="can-not-used" title="退号"><i class="fa fa-minus-square-o"></i></button>';
                            if (row.mzyReqrec.paymode == "本院记账") {
                                html += '                            <button type="button" class="registration-no-color-foot-button"  title="退记账重收" onclick="chargeFeeForByjz(\'' + row.mzyReqrec.serialNo + '\')">';
                                html += '<i class="fa fa-rmb"></i></button>';
                            } else {
                                var printFlag = isEmpty(row.mzyReqrec.printerId);
                                if (printFlag) {
                                    html += '                            <button type="button" class="registration-no-color-foot-button"  title="打印" onclick="prn1Print(\'' + row.mzyReqrec.patientId + '\',' + row.mzyReqrec.times + ')">';
                                } else {
                                    html += '                            <button type="button" class="can-not-used" title="打印">';
                                }
                                html += '<i class="fa fa-print"></i></button>';
                            }
                            return html;

                        }
                        var html = '<button type="button" class="can-not-used" title="修改挂号"><i class="fa fa-edit"></i></button><button type="button" class="registration-no-color-foot-button"title="修改患者" onclick="editUserModal(\'' + row.mzyReqrec.patientId + '\')"><i class="fa fa-user"></i></button>' +
                           // '<button type="button" class="registration-no-color-foot-button" title="修改收款方式" onclick="editPayMode(\'' + row.mzyReqrec.patientId + '\','+row.mzyReqrec.times+',\''+row.mzyReqrec.paymode+'\','+row.mzyReqrec.dcountNo+')"><i class="fa fa-credit-card"></i></button>' +
                            '<button type="button" class="registration-no-color-foot-button" title="退号" onclick="backNoModal(\'' + row.mzyReqrec.patientId + '\',' + row.mzyReqrec.times + ')"><i class="fa fa-minus-square-o"></i></button>';
                        if (row.mzyReqrec.paymode == "本院记账") {
                            html += '                            <button type="button" class="registration-no-color-foot-button"  title="退记账重收" onclick="chargeFeeForByjz(\'' + row.mzyReqrec.serialNo + '\')">';
                            html += '<i class="fa fa-rmb"></i></button>';
                        } else {
                            var printFlag = isEmpty(row.mzyReqrec.printerId);
                            if (printFlag) {
                                html += '                            <button type="button" class="registration-no-color-foot-button"  title="打印" onclick="prn1Print(\'' + row.mzyReqrec.patientId + '\',' + row.mzyReqrec.times + ')">';
                            } else {
                                html += '                            <button type="button" class="can-not-used" title="打印">';
                            }
                            html += '<i class="fa fa-print"></i></button>';
                        }
                        return html;
                    }
                }],
            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: true,
                        styling: 'bootstrap3'
                    });
                    return {
                        "total": 0,//总页数
                        "rows": {}   //数据
                    };
                }
                return {
                    "total": ress.pageViewVo.total,//总页数
                    "rows": ress.pageViewVo.data   //数据
                };
            },
        });
    }
}


/**
 * 得到查询的参数
 * @param params
 * @returns {{mzyReqrec: {unitCode: string | number | string[] | undefined | jQuery, doctorCode: string | number | string[] | undefined | jQuery, name: string | number | string[] | undefined | jQuery}, beginTime: Date, endTime: Date, pageSize: *, pageIndex: number}}
 */
function queryParams(params) {
    var rePortRangeArr = getRePortRangeArr();
    var regiListBtnGroup = getIndex("regi_List_btn_group");
    var temp = {
        mzyReqrec: {
            unitCode: $("#deptNoParam").val(),
            doctorCode: $("#doctorParam").val(),
            name: $("#userNameParam").val(),
            serialNo: $("#serialNoParams").val()
        },
        beginTime: new Date(rePortRangeArr[0]),
        endTime: new Date(rePortRangeArr[1]),
        pageSize: params.limit,   //页面大小
        pageIndex: params.offset / params.limit,  //页码
        phoneNo: $("#phoneParam").val()
    };
    if (regiListBtnGroup == 1) {
        temp = {
            mzyReqrec: {
                unitCode: $("#deptNoParam").val(),
                doctorCode: $("#doctorParam").val(),
                name: $("#userNameParam").val(),
                serialNo: $("#serialNoParams").val(),
                visitedMark: 0,
                cancelMark: 0
            },
            beginTime: new Date(rePortRangeArr[0]),
            endTime: new Date(rePortRangeArr[1]),
            pageSize: params.limit,   //页面大小
            pageIndex: params.offset / params.limit,  //页码
        };
    } else if (regiListBtnGroup == 2) {
        temp = {
            mzyReqrec: {
                unitCode: $("#deptNoParam").val(),
                doctorCode: $("#doctorParam").val(),
                name: $("#userNameParam").val(),
                serialNo: $("#serialNoParams").val(),
                visitedMark: 1,
                cancelMark: 0
            },
            beginTime: new Date(rePortRangeArr[0]),
            endTime: new Date(rePortRangeArr[1]),
            pageSize: params.limit,   //页面大小
            pageIndex: params.offset / params.limit,  //页码
        };
    } else if (regiListBtnGroup == 3) {
        temp = {
            mzyReqrec: {
                unitCode: $("#deptNoParam").val(),
                doctorCode: $("#doctorParam").val(),
                name: $("#userNameParam").val(),
                serialNo: $("#serialNoParams").val(),
                cancelMark: 1
            },
            beginTime: new Date(rePortRangeArr[0]),
            endTime: new Date(rePortRangeArr[1]),
            pageSize: params.limit,   //页面大小
            pageIndex: params.offset / params.limit,  //页码
        };
    }
    return temp;
};

/**
 * 根据是挂号还是已诊或是退号 设置行的颜色
 * @param row
 * @param index
 * @returns {*}
 */
function rowStyle(row, index) {
    var style = {css: {'background': 'linear-gradient(130deg, #06c7d6, #26c175) !important;'}};
    if (row.mzyReqrec.cancelMark == 0) {
        if (row.mzyReqrec.visitedMark == 1) {
            style = {css: {'background': 'linear-gradient(130deg, #41a6f5, #6778ed) !important;'}};
        }
    } else if (row.mzyReqrec.cancelMark == 1) {
        style = {css: {'background': 'linear-gradient(130deg, #ff9e70, #ff6b91) !important;'}};
    }
    return style;
}

/**
 * 获取按钮组选择的下标
 * @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;
}

/**
 * 获取时间选择器的时间数组
 * @returns {string[]}
 */
function getRePortRangeArr() {
    var rePortRange = $('#reportrange span').html();
    var rePortRangeArr = rePortRange.split(" - ");
    rePortRangeArr[0] = rePortRangeArr[0] + " 00:00:00"
    rePortRangeArr[1] = rePortRangeArr[1] + " 23:59:59"
    return rePortRangeArr;
}

/**
 * 清空搜索参数
 */
function clearParams() {
    $("#deptNoParam").selectpicker('val', null);
    $("#deptNoParam").selectpicker('refresh');
    $("#doctorParam").selectpicker('val', null);
    $("#deptNoParam").selectpicker('refresh');
    $("#userNameParam").val(null);
    $("#phoneParam").val(null);
    $('#reportrange span').html(moment().format('YYYY-MM-DD') + ' - ' + moment().format('YYYY-MM-DD'));
}


/**
 * 保存退号信息
 */
function saveBackNo() {
    $.ajax({
        type: "POST",
        url: '/thmz/updateReqrec',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        data: JSON.stringify({
            "patientId": $("#backNoPatientId").val(),
            "times": $("#backNoTimes").val(),
            "cancelMark": 1
        }),
        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'
                });
                loadTableCount();
                loadRegistrationList(true);
                $("#backNoModal").modal("hide");
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
        }
    });
}


/**
 * 清空挂号信息
 */
function clearRegistration() {
    $("#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);
    $("#patientId").val(null);
    $("#editUser").hide();
    //默认光标在卡号输入框
    $("#cardNo").focus();
    initMzWorkTime();
    readonlyOrNot(false);
}


/**
 * 打开退费重收确认弹框
 * @param serialNo
 */
function chargeFeeForByjz(serialNo) {
    $("#serialNo").val(serialNo);
    $("#confirmFeeModal").modal();
}


/**
 * 直接打印发票
 * @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);
                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.reqOrder);
                LODOP.ADD_PRINT_TEXT("47mm", "6mm", "50mm", "3mm", "挂号费:" + temp.reqFee);
                LODOP.ADD_PRINT_TEXT("47mm", "56mm", "50mm", "3mm", "诊查费:" + temp.clinicFee);
                LODOP.ADD_PRINT_TEXT("52mm", "6mm", "50mm", "3mm", "其他:" + temp.othFee);
                LODOP.ADD_PRINT_TEXT("52mm", "56mm", "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) {
                    loadTableCount();
                    loadRegistrationList(true);
                }
            } else if (res.code == -1) {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
        }
    });
};


//判断字符是否为空的方法
function isEmpty(obj) {
    if (typeof obj == "undefined" || obj == null || obj == "") {
        return true;
    } else {
        return false;
    }
}


/**
 * 导出excel
 */
function exportExcel() {
    var rePortRangeArr = getRePortRangeArr();
    var regiListBtnGroup = getIndex("regi_List_btn_group");
    var visitedMark = "";
    var cancelMark = "";
    if (regiListBtnGroup == 1) {
        visitedMark = 0;
        cancelMark = 0;
    } else if (regiListBtnGroup == 2) {
        visitedMark = 1;
        cancelMark = 0;
    } else if (regiListBtnGroup == 3) {

        cancelMark = 1;
    }
    window.location.href = "/thmz/exportListMzyReqrec?beginTime=" + rePortRangeArr[0] + "&endTime=" + rePortRangeArr[1] + "&name=" + $("#userNameParam").val()
        + "&unitCode=" + $("#deptNoParam").val() + "&doctorCode=" + $("#doctorParam").val() + "&phoneNo=" + $("#phoneParam").val() + "&serialNo=" + $("#serialNoParams").val() + "&visitedMark="
        + visitedMark + "&cancelMark=" + cancelMark;
}


/**
 * 修改收款方式
 * @param patientId
 * @param times
 * @param paymode
 */
function editPayMode(patientId,times,paymode,dcountNo) {
    var message = "当前病人本次挂号的收费方式为【"+paymode+"】，确定需要修改吗？";
    if(dcountNo==1){
        message = "当前病人本次挂号的收费方式为【"+paymode+"】，且本次挂号已经结算，确定需要修改吗？如仍需继续修改，会影响已经结算的报表，请重新打印本次挂号所在日期的【日结报表】！";
    }
    $("#editPayModeTip").html(message);
    $("#patientId").val(patientId);
    $("#times").val(times);
    $('#payTypeEditPayMode').selectpicker('val', 1);
    $('#payTypeEditPayMode').selectpicker('refresh');
    $("#editPayModeModal").modal();
}


/**
 * 提交修改收款方式
 */
function saveEditPayMode(){
    $.ajax({
        type: "GET",
        url: '/thmz/updatePayMode?patientId=' + $("#patientId").val() + "&times=" + $("#times").val()+"&payMode="+$("#payTypeEditPayMode").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) {
                successMesage(res);
                clearEditPayMode();
                $("#editPayModeModal").modal("hide");
                loadRegistrationList(true);
            } else if (res.code == -1) {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
        }
    });
}

/**
 * 清空
 */
function clearEditPayMode() {
    $("#patientId").val(null);
    $("#times").val(null);
}