//@ sourceURL=actpatient.js
var LODOP; //声明为全局变量
//默认打印机下标
var printIndex = -1;
//选中的要退的费用收费编码
var chargeItemCodes = null;
$(function () {
    //默认光标在卡号输入框
    $("#cardNo").focus();
    init_daterangepicker();
    $('#myDatepicker').datetimepicker({
        language: 'zh-CN',
        format: 'yyyy-mm-dd hh:ii:ss'
    });
    //$('#reportrange span').html('1970-01-01 - 1970-01-01');
    // var firstDate= new Date("1970-01-01");
    $('#reportrange span').html(moment(new Date('2012')).startOf('year').format('YYYY-MM-DD') + ' - ' + moment(new Date()).format("YYYY-MM-DD"));
    initSelect();
    initFeeTable();
    //卡号输入改变事件
    cardNoChange();

    //重置查询参数
    $('#btn_clean').click(function () {
        cleanParams();
    });
    //初始化页面上面的按钮事件
    //查询
    $('#btn_query').click(function () {
        initFeeTable();
    });

    /**
     * 增加收款方式按钮事件
     */
    $("#addPayType").on("click", function () {
        addPayType(null);
    });

    //初始住院收银方式下拉选
    initChequeType("payType");
    setTimeout(function () {
        getLodop();
    }, 800);

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

//     /**
//      * 设置窗口号
//      */
//     $("#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();
//     });
    postCMD("login", localStorage.getItem("userID"), '000000', '收费项目', 0, 0, 0, '', '祝您早日康复', 0, 0, 0);
    // setTimeout(function () {
    //     postCMD("login",localStorage.getItem("userID"),'000000','收费项目',0,0,0, '','祝您早日康复',0,0,0);
    // }, 3000);
});

/**
 * 列表类型按钮切换事件
 * @param object
 * @param realIndex 下标
 */
function payMarkButtonChange(object, realIndex) {
    $("#pay_mark_group").find("button").each(function (index, element) {
        if ($(element).hasClass("btn-primary")) {
            $(element).removeClass("btn-primary").addClass("btn-default");
        }
    });
    if (realIndex == 0) {
        $("#timeParams").html("入院时间");
    } else {
        $("#timeParams").html("出院时间");
    }
    $(object).removeClass("btn-default").addClass("btn-primary");
    initFeeTable();
}


/**
 * 初始化下拉选
 */
function initSelect() {
    $(".selectpicker").selectpicker({
        dropuAuto: false
    });
    initListDeptSelect();
    var dismissFlag = '<option value="1">出院结算</option><option value="2">中间断账</option>';
    $('#dismissFlag').html(dismissFlag);
    $('#dismissFlag').selectpicker('refresh');
    $("#dismissFlag").selectpicker('val', 1);//默认选中
    $("#dismissFlag").selectpicker('refresh');
}


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


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

var $table_1;

/**
 * 初始化收费表格
 */
function initFeeTable() {
    var payMarkGroup = getIndex("pay_mark_group");
    var visible = false;
    if (payMarkGroup == 1) {
        visible = true;
    }
    $('#tb_table').bootstrapTable("destroy");
    $table_1 = $('#tb_table').bootstrapTable({
        url: '/thmz/getZyActpatientByInpatientNoOrMzNO',         //请求后台的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: [5, 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: [
            // {
            //     checkbox: true
            // },
            {
                field: 'mzNo',
                title: '门诊ID',
                align: "center",
                valign: 'middle',
            },
            {
                field: 'zySerialNo',
                title: '住院流水号',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return Math.abs(value);
                }
            }, {
                field: 'inpatientNo',
                title: '住院号',
                align: "center",
                valign: 'middle',
            }, {
                field: 'name',
                title: '患者姓名',
                align: "center",
                valign: 'middle',
            }, {
                field: 'settleType',
                title: '结算状态',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (value == "0") {
                        return "未结算";
                    }
                    if (value == "1") {
                        return "出院结算";
                    }
                    if (value == "3") {
                        return "中间结算";
                    }
                    // if(value=="3"){
                    //     return "出纳";
                    // }
                    if (value == "4") {
                        return "已出纳";
                    }
                }
            }, {
                field: 'responceType',
                title: '医保身份',
                align: "center",
                valign: 'middle',
            }, {
                field: 'admissTimes',
                title: '住院次数',
                align: "center",
                valign: 'middle',
            }, {
                field: 'balance',
                title: '余额(元)',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return Math.abs(value).toFixed(2);
                    ;
                }
            }, {
                field: 'totalCharge',
                title: '总金额(元)',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return Math.abs(value).toFixed(2);
                    ;
                }
            }, {
                field: 'wardName',
                title: '病区',
                align: "center",
                valign: 'middle',
            }, {
                field: 'zkDeptName',
                title: '小科室',
                align: "center",
                valign: 'middle',
            }, {
                field: 'admissDate',
                title: '入院时间',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (value == null || value == "") {
                        return "";
                    }
                    return format(value, "yyyy-MM-dd HH:mm:ss");
                }
            }, {
                field: 'disDate',
                title: '出院时间',
                align: "center",
                valign: 'middle',
                visible: visible,   //这一列是否隐藏  false 隐藏 true 展示
                formatter: function (value, row, index) {
                    if (value == null || value == "") {
                        return "";
                    }
                    return format(value, "yyyy-MM-dd HH:mm:ss");
                }
            }, {
                title: '操作',
                align: "center",
                valign: 'middle',
                // sortable: true,
                formatter: function (value, row, index) {
                    var str = '<button type="button" class="registration-no-color-foot-button"title="查看账页信息" onclick="getZyLedgerFiles(\'' + row.inpatientNo + '\',' + row.admissTimes + ')"><i class="fa fa-paste"></i></button>';
                    // str += '<button type="button" class="registration-no-color-foot-button"title="出院结算" onclick="settlement(\'' + row.inpatientNo + '\',' + row.admissTimes + ')"><i class="fa fa-credit-card"></i></button>';
                    var payMarkGroup = getIndex("pay_mark_group");
                    if (payMarkGroup == 0) {
                        if (row.settleType == 0) {
                            str += '<button type="button" class="registration-no-color-foot-button"title="出院结算" onclick="settlement(\'' + row.inpatientNo + '\',' + row.admissTimes + ')"><i class="fa fa-credit-card"></i></button>';
                        }
                        str += '<button type="button" class="registration-no-color-foot-button"title="立即出院" onclick="leaveHospital(\'' + row.inpatientNo + '\',' + row.admissTimes + ',\'' + row.name + '\')"><i class="fa fa-sign-out"></i></button>';
                    } else if (payMarkGroup == 1) {
                        str += '<button type="button" class="registration-no-color-foot-button"title="出院召回" onclick="recall(\'' + row.inpatientNo + '\',' + row.admissTimes + ',\'' + row.name + '\')"><i class="fa fa-reply-all"></i></button>';
                        if (row.settleType == 0) {
                            str += '<button type="button" class="registration-no-color-foot-button"title="出院结算" onclick="settlement(\'' + row.inpatientNo + '\',' + row.admissTimes + ')"><i class="fa fa-credit-card"></i></button>';
                        } else if (row.settleType == 1) {
                            str += '<button type="button" class="registration-no-color-foot-button"title="出纳处理" onclick="teller(\'' + row.inpatientNo + '\',' + row.admissTimes + ')"><i class="fa fa-rmb"></i></button>';
                            str += '<button type="button" class="registration-no-color-foot-button" title="取消结算" onclick="cancelTheSettlement(\'' + row.inpatientNo + '\',' + row.admissTimes + ');"><i class="fa fa-reply"></i></button>';
                        } else if (row.settleType == 4) {
                            str += '<button type="button" class="registration-no-color-foot-button"title="申述重算" onclick="cancelCashi(\'' + row.inpatientNo + '\',' + row.admissTimes + ')"><i class="fa fa-retweet"></i></button>';
                            if (row.printFlag == 0) {
                                var key = row.inpatientNo.trim() + "_" + row.admissTimes;
                                str += '<button type="button" id="button_' + key + '" class="registration-no-color-foot-button" title="发票打印" onclick="prn1PrintHand(\'' + row.inpatientNo.trim() + '\',' + row.admissTimes + ',\'' + key + '\');" style="color: #35D082;"><i class="fa fa-print"></i></button>';
                            } else if (row.printFlag == 1) {
                                str += '<button type="button" class="registration-no-color-foot-button" title="发票重打" onclick="repPrint(\'' + row.patientId + '\',' + row.times + ',' + row.receiptNo + ');" style="color: #F4BD00;"><i class="fa fa-print"></i></button>';
                                str += '<button type="button" class="registration-no-color-foot-button" title="发票作废重打" onclick="obsoleteAndRepPrint(\'' + row.patientId + '\',' + row.times + ',' + row.receiptNo + ');" style="color: #E73E48;"><i class="fa fa-print"></i></button>';
                            }
                        }
                    }
                    return str;
                }
            }
        ],
        responseHandler: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var ress = eval(res);
            if (ress.code == -1) {
                if (ress.message != null && ress.message != '') {
                    new PNotify({
                        title: '错误提示',
                        text: ress.message,
                        type: 'error',
                        hide: true,
                        styling: 'bootstrap3'
                    });
                }
                return {
                    "total": 0,//总页数
                    "rows": {}   //数据
                };
            }
            // if(ress.pageViewVo.total==0){
            //     $("#cardNo").val(null);
            //     $("#name").val(null);
            // }
            return {
                "total": ress.total,//总页数
                "rows": ress.data   //数据
            };
        }
    });
}

