//@ sourceURL=toll_administration.js
var LODOP; //声明为全局变量
//默认打印机下标
var printIndex = -1;
//选中的要退的费用收费编码
var chargeItemCodes = null;
$(function () {
    //默认光标在卡号输入框
    $("#cardNo").focus();
    init_daterangepicker();
    initSelect();
    initFeeTable();
    //卡号输入改变事件
    cardNoChange();

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

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

    //初始门诊收银方式下拉选
    initChequeType("payType");
    //初始门诊收银方式下拉选
    initChequeType("payTypeEditPayMode");
    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);

    /**
     * 核酸检测跳转过来的直接刷新待收费列表
     */
    if(patientIdFullForNucleicAcid!=null && patientIdFullForNucleicAcid!=""){
        $("#cardNo").val(patientIdFullForNucleicAcid);
        $("#patientId").val(patientIdFullForNucleicAcid);
        initFeeTable();
    }
});

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

/**
 * 收费明细类型按钮切换事件
 * @param object
 */
function billItemButtonChange(object) {
    $("#bill_item_group").find("button").each(function (index, element) {
        if ($(element).hasClass("btn-primary")) {
            $(element).removeClass("btn-primary").addClass("btn-default");
        }
    });
    $(object).removeClass("btn-default").addClass("btn-primary");
    initChargeDetailTable();
    //默认光标在卡号输入框
    $("#cardNo").focus();
}

/**
 * 收费明细类型按钮切换事件
 * @param object
 */
function refundBillItemButtonChange(object) {
    $("#refund_bill_item_group").find("button").each(function (index, element) {
        if ($(element).hasClass("btn-primary")) {
            $(element).removeClass("btn-primary").addClass("btn-default");
        }
    });
    $(object).removeClass("btn-default").addClass("btn-primary");
    initMzChargeDetailByBillItem(false);
}

/**
 * 初始化下拉选
 */
function initSelect() {
    $(".selectpicker").selectpicker({
        dropuAuto: false
    });
    initDeptSelect();
    initDoctorSelect();
}


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


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

var $table_1;

/**
 * 初始化收费表格
 */