function dismissFlagChange() {
    if ($("#dismissFlag").val() == 1) {
        $("#myDatepickerDiv").addClass("hide");
    } else {
        $("#myDatepickerDiv").removeClass("hide");
    }
}

/**
 * 清空提示区域
 */
function clearMode() {
    $("#inpatientNoParams").val(null);
    $("#admissTimesParams").val(null);
    $("#myDatepicker").val(null);
    $("#dismissFlag").selectpicker('val', 1);//默认选中
    $("#dismissFlag").selectpicker('refresh');

}

/**
 * 查看账页信息
 * @param inpatientNo
 * @param admissTimes
 */
function getZyLedgerFiles(inpatientNo, admissTimes) {
    $('#zyLedgerFile_table').bootstrapTable("destroy");
    $('#zyLedgerFile_table').bootstrapTable({
        url: '/thmz/getZyLedgerFileByInpatientNoAndTimes?inpatientNo=' + inpatientNo + "&admissTimes=" + admissTimes,         //请求后台的URL（*）
        method: 'get',                      //请求方式（*）
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 2,                       //每页的记录行数（*）
        pageList: [5, 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: [
            // {
            //     checkbox: true
            // },
            {
                field: 'ledgerSn',
                title: '账页',
                align: "center",
                valign: 'middle'
            },
            {
                field: 'accountDate',
                title: '结算日期',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (value == null || value == "") {
                        return "";
                    }
                    return format(value, "yyyy-MM-dd HH:mm:ss");
                }
            }, {
                field: 'totalCharge',
                title: '账页金额',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return value.toFixed(2);
                }
            }, {
                field: 'opIdCode',
                title: '操作员',
                align: "center",
                valign: 'middle'
            }
        ],
        onClickRow: function (row) {
            showZyLedgerFile(row);
        },
        responseHandler: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var ress = eval(res);
            if (ress.code == -1) {
                if (ress.message != null && ress.message != '') {
                    new PNotify({
                        title: '错误提示',
                        text: ress.message,
                        type: 'error',
                        hide: true,
                        styling: 'bootstrap3'
                    });
                }
                return {
                    "total": 0,//总页数
                    "rows": {}   //数据
                };
            }
            // if(ress.pageViewVo.total==0){
            //     $("#cardNo").val(null);
            //     $("#name").val(null);
            // }
            showZyLedgerFile(ress.data[0]);
            return {
                "total": ress.total,//总页数
                "rows": ress.data   //数据
            };
        }
    });
    $("#zyLedgerFileModal").modal();

}


/**
 * 切换账页明细内容
 * @param row
 */
function showZyLedgerFile(row) {
    $("#charge1").text(row.charge1.toFixed(2));
    $("#charge2").text(row.charge2.toFixed(2));
    $("#charge3").text(row.charge3.toFixed(2));
    $("#charge4").text(row.charge4.toFixed(2));
    $("#charge5").text(row.charge5.toFixed(2));
    $("#charge6").text(row.charge6.toFixed(2));
    $("#charge7").text(row.charge7.toFixed(2));
    $("#charge8").text(row.charge8.toFixed(2));
    $("#charge9").text(row.charge9.toFixed(2));
    $("#charge10").text(row.charge10.toFixed(2));
    $("#charge11").text(row.charge11.toFixed(2));
    $("#charge12").text(row.charge12.toFixed(2));
    $("#charge13").text(row.charge13.toFixed(2));
    $("#charge14").text(row.charge14.toFixed(2));
    $("#charge15").text(row.charge15.toFixed(2));
    $("#charge16").text(row.charge16.toFixed(2));
    $("#charge17").text(row.charge17.toFixed(2));
    $("#charge18").text(row.charge18.toFixed(2));
    $("#charge19").text(row.charge19.toFixed(2));
    $("#charge20").text(row.charge20.toFixed(2));
    $("#charge21").text(row.charge21.toFixed(2));
    $("#charge22").text(row.charge22.toFixed(2));
    $("#charge23").text(row.charge23.toFixed(2));
    $("#charge24").text(row.charge24.toFixed(2));
    $("#charge25").text(row.charge25.toFixed(2));
    $("#charge26").text(row.charge26.toFixed(2));
    $("#charge27").text(row.charge27.toFixed(2));
    $("#charge28").text(row.charge28.toFixed(2));
    $("#charge29").text(row.charge29.toFixed(2));
    $("#charge30").text(row.charge30.toFixed(2));
    if (row.settle <= 0) {
        $("#settle").text("补交");
    } else {
        $("#settleTitle").text("退款");
    }
    $("#settle").text(row.settle.toFixed(2));
    $("#balance").text(row.balance.toFixed(2));
    $("#deposit").text(row.deposit.toFixed(2));
    $("#totalCharge").text(row.totalCharge.toFixed(2));

}


/**
 * 立即出院
 * @param inpatientNo
 * @param admissTimes
 */
function leaveHospital(inpatientNo, admissTimes, name) {
    if (!confirm("确定要将病人【" + name.trim() + "】，置为出院状态吗？")) {
        return;
    }

    $.ajax({
        type: "GET",
        url: '/thmz/settlementInfo?inpatientNo=' + inpatientNo + "&admissTimes=" + admissTimes,
        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 == -2) {
                if (!confirm(res.message)) {
                    return;
                }
            } else if (res.code == -1) {
                errorMesage(res);
                return;
            }
            $.ajax({
                type: "GET",
                url: '/thmz/leaveHospital?inpatientNo=' + inpatientNo + "&admissTimes=" + admissTimes,
                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) {
                        $('#tb_table').bootstrapTable("refresh");
                        successMesage(res);
                    } else {
                        errorMesage(res);
                    }
                }
            });
        }
    });

}


/**
 * 出院召回
 * @param inpatientNo
 * @param admissTimes
 */
function recall(inpatientNo, admissTimes, name) {
    if (!confirm("确定要将病人【" + name.trim() + "】，做召回处理吗？")) {
        return;
    }
    $.ajax({
        type: "GET",
        url: '/thmz/recall?inpatientNo=' + inpatientNo + "&admissTimes=" + admissTimes,
        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) {
                $('#tb_table').bootstrapTable("refresh");
                successMesage(res);
            } else {
                errorMesage(res);
            }
        }
    });
}


/**
 * 费用冲消 申述重算
 * @param inpatientNo
 * @param admissTimes
 */
function cancelCashi(inpatientNo, admissTimes) {
    if (!confirm("确定要将住院号为【" + inpatientNo.trim() + "】，住院次数为【" + admissTimes + "】的费用进行申述重算吗？")) {
        return;
    }
    $.ajax({
        type: "GET",
        url: '/thmz/cancelCashi?inpatientNo=' + inpatientNo + "&admissTimes=" + admissTimes,
        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) {
                $('#tb_table').bootstrapTable("refresh");
                successMesage(res);
            } else {
                errorMesage(res);
            }
        }
    });
}


/**
 * 出院结算
 * @param inpatientNo
 * @param admissTimes
 */
function settlement(inpatientNo, admissTimes) {
    $("#inpatientNoParams").val(inpatientNo);
    $("#admissTimesParams").val(admissTimes);
    $("#settlementModal").modal();
}

/**
 * 出院计算
 */
function execute() {
    var dismissFlag = $("#dismissFlag").val();
    if (dismissFlag == "2" && ($("#myDatepicker").val() == null || $("#myDatepicker").val() == "")) {
        errorMesageSimaple("中间断帐时间必选");
        return;
    }
    if (dismissFlag == "1") {
        $.ajax({
            type: "GET",
            url: '/thmz/getIntervalDayForLeaveHis?inpatientNo=' + $("#inpatientNoParams").val() + "&admissTimes=" + $("#admissTimesParams").val(),
            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) {
                    if (res.data != null) {
                        if (!confirm(res.message)) {
                            return;
                        }
                    }
                    $.ajax({
                        type: "GET",
                        url: '/thmz/executeNew?inpatientNo=' + $("#inpatientNoParams").val() + "&admissTimes=" + $("#admissTimesParams").val() + "&dismissFlag=" + dismissFlag + "&zjdzDatetime=" + $("#myDatepicker").find("input").val(),
                        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) {
                                successMesage(res);
                                $("#settlementModal").modal("hide");
                                clearMode();
                                $('#tb_table').bootstrapTable("refresh");
                                return;
                            }
                            if (res.code == -1) {
                                errorMesage(res);
                                return;
                            }
                            if (res.code == -2) {
                                $("#settlementModal").modal("hide");
                                $("#ycyzModal").modal();
                                clearMode();
                                var data = res.data;
                                $('#settlement_table').bootstrapTable("destroy");
                                $('#settlement_table').bootstrapTable({
                                    data: data,         //请求后台的URL（*）
                                    //method: 'post',                      //请求方式（*）
                                    toolbar: '#toolbar',                //工具按钮用哪个容器
                                    striped: true,                      //是否显示行间隔色
                                    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                                    pagination: true,                   //是否显示分页（*）
                                    sortable: true,                     //是否启用排序
                                    sortOrder: "asc",                   //排序方式
                                    //queryParams: queryParams,           //传递参数（*）
                                    sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
                                    pageNumber: 1,                       //初始化加载第一页，默认第一页
                                    pageSize: 2,                       //每页的记录行数（*）
                                    pageList: [2, 5, 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: [
                                        // {
                                        //     checkbox: true
                                        // },
                                        {
                                            field: 'chargeStatus',
                                            title: '异常状态',
                                            align: "center",
                                            valign: 'middle',
                                            formatter: function (value, row, index) {
                                                if (value == 5) {
                                                    return '<span style="color:#1E90FF">未确认药</span>';
                                                }
                                                if (value == 6) {
                                                    return '<span style="color:#FFA500">未接收</span>';
                                                }
                                                if (value == 8) {
                                                    return '<span style="color:#FF4500">医技未确认</span>';
                                                }
                                            }
                                        }, {
                                            field: 'orderNo',
                                            title: '医嘱号',
                                            align: "center",
                                            valign: 'middle'
                                        }, {
                                            field: 'orderName',
                                            title: '医嘱名称',
                                            align: "center",
                                            valign: 'middle',
                                        }, {
                                            field: 'frequCode',
                                            title: '频率',
                                            align: "center",
                                            valign: 'middle',
                                        }, {
                                            field: 'cxFlag',
                                            title: '撤销',
                                            align: "center",
                                            valign: 'middle',
                                            formatter: function (value, row, index) {
                                                if (value == 1) {
                                                    return "是";
                                                }
                                                return "否";
                                            }
                                        }, {
                                            field: 'startTime',
                                            title: '开始时间',
                                            align: "center",
                                            valign: 'middle'
                                        }, {
                                            field: 'endTime',
                                            title: '结束时间',
                                            align: "center",
                                            valign: 'middle',
                                        }, {
                                            field: 'physician',
                                            title: '医生',
                                            align: "center",
                                            valign: 'middle',
                                        }, {
                                            field: 'enterOper',
                                            title: '录入人',
                                            align: "center",
                                            valign: 'middle',
                                        }, {
                                            field: 'wardName',
                                            title: '病区',
                                            align: "center",
                                            valign: 'middle'
                                        }
                                    ],
                                    onClickRow: function (row) {
                                        var dataDetal = row.list;
                                        setSettlementTableDetail(dataDetal);
                                    },
                                });
                                //第一次初始化医嘱列表的时候需要同步初始化子医嘱列表
                                setSettlementTableDetail(data[0].list);
                            }
                            if (res.code == -3) {
                                $("#settlementModal").modal("hide");
                                clearMode();
                            }
                        }
                    });
                    return;
                }
                if (res.code == -1) {
                    errorMesage(res);
                    return;
                }
            }
        });
    }
}


/**
 * 初始化子医嘱列表
 */
function setSettlementTableDetail(dataDetal) {
    $('#settlement_table_detail').bootstrapTable("destroy");
    $('#settlement_table_detail').bootstrapTable({
        data: dataDetal,         //请求后台的URL（*）
        //method: 'post',                      //请求方式（*）
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        //queryParams: queryParams,           //传递参数（*）
        sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 2,                       //每页的记录行数（*）
        pageList: [2, 5, 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: [
            // {
            //     checkbox: true
            // },
            {
                field: 'chargeStatus',
                title: '异常状态',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (value == 5) {
                        return '<span style="color:#1E90FF">未确认药</span>';
                    }
                    if (value == 6) {
                        return '<span style="color:#FFA500">未接收</span>';
                    }
                    if (value == 8) {
                        return '<span style="color:#FF4500">医技未确认</span>';
                    }
                }
            }, {
                field: 'chargeCode',
                title: '收费码',
                align: "center",
                valign: 'middle'
            }, {
                field: 'chargeName',
                title: '项目名称',
                align: "center",
                valign: 'middle',
            }, {
                field: 'drugSpecification',
                title: '规格',
                align: "center",
                valign: 'middle',
            }, {
                field: 'chargeAmount',
                title: '数量',
                align: "center",
                valign: 'middle'
            }, {
                field: 'chargeFee',
                title: '金额',
                align: "center",
                valign: 'middle'
            }, {
                field: 'pageNo',
                title: '药品单号',
                align: "center",
                valign: 'middle',
            }
        ]
    });
}

/**
 * 出纳处理
 * @param inpatientNo
 * @param admissTimes
 */
function teller(inpatientNo, admissTimes) {
    inpatientNo = inpatientNo.trim();
    $("#confirmFeeModal").modal();
    $("#surplusAmount").val(0.00);
    $("#inpatientNoTeller").val(inpatientNo);
    $("#admissTimesTeller").val(admissTimes);
    $.ajax({
        type: "GET",
        url: '/thmz/getTellerInfo?inpatientNo=' + inpatientNo + "&admissTimes=" + admissTimes,
        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) {
                if (res.data.settle > 0) {
                    $("#settleType").html("退款");
                    $("#settleName").text("退款金额：");
                } else if (res.data.settle < 0) {
                    $("#settleType").html("补交");
                    $("#settleName").text("补交金额：");
                }
                $("#amountMoneyConfirm").text(res.data.total_charge == null ? 0.00 : res.data.total_charge.toFixed(2));
                $("#depositConfirm").text(res.data.deposit == null ? 0.00 : res.data.deposit.toFixed(2));
                $("#ybjzjeConfirm").text(res.data.ybjzje == null ? 0.00 : res.data.ybjzje.toFixed(2));
                $("#settleConfirm").text(res.data.settle == null ? 0.00 : res.data.settle.toFixed(2));
                $("#cash").val(res.data.settle == null ? 0.00 : res.data.settle.toFixed(2));
                //TODO 需要发送评价消息待确认信息
            } else {
                errorMesage(res);
            }
        }
    });
}


/**
 * 取消出院结算
 * @param inpatientNo
 * @param admissTimes
 */
function cancelTheSettlement(inpatientNo, admissTimes) {
    inpatientNo = inpatientNo.trim();
    if (!confirm("确定要取消住院号为【" + inpatientNo + "】，住院次数为【" + admissTimes + "】的出院结算吗？")) {
        return;
    }
    $.ajax({
        type: "GET",
        url: '/thmz/cancelTheSettlement?inpatientNo=' + inpatientNo + "&admissTimes=" + admissTimes,
        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) {
                $('#tb_table').bootstrapTable("refresh");
                successMesage(res);
            } else {
                errorMesage(res);
            }
        }
    });
}


/**
 * 更新病人缴费记录病人姓名
 * @param index
 * @param field
 * @param value
 * @param row
 */
function saveData(index, field, value, row, table) {
    $.ajax({
        type: "POST",
        url: '/thmz/changePatientIdName',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        data: JSON.stringify({"patientId": row.patientId, "times": row.times, "name": value}),
        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) {
                table.bootstrapTable('updateCell', {
                    index: index,       //行索引
                    field: field,       //列名
                    value: value        //cell值
                })
            } else {
                table.bootstrapTable('updateCell', {
                    index: index,       //行索引
                    field: field,       //列名
                    value: row.name        //cell值
                })
                errorMesage(res);
            }
        }
    });
}

/**
 * 构建列表查询参数
 * @param params
 * @returns {{mzChargeDetail: {patientId: string | number | string[] | undefined | jQuery, warnDept: string | number | string[] | undefined | jQuery, doctorCode: string | number | string[] | undefined | jQuery, name: string | number | string[] | undefined | jQuery, payMark: number}, beginTime: Date, endTime: Date, pageSize: *, pageIndex: number}}
 */
function queryParams(params) {
    var rePortRangeArr = getRePortRangeArr();
    var payMarkGroup = getIndex("pay_mark_group");
    var temp = {
        pageSize: params.limit,   //页面大小
        pageIndex: params.offset / params.limit,  //页码
        mzNo: $("#cardNo").val(),
        name: $("#name").val(),
        ward: $("#deptNoParam").val(),
        zkDept: $("#smallDeptParam").val(),
        inpatientNo: $("#inpatientNo").val(),
        beginTime: rePortRangeArr[0],
        endTime: rePortRangeArr[1],
        tableName: "zy_actpatient"

    };
    if (payMarkGroup == 1) {
        temp.tableName = "zy_inactpatient";
    }
    return temp;
};

function initChargeDetailTable() {
    initChargeDetailTablePublic('/thmz/getMzChargeDetailByBillItem', $('#charge_detail_table'), queryParamsForDetail);
}

function initMzChargeDetailByBillItem(flag) {
    if (flag) {
        $("#refund_bill_item_group").removeClass("hide").addClass("in");
        if ($("#plusOrMinus").hasClass("fa-plus")) {
            $("#plusOrMinus").removeClass("fa-plus").addClass("fa-minus");
            initChargeDetailTablePublic('/thmz/getNewListForRefundFeeByBillItem', $('#refund_fee_bill_table'), queryParamsForRefundByBillItem);
        } else if ($("#plusOrMinus").hasClass("fa-minus")) {
            $("#plusOrMinus").removeClass("fa-minus").addClass("fa-plus");
            $("#refund_bill_item_group").removeClass("in").addClass("hide");
            $('#refund_fee_bill_table').bootstrapTable("destroy");
        }
    } else {
        initChargeDetailTablePublic('/thmz/getNewListForRefundFeeByBillItem', $('#refund_fee_bill_table'), queryParamsForRefundByBillItem);
    }
}

/**
 * 初始化收费明细表格
 */