function initFeeTable() {
    var payMarkGroup = getIndex("pay_mark_group");
    var timeColumusName = "处方时间";
    var timeColumus = "priceTime";
    $("#refundFeeTip").removeClass("in").addClass("hide");
    $("#chargeFeeTip").removeClass("hide").addClass("in");
    if (payMarkGroup == 1) {
        timeColumusName = "缴费时间";
        timeColumus = "chargeDate";
        $("#refundFeeTip").removeClass("hide").addClass("in");
        $("#chargeFeeTip").removeClass("in").addClass("hide");
    } else if (payMarkGroup == 2) {
        timeColumusName = "退费时间";
        timeColumus = "inputDate";
    }


    var patientId = $("#patientId").val();
    //查询记账信息
    if (payMarkGroup == 0 && patientId != null && patientId != '') {
        $("#patientIdHaveTally").val(patientId);
        $.ajax({
            type: "GET",
            url: '/thmz/getTallyTotalCharge?patientId=' + patientId,
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
            success: function (res) {
                if (res == '401' || res == 401) {
                    window.location.href = '/thmz/login/view'
                    return;
                }
                if (res.code == 0) {
                    if (res.data != null && res.data > 0) {
                        $("#haveTallyModal").modal();
                        $("#totalTallyAmount").text(res.data.toFixed(2));
                    } else {
                        $("#haveTallyModal").modal('hide');
                    }
                } else {
                    new PNotify({
                        title: '错误提示',
                        text: res.message,
                        type: 'error',
                        hide: true,
                        styling: 'bootstrap3'
                    });
                }
            }
        });
    }

    $('#tb_table').bootstrapTable("destroy");
    $table_1 = $('#tb_table').bootstrapTable({
        url: '/thmz/listMzChargeDetail',         //请求后台的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: 5,                       //每页的记录行数（*）
        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: 'realNo',
                title: '缴费流水号',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return Math.abs(value);
                }
            }, {
                field: 'patientId',
                title: '患者编号',
                align: "center",
                valign: 'middle',
            }, {
                field: 'name',
                title: '患者姓名',
                align: "center",
                valign: 'middle',
            }, {
                field: 'times',
                title: '就诊次数',
                align: "center",
                valign: 'middle',
            }, {
                field: 'receiptNo',
                title: '结算次数',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return Math.abs(value);
                }
            }, {
                field: 'notDiscountAmount',
                title: '订单金额(元)',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return Math.abs(value).toFixed(2);
                }
            }, {
                field: 'discountAmount',
                title: '优惠总额(元)',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return Math.abs(value).toFixed(2);
                }
            }, {
                field: 'amount',
                title: '应付金额(元)',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return Math.abs(value).toFixed(2);
                }
            }, {
                field: 'warnDept',
                title: '科室',
                align: "center",
                valign: 'middle',
            }, {
                field: 'doctorCode',
                title: '医生',
                align: "center",
                valign: 'middle',
            }, {
                field: timeColumus,
                title: timeColumusName,
                align: "center",
                valign: 'middle',
                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="chargeDetailModal(\'' + row.patientId + '\',' + row.times + ',' + row.receiptNo + ')"><i class="fa fa-plus"></i></button>';
                    str += '<button type="button" class="registration-no-color-foot-button" title="诊断查询" onclick="diagnoseQuery(\'' + row.patientId + '\',' + row.times + ')"><i class="fa fa-search-minus"></i></button>';
                    var payMarkGroup = getIndex("pay_mark_group");
                    if (payMarkGroup == 0) {
                        str += '<button type="button" class="registration-no-color-foot-button"title="确认收费" onclick="tipHaveTally(' + row.amount + ',\'' + row.patientId + '\',' + row.times + ',\'' + row.name + '\',' + row.receiptNo + ')"><i class="fa fa-rmb"></i></button>';
                        return str;
                    }
                    if (payMarkGroup == 1) {
                       // str += '<button type="button" class="registration-no-color-foot-button" title="修改收款方式" onclick="showChequType(\'' + row.patientId + '\','+row.times+','+row.receiptNo+')"><i class="fa fa-credit-card"></i></button>' ;
                        str += '<button type="button" class="registration-no-color-foot-button" title="退费" onclick="refundFee(\'' + row.patientId + '\',' + row.times + ',' + row.receiptNo + ',' + row.printFlag + ');"><i class="fa fa-reply"></i></button>';
                        if (row.printFlag == 0) {
                            str += '<button type="button" id="button_' + row.realNo + '" class="registration-no-color-foot-button" title="发票打印" onclick="prn1PrintHand(\'' + row.patientId + '\',' + row.times + ',true,' + row.receiptNo + ',' + row.realNo + ');" 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;
                    }
                    if (payMarkGroup == 2) {
                       // str += '<button type="button" class="registration-no-color-foot-button" title="修改收款方式" onclick="showChequType(\'' + row.patientId + '\','+row.times+','+row.receiptNo+')"><i class="fa fa-credit-card"></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.pageViewVo.total,//总页数
                "rows": ress.pageViewVo.data   //数据
            };
        },
        /**
         * @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' && (payMarkGroup == 0 || payMarkGroup == 1)) {
                $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, $table_1);
                })
            }
        },
    });
}

/**
 * 更新病人缴费记录病人姓名
 * @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 = {
        mzChargeDetail: {
            patientId: $("#patientId").val(),
            warnDept: $("#deptNoParam").val(),
            doctorCode: $("#doctorParam").val(),
            name: $("#name").val(),
            payMark: 5
        },
        beginTime: new Date(rePortRangeArr[0]),
        endTime: new Date(rePortRangeArr[1]),
        pageSize: params.limit,   //页面大小
        pageIndex: params.offset / params.limit,  //页码
        serialNo: $("#serialNo").val(),
        ownData: $('#ownData').is(':checked') ? 0 : 1,
    };
    if (payMarkGroup == 1) {
        temp.mzChargeDetail.payMark = 0;
    } else if (payMarkGroup == 2) {
        temp.mzChargeDetail.payMark = 1;
    }
    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: 'origPrice',
                title: '原单价(元)',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                   if(value!=undefined && value!=null){
                       return value.toFixed(2);
                   }
                }
            }, {
                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());
}


/**
 * 打开收费明细窗口
 * @param data
 */
function chargeDetailModal(patientId, times, receiptNo) {
    $("#patientIdChargeItem").val(patientId);
    $("#timesChargeItem").val(times);
    $("#receiptNoChargeItem").val(receiptNo);
    $("#chargeDetailModal").modal();
    initChargeDetailTable();
}


/**
 * 病人当前就诊次数的诊断查询
 * @param data
 */
function diagnoseQuery(patientId, times) {
    $.ajax({
        type: "POST",
        url: '/thmz/getVisitTableByPatientIdAndTimes',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        data: JSON.stringify({"patientId": patientId, "times": times}),
        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.icdText != null || res.data.icdText != '') {
                    $("#diagnoseModal").modal();
                    $("#diagnose").html(res.data.icdText);
                } else {
                    new PNotify({
                        title: '操作提示',
                        text: '当前病人诊断未知',
                        type: 'warn',
                        styling: 'bootstrap3'
                    });
                }
            } else {
                errorMesage(res);
            }
        }
    });
}


// /**
//  * 打开退费重收明细窗口
//  * @param data
//  */
// function chargeRefundDetailModal(patientId, times) {
//     // $("#patientIdChargeItem").val(patientId);
//     // $("#timesChargeItem").val(times);
//     initMzChargeDetailByBillItem();
// }

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


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


/**
 * 校验收款金额
 * @param flag 是否是提交时候的校验，是的话，如果缴费金额不够，需要返回 false
 */
function checkFee(flag) {
    var realMoney = parseFloat($("#realMoney").val());
    realMoney = realMoney.toFixed(2);
    $("#realMoney").val(realMoney);
    var arr = $("#payForm").find("div.pay-item");
    if (arr.length > 0) {
        //非现金收款总金额
        var notCashAmount = 0;
        //现金收款总额
        var cashAmount = 0;
        for (var i = 0; i < arr.length; i++) {
            var temp = parseFloat($(arr[i]).find("input").val());
            if (isNaN(temp)) {
                temp = 0;
            }
            if ($(arr[i]).find("select").val() != 1) {
                notCashAmount = Add(notCashAmount, temp);
            } else {
                cashAmount = Add(cashAmount, 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;
                }
            }
        }
        if (notCashAmount > realMoney) {
            new PNotify({
                title: '错误提示',
                text: "非现金收款金额不能大于实收金额！",
                type: 'error',
                hide: true,
                styling: 'bootstrap3'
            });
            $("#addPayType").parent().removeClass("in").addClass("hide");
            return;
        }
        var totalAmount = Add(cashAmount, notCashAmount);
        $("#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");
            }
            $("#changeAmount").val(0.00);
            var surplusAmount = Minus(realMoney, totalAmount);
            $("#surplusAmount").val(surplusAmount);
            return;
        }
        var changeAmount = 0.00;
        if (totalAmount >= realMoney) {
            changeAmount = Minus(totalAmount, realMoney);
            //changeAmount = changeAmount.toFixed(2);
            $("#changeAmount").val(changeAmount);
            $("#addPayType").parent().removeClass("in").addClass("hide");
            if (!flag) {
                sendPeiceMessage(realMoney, totalAmount, changeAmount, '实际支付金额为' + totalAmount + '元,应找零' + changeAmount + '元', $("#patientIdHaveTally").val(), $("#nameHaveTally").val());
            }
        }
        //设置收费首页找零与应收和实收金额
        $("#payableAmount").text(realMoney);
        $("#paidAmount").text(totalAmount);
        $("#changedAmount").text(changeAmount);
    }
    //计算和设置折扣比例
    var amountMoneyConfirm = parseFloat($("#amountMoneyConfirm").text());
    var discount = 100;
    if (realMoney < amountMoneyConfirm) {
        discount = Division(realMoney, Multiply(amountMoneyConfirm, 100));
    }
    $("#discount").text(discount.toFixed(2))
    return true;
}


/**
 * 提示有记账记录
 */