function initChargeDetailTablePublic(url, obj, params) {
    $(obj).bootstrapTable("destroy");
    $(obj).bootstrapTable({
        url: url,         //请求后台的URL（*）
        method: 'post',                      //请求方式（*）
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: false,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        // sortName: 'orderNo',                //排序字段
        queryParams: params,           //传递参数（*）
        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: [
            // {
            //     checkbox: true
            // },
            {
                field: 'orderNo',
                title: '处方号',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return Math.abs(value);
                }
            }, {
                field: 'chargeItemCode',
                title: '编码',
                align: "center",
                valign: 'middle',
            }, {
                field: 'tcName',
                title: '项目',
                align: "center",
                valign: 'middle',
            },
            // {
            //     field: 'times',
            //     title: '规格',
            //     align: "center",
            //     valign: 'middle',
            // },
            {
                field: 'quantity',
                title: '数量',
                align: "center",
                valign: 'middle'
            }, {
                field: 'drugWin',
                title: '副数',
                align: "center",
                valign: 'middle',
            }, {
                field: 'unitPrice',
                title: '单价(元)',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return value.toFixed(2);
                }
            }, {
                field: 'amount',
                title: '总金额(元)',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return value.toFixed(2);
                }
            }
        ],
        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.data   //数据
            };
        },
    });
}

/**
 * 构建列表查询参数
 * @param params
 * @returns {{patientId: string | number | string[] | undefined | jQuery, times: string | number | string[] | undefined | jQuery, billItemCode: number}}
 */
function queryParamsForDetail(params) {
    var billItemGroup = getIndex("bill_item_group");
    var payMarkGroup = getIndex("pay_mark_group");
    var temp = {
        patientId: $("#patientIdChargeItem").val(),
        times: $("#timesChargeItem").val(),
        receiptNo: $("#receiptNoChargeItem").val(),
        billItemCode: billItemGroup,
        payMark: 5
    };
    if (payMarkGroup == 1) {
        temp.payMark = 0;
    } else if (payMarkGroup == 2) {
        temp.payMark = 1;
    }
    return temp;
};


/**
 * 构建列表查询参数
 * @param params
 * @returns {{patientId: string | number | string[] | undefined | jQuery, times: string | number | string[] | undefined | jQuery, billItemCode: number}}
 */
function queryParamsForRefundByBillItem(params) {
    var billItemGroup = getIndex("refund_bill_item_group");
    return {
        patientId: $("#patientIdRefund").val(),
        times: $("#timesRefund").val(),
        receiptNo: $("#receiptNoRefund").val(),
        chargeItemCodes: chargeItemCodes,
        billItemCode: billItemGroup
    };
};

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


/**
 * 卡号有变化后查询病人信息
 */
function queryUserInfoByCardNo() {
    var cardNo = $("#cardNo").val();
    var index = cardNo.indexOf("-");
    if (index > 0 && index == cardNo.length - 2) {
        $("#patientId").val(cardNo);
        initFeeTable();
    } else if (cardNo == '120' || 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) {
                        $("#patientId").val(res.data.patientId);
                        initFeeTable();
                    }
                } else {
                    new PNotify({
                        title: '错误提示',
                        text: res.message,
                        type: 'error',
                        hide: true,
                        styling: 'bootstrap3'
                    });
                }
            }
        });
    } else if (cardNo == null || cardNo == "") {
        cleanParams();
    }
}

/**
 * 获取按钮组选择的下标
 * @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 confirmFeeModal(times, totalCharge, receiptNo) {
    $('#payType').selectpicker('val', 1);
    $('#payType').selectpicker('refresh');
    var data = parseFloat($("#dataIdHaveTally").val());
    if (totalCharge != null && totalCharge > 0) {
        data = totalCharge;
        $("#timesHaveTally").val(times);
        $("#receiptNoHaveTally").val(receiptNo);
    }
    var prevAll = $("#changeAmountParent").prevAll();
    while (prevAll.length > 2) {
        $("#changeAmountParent").prev().remove();
        prevAll = $("#changeAmountParent").prevAll();
    }
    // $("#realMoney").val($("#amountMoneyConfirm").text());
    // $("#cash").val($("#amountMoneyConfirm").text());
    $("#tallyDetailModal").modal('hide');
    $("#haveTallyModal").modal('hide');
    $("#confirmFeeModal").modal();
    $("#amountMoneyConfirm").text(data);
    var fundPay = $("#fundPay").val();
    if (fundPay > 0) {
        addPayType("payType_0");
        $('#payType_0').selectpicker('val', 2);
        $('#payType_0').selectpicker('refresh');
        $("#payType_0").parent().parent().next().children(':first').val(fundPay);
        $("#payType_0").parent().parent().next().next().children(':first').remove();
        $("#payType_0").attr("disabled", true);
        $("#payType_0").parent().parent().next().children(':first').attr("readonly", "readonly");
    }
    var realMoney = Minus(data, fundPay);
    $("#realMoney").val(data);
    $("#cash").val(realMoney);
    // $("#cash").val(null);
    setTimeout(function () {
        //默认光标在卡号输入框
        $("#cash").focus();
    }, 800);
    $("#payType").selectpicker('val', 1);
    $("#payType").selectpicker('refresh');
    $("#changeAmount").val(0.0);
    $("#surplusAmount").val(0.0);
    sendPeiceMessage(realMoney, 0, 0, '您本次应付金额为' + realMoney + '元', $("#patientIdHaveTally").val(), $("#nameHaveTally").val());
}


/**
 * 初始门诊收银方式下拉选
 */
function initChequeType(payType) {
    $.ajax({
        type: "GET",
        url: '/thmz/getAllZdChequeTypeForZy',
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        async: false,
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var html = '';
            $.each(res.data, function (commentIndex, comment) {
                html += '<option value="' + comment.code + '">' + comment.name + '</option>';
            });
            $('#' + payType).empty();
            $('#' + payType).html(html);
            $('#' + payType).selectpicker('refresh');
            $('#' + payType).selectpicker('val', 'A');
            $('#' + payType).selectpicker('refresh');
        }
    });
}


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


/**
 * 校验收款金额
 * @param flag 是否是提交时候的校验，是的话，如果缴费金额不够，需要返回 false
 */
function checkFee(flag) {
    var realMoney = $("#settleConfirm").text();
    var arr = $("#payForm").find("div.pay-item");
    if (arr.length > 0) {
        //总金额
        var totalAmount = 0;
        for (var i = 0; i < arr.length; i++) {
            var temp = parseFloat($(arr[i]).find("input").val());
            if (isNaN(temp)) {
                temp = 0;
            }
            totalAmount = Add(totalAmount, temp);
            for (var j = 0; j < arr.length; j++) {
                if ($(arr[i]).find("select").val() == $(arr[j]).find("select").val() && i != j) {
                    new PNotify({
                        title: '错误提示',
                        text: "已经存在相同的支付方式，请不要重复添加！",
                        type: 'error',
                        hide: true,
                        styling: 'bootstrap3'
                    });
                    return;
                }
            }
        }

        $("#surplusAmount").val(0.0);
        if (totalAmount < realMoney) {
            if (flag) {
                new PNotify({
                    title: '错误提示',
                    text: "支付金额不能少于实际应支付金额,请调整支付金额或者增加支付方式！",
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
                return false;
            }
            if (totalAmount == 0) {
                $("#addPayType").parent().removeClass("in").addClass("hide");
            } else {
                $("#addPayType").parent().removeClass("hide").addClass("in");
            }
            var surplusAmount = Minus(realMoney, totalAmount);
            $("#surplusAmount").val(surplusAmount);
            return;
        }
        if (totalAmount >= realMoney) {
            $("#addPayType").parent().removeClass("in").addClass("hide");
        }
    }
    return true;
}


var $tally_detail_table;

/**
 * 初始化本院记账明细表格
 */
function initTallyDetailTable() {
    $("#haveTallyModal").modal('hide');
    var patientId = $("#patientIdHaveTally").val();
    // var name = $("#nameHaveTally").val();
    if (patientId == null || patientId == '') {
        return;
    }
    $("#tallyDetailModal").modal();
    $('#tally_detail_table').bootstrapTable("destroy");
    $tally_detail_table = $('#tally_detail_table').bootstrapTable({
        url: '/thmz/getTallyReceiptSerial?patientId=' + patientId,         //请求后台的URL（*）
        method: 'get',                      //请求方式（*）
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: false,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        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: [
            // {
            //     checkbox: true,
            // },
            {
                field: 'patientId',
                title: '病人编号',
                align: "center",
                valign: 'middle'
            }, {
                field: 'name',
                title: '病人姓名',
                align: "center",
                valign: 'middle',
                // formatter: function (value, row, index) {
                //     return name;
                // }
            }, {
                field: 'times',
                title: '就诊次数',
                align: "center",
                valign: 'middle',
            },
            {
                field: 'totalCharge',
                title: '总费用(元)',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return value.toFixed(2);
                }
            },
            {
                field: 'chargeDate',
                title: '记账时间',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return format(value, "yyyy-MM-dd HH:mm:ss");
                }
            }
        ],
        /**
         * @param {点击列的 field 名称} field
         * @param {点击列的 value 值} value
         * @param {点击列的整行数据} row
         * @param {td 元素} $element
         */
        onClickCell: function (field, value, row, $element) {
            var cardNo = $("#cardNo").val();
            if (cardNo == '120' && field == 'name') {
                $element.attr('contenteditable', true);
                $element.html(null);
                $element.focus();
                $element.blur(function () {
                    var index = $element.parent().data('index');
                    var tdValue = $element.html();
                    saveData(index, field, tdValue, row, $tally_detail_table);
                })
            }
        },
        onDblClickRow: function (row) {
            confirmFeeModal(row.times, row.totalCharge, row.receiptNo);
        },
        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": {}   //数据
                };
            }
            if (ress.data == null || ress.data.length == 0) {
                $("#tallyDetailModal").modal("hide");
            }
            return {
                "rows": ress.data   //数据
            };
        },
    });
}