function tipHaveTally(data, patientId, times, name, receiptNo) {
    if (patientId == null || patientId == "") {
        return;
    }
    $("#patientIdHaveTally").val(patientId);
    $("#nameHaveTally").val(name);
    $("#dataIdHaveTally").val(data);
    $("#timesHaveTally").val(times);
    $("#receiptNoHaveTally").val(receiptNo);
    // $.ajax({
    //     type: "GET",
    //     url: '/thmz/getTallyTotalCharge?patientId=' + patientId,
    //     contentType: "application/json;charset=UTF-8",
    //     dataType: "json",
    //     headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
    //     success: function (res) {
    //         if (res == '401' || res == 401) {
    //             window.location.href = '/thmz/login/view'
    //             return;
    //         }
    //         if (res.code == 0) {
    //             if (res.data != null && res.data > 0) {
    //                 $("#haveTallyModal").modal();
    //                 $("#totalTallyAmount").text(res.data.toFixed(2));
    //             } else {
    //                 $("#haveTallyModal").modal('hide');
    //                 confirmFeeModal(null,null,null);
    //             }
    //         } else {
    //             new PNotify({
    //                 title: '错误提示',
    //                 text: res.message,
    //                 type: 'error',
    //                 hide: true,
    //                 styling: 'bootstrap3'
    //             });
    //         }
    //     }
    // });

    $.ajax({
        type: "POST",
        url: '/thmz/getTmFee',
        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) {
                if (res.data != undefined && res.data != null) {
                    $("#fundPay").val(res.data.fundPay);
                    //$("#realMoney").val(res.data.selfPay);
                } else {
                    $("#fundPay").val(0.0);
                }
            } else {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
            $("#saveConfirmFee").attr("disabled", false);
        }
    });

    confirmFeeModal(null, null, null);
}

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: "client",           //分页方式：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");
                }
            }
            // , {
            //     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="reInsertDetailModal(\'' + row.patientId + '\',' + row.times + ',' + row.receiptNo + ')"><i class="fa fa-exchange"></i></button>';
            //         return str;
            //     }
            // }
        ],
        /**
         * @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 saveConfirmFee() {
    $("#saveConfirmFee").attr("disabled", true);
    if (!checkFee(true)) {
        $("#saveConfirmFee").attr("disabled", false);
        return;
    }
    var jsonData = JSON.parse('{"patientId":"","times":"","receiptNo":"","mzDepositFiles":[]}');
    var patientId = $("#patientIdHaveTally").val();
    var times = $("#timesHaveTally").val();
    var receiptNo = $("#receiptNoHaveTally").val();
    jsonData.patientId = patientId;
    jsonData.times = times;
    jsonData.receiptNo = receiptNo;
    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('{"chequeType":"","amount":""}');
            tempJson.chequeType = $(arr[i]).find("select").val();
            //现金有可能会多收，比入实收37，对方给了100，需要找零63. 所以必须减去找零金额，才是实收金额
            if (tempJson.chequeType == "1") {
                temp = temp - $("#changeAmount").val();
                temp = temp.toFixed(2);
            }
            tempJson.amount = temp;
            jsonData.mzDepositFiles[i] = tempJson;
        }
    }
    $.ajax({
        type: "POST",
        url: '/thmz/chargeFee',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        data: JSON.stringify(jsonData),
        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) {
                prn1Print(patientId, times, true, res.receiptNo);
                new PNotify({
                    title: '操作提示',
                    text: res.message,
                    type: 'success',
                    hide: true,
                    styling: 'bootstrap3'
                });
                $("#confirmFeeModal").modal("hide");
                $("#patientId").val(null);
                $("#cardNo").val(null);
                $("#name").val(null);
                $("#fundPay").val(0);
                initFeeTable();
                //默认光标在卡号输入框
                $("#cardNo").focus();
                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'
                });
            }
            $("#saveConfirmFee").attr("disabled", false);
        }
    });
}


/**
 * 直接打印发票
 * @param patientId
 * @param times
 * @param chargeFeeFlag 收费 退费标记  true 收费和重打发票来源 false 退费来源
 */
function prn1PrintHand(patientId, times, chargeFeeFlag, receiptNo, realNo) {
    $("#button_" + realNo).css("display", "none");
    prn1Print(patientId, times, chargeFeeFlag, receiptNo);
}


/**
 * 直接打印发票
 * @param patientId
 * @param times
 * @param chargeFeeFlag 收费 退费标记  true 收费和重打发票来源 false 退费来源
 */
function prn1Print(patientId, times, chargeFeeFlag, receiptNo) {
    var url = '/thmz/getAllSerialForThisTime?patientId=' + patientId + "&times=" + times + "&receiptNo=" + receiptNo;
    printCommon(url, patientId, times, chargeFeeFlag);
}