/**
 * 出纳处理保存
 */
function saveTeller() {
    $("#saveTeller").attr("disabled", true);
    if (!checkFee(true)) {
        $("#saveTeller").attr("disabled", false);
        return;
    }
    var inpatientNo = $("#inpatientNoTeller").val();
    var admissTimes = $("#admissTimesTeller").val();
    var settleTypeName = $("#settleType").html();
    var settleType = "3";
    if ("退款" == settleTypeName) {
        settleType = "4";
    } else if ("补交") {
        settleType = "3";
    }
    var jsonData = JSON.parse('{"zyDepositFiles":[]}');
    var arr = $("#payForm").find("div.pay-item");
    if (arr.length > 0) {
        for (var i = 0; i < arr.length; i++) {
            var temp = parseFloat($(arr[i]).find("input").val());
            var tempJson = JSON.parse('{"inpatientNo":"","admissTimes":"","depoType":"","depoAmount":"","status":""}');
            tempJson.inpatientNo = inpatientNo;
            tempJson.admissTimes = admissTimes;
            tempJson.status = settleType;
            tempJson.depoType = $(arr[i]).find("select").val();
            tempJson.depoAmount = temp;
            jsonData.zyDepositFiles[i] = tempJson;
        }
    }
    $.ajax({
        type: "POST",
        url: '/thmz/teller',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        data: JSON.stringify(jsonData.zyDepositFiles),
        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) {
                //TODO 打印发票
                //prn1Print(patientId, times, true, res.receiptNo);
                new PNotify({
                    title: '操作提示',
                    text: res.message,
                    type: 'success',
                    hide: true,
                    styling: 'bootstrap3'
                });
                $("#confirmFeeModal").modal("hide");
                $("#inpatientNoTeller").val(null);
                $("#admissTimesTeller").val(null);
                $('#tb_table').bootstrapTable("refresh");
                //默认光标在卡号输入框
                $("#cardNo").focus();
                //TODO 发送评价消息
                //postCMD("appraise", localStorage.getItem("userID"), '000000', '收费项目', 0, 0, 0, '', '祝您早日康复', 0, 0, 0);
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
            $("#saveTeller").attr("disabled", false);
        }
    });
}


/**
 * 直接打印发票
 * @param inpatientNo
 * @param admissTimes
 * @param key
 */
function prn1PrintHand(inpatientNo, admissTimes, key) {
    $("#button_" + key).css("display", "none");
    getAllReceiptForThisTime(inpatientNo, admissTimes);
}


/**
 * 获取当前住院的所有发票
 * @param inpatientNo
 * @param admissTimes
 */
function getAllReceiptForThisTime(inpatientNo, admissTimes) {
    $.ajax({
        type: "GET",
        url: '/thmz/getAllReceiptForThisTime?inpatientNo=' + inpatientNo + "&admissTimes=" + admissTimes,
        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.length == 1) {
                    prn1Print(inpatientNo, admissTimes, res.data[0].ledgerSn);
                } else {
                    $("#tip_title").text("发票打印");
                    $("#tip_message").text("请选择需要打印发票的账页");
                    $("#repPrintModal").modal();
                    $("#repPrintTable").html(null);
                    for (var i = 0; i < res.data.length; i++) {
                        $("<tr><td>" + res.data[i].ledgerSn + "</td></tr>").appendTo("#repPrintTable").bind('click', function () {
                            $("#repPrintModal").modal("hide");
                            prn1Print(inpatientNo, admissTimes, $(this).text());
                        });
                    }
                }

            }
        }
    });


}


/**
 * 直接打印发票
 * @param inpatientNo
 * @param admissTimes
 */
function prn1Print(inpatientNo, admissTimes, ledgerSn) {
    var url = '/thmz/printReceiptForThisLedgerSn?inpatientNo=' + inpatientNo + "&admissTimes=" + admissTimes + "&ledgerSn=" + ledgerSn;
    printCommon(url, inpatientNo, admissTimes, ledgerSn);
}


/**
 * 重打发票
 * @param patientId
 * @param times
 */
function repPrint(patientId, times, receiptNo) {
    $.ajax({
        type: "GET",
        url: '/thmz/getReceiptForThisTime?patientId=' + patientId + "&times=" + times + "&receiptNo=" + receiptNo,
        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.length == 1) {
                    var message = "确定要重新打印发票号码为【" + res.data[0].receiptBill + "】的发票吗？请确认发票打印机即将要打印的发票编号";
                    var url = '/thmz/repPrintForThisTime?patientId=' + patientId + "&times=" + times + "&obsolete=0" + "&receiptBill=" + res.data[0].receiptBill;
                    confirmMessage(patientId, times, message, url);
                } else {
                    $("#tip_message").text("请选择需要重新打印的发票号");
                    $("#repPrintModal").modal();
                    $("#repPrintTable").html(null);
                    for (var i = 0; i < res.data.length; i++) {
                        $("<tr><td>" + res.data[i].receiptBill + "</td></tr>").appendTo("#repPrintTable").bind('click', function () {
                            $("#repPrintModal").modal("hide");
                            var message = "确定要重新打印发票号码为【" + $(this).text() + "】的发票吗？请确认发票打印机即将要打印的发票编号";
                            var url = '/thmz/repPrintForThisTime?patientId=' + patientId + "&times=" + times + "&obsolete=0" + "&receiptBill=" + $(this).text();
                            confirmMessage(patientId, times, message, url);
                        });
                    }
                }

            }
        }
    });
}

/**
 * 发票重打提示
 * @param patientId
 * @param times
 * @param name
 */
function confirmMessage(patientId, times, message, url) {
    if (!confirm(message)) {
        return;
    }
    //var url='/thmz/repPrintForThisTime?patientId=' + patientId + "&times=" + times + "&obsolete=0" + "&receiptBill="+receiptBill;
    printCommon(url, patientId, times, true);
}


/**
 * 作废重打发票
 * @param patientId
 * @param times
 */
function obsoleteAndRepPrint(patientId, times, receiptNo) {
    $.ajax({
        type: "GET",
        url: '/thmz/getReceiptForThisTime?patientId=' + patientId + "&times=" + times + "&receiptNo=" + receiptNo,
        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.length == 1) {
                    var message = "确定要作废发票号码为【" + res.data[0].receiptBill + "】的发票吗？请确认需要作废发票编号";
                    var url = '/thmz/repPrintForThisTime?patientId=' + patientId + "&times=" + times + "&obsolete=1" + "&receiptBill=" + res.data[0].receiptBill;
                    confirmMessage(patientId, times, message, url);
                } else {
                    $("#tip_message").text("请选择需要作废的发票号");
                    $("#repPrintModal").modal();
                    $("#repPrintTable").html(null);
                    for (var i = 0; i < res.data.length; i++) {
                        $("<tr><td>" + res.data[i].receiptBill + "</td></tr>").appendTo("#repPrintTable").bind('click', function () {
                            $("#repPrintModal").modal("hide");
                            var message = "确定要作废发票号码为【" + $(this).text() + "】的发票吗？请确认需要作废发票编号";
                            var url = '/thmz/repPrintForThisTime?patientId=' + patientId + "&times=" + times + "&obsolete=1" + "&receiptBill=" + $(this).text();
                            confirmMessage(patientId, times, message, url);
                        });
                    }
                }

            }
        }
    });
}


/**
 * 打印发票通用方法
 * @param patientId
 * @param times
 */
function printCommon(url, inpatientNo, admissTimes, ledgerSn) {
    setPrint();
    var height = "102mm";
    // if (countReceiot % 2 == 0) {
    //     height = "93.2mm";
    // }
    $.ajax({
        type: "GET",
        url: url,
        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.zyReceipt == null || res.zyReceipt.length == 0) {
                    return;
                }
                LODOP = getLodop();
                var zyReceipt = res.zyReceipt;
                var zyActpatient = res.zyActpatient;
                var jeMap = res.jeMap;
                LODOP.PRINT_INITA(6, 0, "191mm", height, "泰和住院发票打印");
                //设置默认打印机
                LODOP.SET_PRINTER_INDEX(printIndex);
                LODOP.SET_SHOW_MODE("BKIMG_WIDTH", "191mm");
                LODOP.SET_SHOW_MODE("BKIMG_HEIGHT", height);
                LODOP.SET_PRINT_PAGESIZE(1, "191mm", height, "CreateCustomPage");
                LODOP.SET_PRINT_MODE("CREATE_CUSTOM_PAGE_NAME", "住院发票");//对新建的纸张重命名
                LODOP.SET_PRINT_STYLE("FontSize", 9); //字体大小
                //LODOP.ADD_PRINT_TEXT("上边距 6mm", "左边距 0mm", "长度 45mm", "高度 3mm", "内容 湖南泰和医院管理有限公司");
                LODOP.ADD_PRINT_TEXT("8mm", "12mm", "40mm", "3mm", zyActpatient.responceTypeName);
                LODOP.ADD_PRINT_TEXT("12mm", "12mm", "30mm", "3mm", zyReceipt.receiptNo);
                LODOP.ADD_PRINT_TEXT("16mm", "12mm", "145mm", "3mm", "总费用：" + jeMap.total_charge.toFixed(2) + "元，医保支付：" + jeMap.ybjzje.toFixed(2) + "元，个人自付：" + jeMap.zfje.toFixed(2) + "元");
                LODOP.ADD_PRINT_TEXT("21.5mm", "22mm", "15mm", "3mm", zyActpatient.name);
                LODOP.ADD_PRINT_TEXT("21.5mm", "42mm", "12mm", "3mm", zyActpatient.sex);
                LODOP.ADD_PRINT_TEXT("21.5mm", "119mm", "25mm", "3mm", zyActpatient.wardName);
                LODOP.ADD_PRINT_TEXT("21.5mm", "149mm", "30mm", "3mm", zyActpatient.inpatientNo);
                LODOP.ADD_PRINT_TEXT("25.5mm", "16mm", "12mm", "3mm", format(zyActpatient.admissDate, "yyyy"));
                LODOP.ADD_PRINT_TEXT("25.5mm", "30mm", "7mm", "3mm", format(zyActpatient.admissDate, "MM"));
                LODOP.ADD_PRINT_TEXT("25.5mm", "40mm", "8mm", "3mm", format(zyActpatient.admissDate, "dd"));
                LODOP.ADD_PRINT_TEXT("25.5mm", "64mm", "12mm", "3mm", format(zyActpatient.disDate, "yyyy"));
                LODOP.ADD_PRINT_TEXT("25.5mm", "78mm", "7mm", "3mm", format(zyActpatient.disDate, "MM"));
                LODOP.ADD_PRINT_TEXT("25.5mm", "88mm", "8mm", "3mm", format(zyActpatient.disDate, "dd"));
                LODOP.ADD_PRINT_TEXT("25.5mm", "116mm", "8mm", "3mm", res.days);
                LODOP.ADD_PRINT_TEXT("25.5mm", "142mm", "12mm", "3mm", format(zyReceipt.printDate, "yyyy"));
                LODOP.ADD_PRINT_TEXT("25.5mm", "157mm", "7mm", "3mm", format(zyReceipt.printDate, "MM"));
                LODOP.ADD_PRINT_TEXT("25.5mm", "167mm", "8mm", "3mm", format(zyReceipt.printDate, "dd"));

                LODOP.ADD_PRINT_TEXT("35mm", "31mm", "17mm", "3mm", (zyReceipt.charge1 == null || zyReceipt.charge1 == "0.00" || zyReceipt.charge1 == 0) ? "" : zyReceipt.charge1.toFixed(2));
                LODOP.ADD_PRINT_TEXT("40.5mm", "31mm", "17mm", "3mm", (zyReceipt.charge2 == null || zyReceipt.charge2 == "0.00" || zyReceipt.charge2 == 0) ? "" : zyReceipt.charge2.toFixed(2));
                LODOP.ADD_PRINT_TEXT("46mm", "31mm", "17mm", "3mm", (zyReceipt.charge3 == null || zyReceipt.charge3 == "0.00" || zyReceipt.charge3 == 0) ? "" : zyReceipt.charge3.toFixed(2));
                LODOP.ADD_PRINT_TEXT("51.5mm", "31mm", "17mm", "3mm", (zyReceipt.charge4 == null || zyReceipt.charge4 == "0.00" || zyReceipt.charge4 == 0) ? "" : zyReceipt.charge4.toFixed(2));
                LODOP.ADD_PRINT_TEXT("57mm", "31mm", "17mm", "3mm", "");
                LODOP.ADD_PRINT_TEXT("62.5mm", "31mm", "17mm", "3mm", (zyReceipt.charge6 == null || zyReceipt.charge6 == "0.00" || zyReceipt.charge6 == 0) ? "" : zyReceipt.charge6.toFixed(2));
                LODOP.ADD_PRINT_TEXT("68mm", "31mm", "17mm", "3mm", (zyReceipt.charge7 == null || zyReceipt.charge7 == "0.00" || zyReceipt.charge7 == 0) ? "" : zyReceipt.charge7.toFixed(2));
                LODOP.ADD_PRINT_TEXT("74.5mm", "31mm", "17mm", "3mm", (zyReceipt.charge8 == null || zyReceipt.charge8 == "0.00" || zyReceipt.charge8 == 0) ? "" : zyReceipt.charge8.toFixed(2));

                LODOP.ADD_PRINT_TEXT("35mm", "62mm", "17mm", "3mm", (zyReceipt.charge9 == null || zyReceipt.charge9 == "0.00" || zyReceipt.charge9 == 0) ? "" : zyReceipt.charge9.toFixed(2));
                LODOP.ADD_PRINT_TEXT("40.5mm", "62mm", "17mm", "3mm", "");
                LODOP.ADD_PRINT_TEXT("46mm", "62mm", "17mm", "3mm", (zyReceipt.charge11 == null || zyReceipt.charge11 == "0.00" || zyReceipt.charge11 == 0) ? "" : zyReceipt.charge11.toFixed(2));
                LODOP.ADD_PRINT_TEXT("51.5mm", "62mm", "17mm", "3mm", (zyReceipt.charge12 == null || zyReceipt.charge12 == "0.00" || zyReceipt.charge12 == 0) ? "" : zyReceipt.charge12.toFixed(2));
                LODOP.ADD_PRINT_TEXT("57mm", "62mm", "17mm", "3mm", (zyReceipt.charge13 == null || zyReceipt.charge13 == "0.00" || zyReceipt.charge13 == 0) ? "" : zyReceipt.charge13.toFixed(2));
                LODOP.ADD_PRINT_TEXT("62.5mm", "62mm", "17mm", "3mm", (zyReceipt.charge14 == null || zyReceipt.charge14 == "0.00" || zyReceipt.charge14 == 0) ? "" : zyReceipt.charge14.toFixed(2));
                LODOP.ADD_PRINT_TEXT("68mm", "62mm", "17mm", "3mm", (zyReceipt.charge15 == null || zyReceipt.charge15 == "0.00" || zyReceipt.charge15 == 0) ? "" : zyReceipt.charge15.toFixed(2));
                LODOP.ADD_PRINT_TEXT("74.5mm", "62mm", "17mm", "3mm", (zyReceipt.charge16 == null || zyReceipt.charge16 == "0.00" || zyReceipt.charge16 == 0) ? "" : zyReceipt.charge16.toFixed(2));

                LODOP.ADD_PRINT_TEXT("35mm", "95mm", "17mm", "3mm", (zyReceipt.charge17 == null || zyReceipt.charge17 == "0.00" || zyReceipt.charge17 == 0) ? "" : zyReceipt.charge17.toFixed(2));
                LODOP.ADD_PRINT_TEXT("40.5mm", "95mm", "17mm", "3mm", (zyReceipt.charge18 == null || zyReceipt.charge18 == "0.00" || zyReceipt.charge18 == 0) ? "" : zyReceipt.charge18.toFixed(2));
                LODOP.ADD_PRINT_TEXT("46mm", "95mm", "17mm", "3mm", (zyReceipt.charge19 == null || zyReceipt.charge19 == "0.00" || zyReceipt.charge19 == 0) ? "" : zyReceipt.charge19.toFixed(2));
                LODOP.ADD_PRINT_TEXT("51.5mm", "95mm", "17mm", "3mm", (zyReceipt.charge20 == null || zyReceipt.charge20 == "0.00" || zyReceipt.charge20 == 0) ? "" : zyReceipt.charge20.toFixed(2));
                LODOP.ADD_PRINT_TEXT("57mm", "95mm", "17mm", "3mm", (zyReceipt.charge21 == null || zyReceipt.charge21 == "0.00" || zyReceipt.charge21 == 0) ? "" : zyReceipt.charge21.toFixed(2));
                LODOP.ADD_PRINT_TEXT("62.5mm", "95mm", "17mm", "3mm", (zyReceipt.charge22 == null || zyReceipt.charge22 == "0.00" || zyReceipt.charge22 == 0) ? "" : zyReceipt.charge22.toFixed(2));
                LODOP.ADD_PRINT_TEXT("68mm", "95mm", "17mm", "3mm", (zyReceipt.charge23 == null || zyReceipt.charge23 == "0.00" || zyReceipt.charge23 == 0) ? "" : zyReceipt.charge23.toFixed(2));
                LODOP.ADD_PRINT_TEXT("74.5mm", "95mm", "17mm", "3mm", (zyReceipt.charge24 == null || zyReceipt.charge24 == "0.00" || zyReceipt.charge24 == 0) ? "" : zyReceipt.charge24.toFixed(2));

                LODOP.ADD_PRINT_TEXT("35mm", "128mm", "17mm", "3mm", (zyReceipt.charge25 == null || zyReceipt.charge25 == "0.00" || zyReceipt.charge25 == 0) ? "" : zyReceipt.charge25.toFixed(2));
                var itemHeight=40.5;
                if (zyReceipt.charge5 != null && zyReceipt.charge5 != "0.00" && zyReceipt.charge5 != 0) {
                    LODOP.ADD_PRINT_TEXT(itemHeight+"mm", "110mm", "17mm", "3mm", "手术器械");
                    LODOP.ADD_PRINT_TEXT(itemHeight+"mm", "128mm", "17mm", "3mm", (zyReceipt.charge5 == null || zyReceipt.charge5 == "0.00" || zyReceipt.charge5 == 0) ? "" : zyReceipt.charge5.toFixed(2));
                    itemHeight+=5.5;
                }
                if (zyReceipt.charge10 != null && zyReceipt.charge10 != "0.00" && zyReceipt.charge10 != 0) {
                    LODOP.ADD_PRINT_TEXT(itemHeight+"mm", "110mm", "17mm", "3mm", "麻醉费");
                    LODOP.ADD_PRINT_TEXT(itemHeight+"mm", "128mm", "17mm", "3mm", (zyReceipt.charge10 == null || zyReceipt.charge10 == "0.00" || zyReceipt.charge10 == 0) ? "" : zyReceipt.charge10.toFixed(2));
                    itemHeight+=5.5;
                }
                if (zyReceipt.charge26 != null && zyReceipt.charge26 != "0.00" && zyReceipt.charge26 != 0) {
                    LODOP.ADD_PRINT_TEXT(itemHeight+"mm", "110mm", "17mm", "3mm", "其他");
                    LODOP.ADD_PRINT_TEXT(itemHeight+"mm", "128mm", "17mm", "3mm", (zyReceipt.charge26 == null || zyReceipt.charge26 == "0.00" || zyReceipt.charge26 == 0) ? "" : zyReceipt.charge26.toFixed(2));
                    itemHeight+=5.5;
                }
                if (zyReceipt.charge27 != null && zyReceipt.charge27 != "0.00" && zyReceipt.charge27 != 0) {
                    LODOP.ADD_PRINT_TEXT(itemHeight+"mm", "110mm", "17mm", "3mm", "材料费");
                    LODOP.ADD_PRINT_TEXT(itemHeight+"mm", "128mm", "17mm", "3mm", (zyReceipt.charge27 == null || zyReceipt.charge27 == "0.00" || zyReceipt.charge27 == 0) ? "" : zyReceipt.charge27.toFixed(2));
                    itemHeight+=5.5;
                }
                if (zyReceipt.charge28 != null && zyReceipt.charge28 != "0.00" && zyReceipt.charge28 != 0) {
                    LODOP.ADD_PRINT_TEXT(itemHeight+"mm", "110mm", "17mm", "3mm", "中成药费");
                    LODOP.ADD_PRINT_TEXT(itemHeight+"mm", "128mm", "17mm", "3mm", (zyReceipt.charge28 == null || zyReceipt.charge28 == "0.00" || zyReceipt.charge28 == 0) ? "" : zyReceipt.charge28.toFixed(2));
                    //itemHeight+=5.5;
                }

                LODOP.ADD_PRINT_TEXT("80mm", "32mm", "95mm", "3mm", "个人支付合计：" + ((jeMap.zfje == null || jeMap.zfje == "0.00" || jeMap.zfje == 0) ? "" : jeMap.zfje.toFixed(2)));
                LODOP.ADD_PRINT_TEXT("84mm", "32mm", "95mm", "3mm", res.grhjzfje);
                LODOP.ADD_PRINT_TEXT("89mm", "32mm", "40mm", "3mm", res.printer);

                LODOP.ADD_PRINT_TEXT("40.5mm", "158mm", "17mm", "3mm", ((jeMap.deposit == null || jeMap.deposit == "0.00" || jeMap.deposit == 0) ? "" : jeMap.deposit.toFixed(2)));
                LODOP.ADD_PRINT_TEXT("62.5mm", "158mm", "17mm", "3mm", ((jeMap.settle == null || jeMap.settle == "0.00" || jeMap.settle == 0) ? "" : jeMap.settle.toFixed(2)));
                LODOP.PRINT();
                //LODOP.PREVIEW();
                $('#tb_table').bootstrapTable("refresh");
            } else if (res.code == -1) {
                errorMesage(res);
            }
        }
    });
}