/**
 * 重打发票
 * @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
 * @param chargeFeeFlag 收费 退费标记  true 收费和重打发票来源 false 退费来源
 */
function printCommon(url, patientId, times, chargeFeeFlag) {
    setPrint();
    var height = "93.15mm";
    // 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.data == null || res.data.length == 0) {
                    return;
                }
                // countReceiot++;
                for (var i = 0; i < res.data.length; i++) {
                    LODOP = getLodop();
                    var temp = res.data[i].mzReceiptSerial;
                    LODOP.PRINT_INITA(6, 0, "120mm", height, "泰和门诊发票打印");
                    //设置默认打印机
                    LODOP.SET_PRINTER_INDEX(printIndex);
                    LODOP.SET_SHOW_MODE("BKIMG_WIDTH", "120mm");
                    LODOP.SET_SHOW_MODE("BKIMG_HEIGHT", height);
                    LODOP.SET_PRINT_PAGESIZE(1, "120mm", height, "CreateCustomPage");
                    LODOP.SET_PRINT_MODE("CREATE_CUSTOM_PAGE_NAME", "门诊发票");//对新建的纸张重命名
                    LODOP.SET_PRINT_STYLE("FontSize", 11); //字体大小
                    LODOP.ADD_PRINT_TEXT("6mm", "0mm", "45mm", "3mm", "湖南泰和医院管理有限公司");
                    LODOP.ADD_PRINT_TEXT("6mm", "59mm", "30mm", "3mm", "机制号:");
                    LODOP.ADD_PRINT_TEXT("6mm", "72mm", "20mm", "3mm", temp.serialNo);
                    LODOP.ADD_PRINT_TEXT("19mm", "0mm", "35mm", "3mm", temp.receiptBill);
                    LODOP.ADD_PRINT_TEXT("25mm", "7mm", "40mm", "3mm", res.mzPatientMi.name);
                    LODOP.ADD_PRINT_TEXT("25mm", "61mm", "27mm", "3mm", patientId);
                    var feeList = res.data[i].feeList;
                    if (feeList != null && feeList.length > 0) {
                        var top = 32;
                        var left = 6;
                        for (var j = 0; j < feeList.length; j++) {
                            var row = parseInt(j / 3);
                            var tempTop = top + row * 5;
                            var tempLeft = left;
                            if (j % 3 == 1) {
                                tempLeft = left + 30;
                            } else if (j % 3 == 2) {
                                tempLeft = left + 60;
                            }
                            LODOP.ADD_PRINT_TEXT(tempTop + "mm", tempLeft + "mm", "30mm", "3mm", feeList[j]);
                        }
                    }
                    // LODOP.ADD_PRINT_TEXT("32mm","25mm","25mm","3mm","诊查费  10.00");
                    // LODOP.ADD_PRINT_TEXT("32mm","50mm","25mm","3mm","中成药费30.10");
                    // LODOP.ADD_PRINT_TEXT("37mm","25mm","25mm","3mm","治疗费  22.00");
                    // LODOP.ADD_PRINT_TEXT("37mm","50mm","25mm","3mm","材料费  14.20");
                    // LODOP.ADD_PRINT_TEXT("42mm","25mm","25mm","3mm","西药费 161.20");
                    var qyxxs = res.data[i].qyxxs;
                    if (qyxxs != null && qyxxs.length > 0) {
                        var top = 54;
                        for (var j = 0; j < qyxxs.length; j++) {
                            var row = j / 3;
                            var tempTop = top + row * 10;
                            var qyxx = qyxxs[j];
                            var arr = qyxx.split(",");
                            LODOP.ADD_PRINT_TEXT(tempTop + "mm", "6mm", "50mm", "3mm", "取药窗口：" + arr[0]);
                            LODOP.ADD_PRINT_TEXT(tempTop + "mm", "61mm", "50mm", "3mm", "取药号码：" + arr[1]);
                        }
                    }
                    // LODOP.ADD_PRINT_TEXT("54mm","25mm","50mm","3mm","取药窗口：西药房4号窗口");
                    // LODOP.ADD_PRINT_TEXT("54mm","80mm","35mm","3mm","取药号码：408392");
                    LODOP.ADD_PRINT_TEXT("65mm", "21mm", "60mm", "3mm", temp.totalCharge + " 元");
                    LODOP.ADD_PRINT_TEXT("72mm", "19mm", "60mm", "3mm", res.data[i].totalChargeStr);
                    LODOP.ADD_PRINT_TEXT("79mm", "0mm", "15mm", "3mm", res.data[i].year);//年
                    LODOP.ADD_PRINT_TEXT("79mm", "13mm", "10mm", "3mm", res.data[i].month);//月
                    LODOP.ADD_PRINT_TEXT("79mm", "25mm", "10mm", "3mm", res.data[i].day);//日
                    LODOP.ADD_PRINT_TEXT("79mm", "53mm", "50mm", "3mm", temp.operatorId);//收费员
                    LODOP.PRINT();
                    //LODOP.PREVIEW();
                    initFeeTable();
                }

            } else if (res.code == -1) {
                //退费就退出，不提示异常
                if (!chargeFeeFlag) {
                    return;
                }
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
        }
    });
}