//
// /**
//  * 加载打印机列表
//  * @constructor
//  */
// function CreatePrinterList() {
//     LODOP = getLodop();
//     LODOP.PRINT_INITA(6, 0, "92mm", "120mm", "泰和门诊发票打印");
//     //获取打印机设备数，用于进行遍历
//     var count = LODOP.GET_PRINTER_COUNT();
//     var html = "";
//     for (var i = 0; i < count; i++) {
//         //根据设备序号获取设备名
//         var msg = LODOP.GET_PRINTER_NAME(i);
//         html += "<option value='" + i + "'>" + msg + "</option>";
//     }
//     $('#printSelect').html(html);
//     $('#printSelect').selectpicker('refresh');
//     $.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) {
//                 $('#printSelect').selectpicker('val', res.data.printIndex);
//                 $('#printSelect').selectpicker('refresh');
//                 printIndex=res.data.printIndex;
//             }
//         }
//     });
// }


//
//
// /**
//  * 保存窗口号
//  */
// function saveWindows() {
//     $.ajax({
//         type: "POST",
//         url: '/thmz/saveWindows',
//         contentType: "application/json;charset=UTF-8",
//         dataType: "json",
//         data: JSON.stringify({"windowsNo": $("#windowsNum").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;
//             }
//             $('#editWindowsModal').modal('hide');
//             if (res.code == 0) {
//                 new PNotify({
//                     title: '操作提示',
//                     text: res.message,
//                     type: 'success',
//                     hide: true,
//                     styling: 'bootstrap3'
//                 });
//             } else {
//                 new PNotify({
//                     title: '错误提示',
//                     text: res.message,
//                     type: 'error',
//                     hide: true,
//                     styling: 'bootstrap3'
//                 });
//             }
//         }
//     });
// }
//
//
//
// /**
//  * 保存打印机
//  */
// function savePrint() {
//     $.ajax({
//         type: "POST",
//         url: '/thmz/savePrintIndex',
//         contentType: "application/json;charset=UTF-8",
//         dataType: "json",
//         data: JSON.stringify({"printIndex": $("#printSelect").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;
//             }
//             LODOP = getLodop();
//             LODOP.PRINT_INITA(6, 0, "92mm", "120mm", "泰和门诊发票打印");
//             LODOP.SET_PRINTER_INDEX($("#printSelect").val());
//             printIndex=$("#printSelect").val();
//             $('#editPrintModal').modal('hide');
//             if (res.code == 0) {
//                 new PNotify({
//                     title: '操作提示',
//                     text: res.message,
//                     type: 'success',
//                     hide: true,
//                     styling: 'bootstrap3'
//                 });
//             } else {
//                 new PNotify({
//                     title: '错误提示',
//                     text: res.message,
//                     type: 'error',
//                     hide: true,
//                     styling: 'bootstrap3'
//                 });
//             }
//         }
//     });
// }


/**
 * 查询默认打印机
 */
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.zyPrintIndex;
            } else {
                printIndex = -1;
            }
        }
    });
}


/**
 * 退费操作
 */
function refundFee(patientId, times, receiptNo, printFlag) {
    if (printFlag == 0) {
        new PNotify({
            title: '错误提示',
            text: '当前病人缴费记录发票还未打印，无法进行退费，请先打印该发票！',
            type: 'error',
            hide: true,
            styling: 'bootstrap3'
        });
        return;
    }
    $("#refundFeePrepare").text(0.00);
    $("#refundFeeDetailModal").modal();
    $("#refund_bill_item_group").removeClass("in").addClass("hide");
    $('#refund_fee_bill_table').bootstrapTable("destroy");
    initRefundFeeDetailTable(patientId, times, receiptNo);
}

/**
 * 初始化退费明细表格
 * @param patientId
 * @param times
 * @param receiptNo
 */
function initRefundFeeDetailTable(patientId, times, receiptNo) {
    $("#patientIdRefund").val(patientId);
    $("#timesRefund").val(times);
    $("#receiptNoRefund").val(receiptNo);
    $('#refund_fee_detail_table').bootstrapTable("destroy");
    $('#refund_fee_detail_table').bootstrapTable({
        url: '/thmz/getRefundFeeDetail',         //请求后台的URL（*）
        method: 'post',                      //请求方式（*）
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: false,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        // sortName: 'orderNo',                //排序字段
        queryParams: queryParamsForRefundFee(patientId, times, receiptNo),           //传递参数（*）
        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: [
            {
                checkbox: true,
                formatter: function (value, row, index) {
                    if (row.confirmFlag == 1) {
                        return {
                            disabled: true, //设置是否可用
                            checked: false//设置选中
                        }
                    }
                    if (row.confirmFlag == 3) {
                        getRefundFee();
                        return {
                            disabled: true, //设置是否可用
                            checked: true//设置选中
                        }
                    }
                }
            },
            {
                field: 'orderNo',
                title: '处方号',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return Math.abs(value);
                }
            }, {
                field: '',
                title: '项目号',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return index + 1;
                }
            }, {
                field: 'billItemCode',
                title: '分类名称',
                align: "center",
                valign: 'middle',
            }, {
                field: 'chargeItemCode',
                title: '收费编码',
                align: "center",
                valign: 'middle',
            }, {
                field: 'tcName',
                title: '项目',
                align: "center",
                valign: 'middle',
            },
            {
                field: 'quantity',
                title: '数量',
                align: "center",
                valign: 'middle'
                ,
                formatter: function (value, row, index) {
                    return value * row.drugWin;
                }
            }, {
                field: 'unitPrice',
                title: '单价(元)',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return value.toFixed(2);
                }
            }, {
                field: 'amount',
                title: '总金额(元)',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return value.toFixed(2);
                }
            }, {
                field: 'confirmFlag',
                title: '确认标志',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (value == 0) {
                        return "待确认";
                    }
                    if (value == 1) {
                        return "已确认";
                    }
                    if (value == 3) {
                        return "已取消";
                    }
                    if (value == 4) {
                        return "已退费";
                    }
                }

            }, {
                field: 'decAmount',
                title: '退药量',
                align: "center",
                valign: 'middle',
                // formatter: function (value, row, index) {
                //     return value.toFixed(2);
                // }
            }, {
                field: 'execDept',
                title: '确认科室',
                align: "center",
                valign: 'middle'
            }, {
                field: 'confirmTime',
                title: '确认时间',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (value != null && value != "") {
                        return format(value, "yyyy-MM-dd HH:mm:ss");
                    }
                    return "";
                }
            }
        ],
        //点击全选框时触发的操作
        onCheckAll: function (rows) {
            getRefundFee();
        },
        //取消所有
        onUncheckAll: function (row) {
            getRefundFee();
        },
        //点击每一个单选框时触发的操作
        onCheck: function (row) {
            getRefundFee();
        },
        //取消每一个单选框时对应的操作；
        onUncheck: function (row) {
            getRefundFee();
        },
        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.data   //数据
            };
        },
    });
}


/**
 * 退费列表参数
 * @param patientId
 * @param times
 * @returns {{patientId: *, times: *}}
 */
function queryParamsForRefundFee(patientId, times, receiptNo) {
    var temp = {
        patientId: patientId,
        times: times,
        receiptNo: receiptNo
    };
    return temp;
};


/**
 * 每次选择费用清单明细时计算实际应退金额
 */
function getRefundFee() {
    extracted();
    if (chargeItemCodes == null) {
        $("#refundFeePrepare").text(0.00);
        return;
    }
    $.ajax({
        type: "POST",
        url: '/thmz/getNewListForRefundFee',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        data: JSON.stringify({
            patientId: $("#patientIdRefund").val(),
            times: $("#timesRefund").val(),
            receiptNo: $("#receiptNoRefund").val(),
            chargeItemCodes: chargeItemCodes
        }),
        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) {
                $("#refundFeePrepare").text(res.pageViewVo.data[0].refundFee.toFixed(2));
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
        }
    });
}


/**
 * 发起预退费
 */
function readyRefundFee() {
    extracted();
    $("#refundFeeModal").modal();
    initRefundChargeDetailTable(chargeItemCodes);
    $("#refundFeeDetailModal").modal("hide");

}

/**
 * 获取预退费金额
 * @returns {*}
 */
function extracted() {
    var allSelecteds = $('#refund_fee_detail_table').bootstrapTable('getAllSelections');
    chargeItemCodes = null;
    if (allSelecteds != null && allSelecteds.length > 0) {
        for (var i = 0; i < allSelecteds.length; i++) {
            var temp = allSelecteds[i].orderNo + "_" + allSelecteds[i].itemNo + "_" + allSelecteds[i].chargeItemCode;
            if (chargeItemCodes == null) {
                chargeItemCodes = temp;
            } else {
                chargeItemCodes += "," + temp;
            }
        }
    }
}

/**
 * 初始化退费重收费明细表格
 */
function initRefundChargeDetailTable(chargeItemCodes) {
    $('#refund_fee_table').bootstrapTable("destroy");
    $('#refund_fee_table').bootstrapTable({
        url: '/thmz/getNewListForRefundFee',         //请求后台的URL（*）
        method: 'post',                      //请求方式（*）
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: false,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        // sortName: 'orderNo',                //排序字段
        queryParams: queryParamsForRefundDetail(chargeItemCodes),           //传递参数（*）
        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: [
            // {
            //     checkbox: true
            // },
            {
                field: 'patientId',
                title: '患者编号',
                align: "center",
                valign: 'middle',
            }, {
                field: 'name',
                title: '患者姓名',
                align: "center",
                valign: 'middle',
            }, {
                field: 'oriAmount',
                title: '已收金额(元)',
                align: "center",
                valign: 'middle',
            }, {
                field: 'refundFee',
                title: '应退金额(元)',
                align: "center",
                valign: 'middle'
            }, {
                field: 'amount',
                title: '应收金额(元)',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return Math.abs(value);
                }
            }, {
                title: '操作',
                align: "center",
                valign: 'middle',
                // sortable: true,
                formatter: function (value, row, index) {
                    var str = "";
                    if (row.amount == 0 || row.amount == null || row.amount == undefined) {
                        str = '<button type="button" class="can-not-used" title="费用明细" ><i id="plusOrMinus" class="fa fa-plus"></i></button>';
                    } else {
                        str = '<button type="button" class="registration-no-color-foot-button" title="费用明细" onclick="initMzChargeDetailByBillItem(true)"><i id="plusOrMinus" class="fa fa-plus"></i></button>';
                    }
                    str += '<button type="button" class="registration-no-color-foot-button"title="确认退费" onclick="saveRefundFee()"><i class="fa fa-check"></i></button>';
                    return str;
                }
            }
        ],
        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": {}   //数据
                };
            }
            $("#oriAmount").text(ress.pageViewVo.data[0].oriAmount);
            $("#newAmount").text(ress.pageViewVo.data[0].amount);
            $("#refundAmount").text(ress.pageViewVo.data[0].refundFee);
            return {
                "total": ress.pageViewVo.total,//总页数
                "rows": ress.pageViewVo.data   //数据
            };
        },
    });
}

/**
 * 构建列表查询参数
 * @param chargeItemCodes
 * @returns {{patientId: string | number | string[] | undefined | jQuery, times: string | number | string[] | undefined | jQuery, billItemCode: number}}
 */
function queryParamsForRefundDetail(chargeItemCodes) {
    return {
        patientId: $("#patientIdRefund").val(),
        times: $("#timesRefund").val(),
        receiptNo: $("#receiptNoRefund").val(),
        chargeItemCodes: chargeItemCodes
    };
};

/**
 * 关闭预退费窗口
 */
function closeRefundFeeDetailModal() {
    $("#refundFeeDetailModal").modal("hide");
}

/**
 * 提交退费操作
 */
function saveRefundFee() {
    var params = queryParamsForRefundByBillItem(null);
    $.ajax({
        type: "POST",
        url: '/thmz/saveRefundFee',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        data: JSON.stringify(params),
        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'
                });
                $("#refundFeeModal").modal("hide");
                if (res.times > 0) {
                    prn1Print(res.patientId, res.times, false, 1);
                } else {
                    initFeeTable();
                }
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
        }
    });
}

/**
 * 清空查询条件
 */
function cleanParams() {
    $("#deptNoParam").selectpicker('val', null);//默认选中
    $("#deptNoParam").selectpicker('refresh');
    $("#smallDeptParam").selectpicker('val', null);//默认选中
    $("#smallDeptParam").selectpicker('refresh');
    $("#cardNo").val(null);
    $("#name").val(null);
    $('#reportrange span').html(moment(new Date('2012')).startOf('year').format('YYYY-MM-DD') + ' - ' + moment(new Date()).format("YYYY-MM-DD"));
    $("#patientId").val(null);
    //默认光标在卡号输入框
    $("#cardNo").focus();
    $("#inpatientNo").val(null);
}


/**
 * 增加收费方式
 */
function addPayType(id) {
    // var arr = $("#payForm").find("div.pay-item");
    // if (arr.length > 0) {
    //     for (var i = 0; i < arr.length; i++) {
    //         var temp = parseFloat($(arr[i]).find("input").val());
    //         if (temp == 0) {
    //             new PNotify({
    //                 title: '错误提示',
    //                 text: "存在未使用的收款方式，请不要重复添加！",
    //                 type: 'error',
    //                 hide: true,
    //                 styling: 'bootstrap3'
    //             });
    //             return;
    //         }
    //     }
    // }
    var payTypeId = null;
    if (id != undefined && id != null) {
        payTypeId = id;
    } else {
        var payTypeIndex = $("#payTypeIndex").val();
        payTypeId = "payType_" + payTypeIndex;
    }
    var html = '<div class="item form-group pay-item"><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 + '" onchange="checkFee(false)"></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" onchange="checkFee()"></div><div class="col-md-1 col-sm-1 col-xs-12" style="line-height: 34px;">元&nbsp;&nbsp;<a style="line-height: 34px;cursor: pointer;" onclick="closeThisParent(this)"><i class="fa fa-close"></i></a></div></div></div>';
    $("#changeAmountParent").before(html);
    initChequeType(payTypeId)
    if (payTypeIndex != undefined && payTypeIndex != null) {
        payTypeIndex = Add(payTypeIndex, 1);
        $("#payTypeIndex").val(payTypeIndex);
    }
    $("#addPayType").parent().removeClass("in").addClass("hide");
}

/**
 * 取消费用上传
 */
function cancelFee() {
    var patientId = $("#patientIdHaveTally").val();
    var times = $("#timesHaveTally").val();
    var receiptNo = $("#receiptNoHaveTally").val();
    $.ajax({
        type: "POST",
        url: '/thmz/cancelTmFee',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        data: JSON.stringify({"patientId": patientId, "times": times, "receiptNo": receiptNo}),
        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) {
                $("#fundPay").val(0);
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
        }
    });
}