//
// /**
//  * 加载打印机列表
//  * @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.printIndex;
            } 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   //数据
            };
        },
        //加载完成事件
        onLoadSuccess: function (data) {
            getRefundFee();
        }
    });
}


/**
 * 退费列表参数
 * @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');
    $("#doctorParam").selectpicker('val', null);//默认选中
    $("#doctorParam").selectpicker('refresh');
    $("#cardNo").val(null);
    $("#name").val(null);
    $('#reportrange span').html(moment().format('YYYY-MM-DD') + ' - ' + moment().format('YYYY-MM-DD'));
    $("#patientId").val(null);
    //默认光标在卡号输入框
    $("#cardNo").focus();
    $("#serialNo").val(null);
    $("#ownData").removeAttr("checked");
}


/**
 * 增加收费方式
 */
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'
                });
            }
        }
    });
}

/**
 * 查询当前门诊缴费订单的所有缴费方式列表
 * @param patientId
 * @param times
 * @param receiptNo
 */
function showChequType(patientId, times, receiptNo) {
    $("#depositFileModal").modal();
    $('#deposit_file_detail_table').bootstrapTable("destroy");
    $('#deposit_file_detail_table').bootstrapTable({
        url: '/thmz/getAllDepositFileForThisTime?patientId=' + patientId + "&times=" + times+"&receiptNo="+Math.abs(receiptNo),         //请求后台的URL（*）
        method: 'get',                      //请求方式（*）
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: false,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 5,                       //每页的记录行数（*）
        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: 'times',
                title: '就诊次数',
                align: "center",
                valign: 'middle',
            },{
                field: 'amount',
                title: '支付金额(元)',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return value.toFixed(2);
                }
            },
            {
                field: 'chequeTypeName',
                title: '支付方式',
                align: "center",
                valign: 'middle'
            }
        ],
        onDblClickRow: function (row) {
            editChequType(row.receiptSn,row.chequeType,row.dcountNo,row.chequeTypeName);
        },
        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   //数据
            };
        },
    });
}



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


/**
 * 提交修改收款方式
 */
function saveEditPayMode(){
    $.ajax({
        type: "GET",
        url: '/thmz/updateChequType?oldChequeType=' + $("#chequType").val() + "&receiptSn=" + $("#receiptSn").val()+"&chequeType="+$("#payTypeEditPayMode").val(),
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                successMesage(res);
                clearEditPayMode();
                $("#editPayModeModal").modal("hide");
            } else if (res.code == -1) {
                new PNotify({
                    title: '错误提示',
                    text: res.message,
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
            }
        }
    });
}

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

//
// /**
//  * 反写备份表的数据到正式表中，记账的数据在备分表
//  * @param patientId
//  * @param times
//  * @param receiptNo
//  */
// function reInsertDetailModal(patientId,times ,receiptNo) {
//     $.ajax({
//         type: "POST",
//         url: '/thmz/reSaveDetailForByjz',
//         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) {
//                successMesage(res);
//                initFeeTable();
//             } else {
//                 new PNotify({
//                     title: '错误提示',
//                     text: res.message,
//                     type: 'error',
//                     hide: true,
//                     styling: 'bootstrap3'
//                 });
//             }
//         }
//     });
// }