//@ sourceURL=accepting.js

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

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

    /**
     * 收费
     */
    $("#chargeFee").on("click", function (t) {
        $("#chargeFeeModal").modal("show");
    });

    initChequeType();

    /**
     * 收费保存
     */
    $("#saveEdit").on("click", function (t) {
        $.ajax({
            type: "POST",
            url: '/thmz/saveZyDepositFile',
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            async: false,
            data: JSON.stringify({
                "status": "1",
                "inpatientNo": $("#admissionNumber").val(),
                "depoType": $("#depoType").val(),
                "depoAmount": $("#depoAmount").val(),
                "chequeNo": $("#chequeNo").val()
            }),
            headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
            success: function (res) {
                if (res == '401' || res == 401) {
                    window.location.href = '/thmz/login/view'
                    return;
                }
                if (res.code == 0) {
                    $('#tb_table').bootstrapTable("refresh");
                    $("#chargeFeeModal").modal("hide");
                    successMesage(res);
                    if (confirm("现在打印收据吗？")) {
                        prn1Print(res.zyDepositFile.inpatientNo,res.receiptNo,false);
                    }
                } else {
                    errorMesage(res);
                }
            }
        });
    });


    /**
     * 退费提交
     */
    $("#refundZyFee").on("click", function (t) {
       saveRefundZyFee();
    });

    // initStatus();
});


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


/**
 * 初始化事务
 */
function initStatus() {
    $('#status').empty();
    $('#status').html('<option value="1">预交</option><option value="2">退费</option>');
    $('#status').selectpicker('refresh');
}

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

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


/**
 * 根据病人门诊id或者住院号查询病人信息
 */
function getZyActpatientByInpatientNoOrMzNO(id) {
    $('#patientTable').bootstrapTable("destroy");
    $('#patientTable').bootstrapTable({
        url: '/thmz/getZyActpatientByInpatientNoOrMzNO',         //请求后台的URL（*）
        method: 'post',                      //请求方式（*）
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        queryParams: queryPatientListParams,           //传递参数（*）
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 10,                       //每页的记录行数（*）
        pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
        search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
        strictSearch: true,
        showColumns: false,                  //是否显示所有的列
        showRefresh: false,                  //是否显示刷新按钮
        minimumCountColumns: 2,             //最少允许的列数
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
        showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
        cardView: false,                    //是否显示详细视图
        detailView: false,
        //rowStyle:rowStyle,//通过自定义函数设置行样式
        ajaxOptions: {
            headers: {
                'Accept': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem("token")
            }
        },
        columns: [
             {
                field: 'name',
                title: '姓名',
                align: "center",
                valign: 'middle',
            }, {
                field: 'inpatientNo',
                title: '住院号',
                align: "center",
                valign: 'middle',
            }, {
                field: 'admissTimes',
                title: '住院次数',
                align: "center",
                valign: 'middle'
            }
        ],
        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(res.data.length==0){
                if (id == 'admissionNumber') {
                    $("#patientId").val(null);
                } else if (id == 'patientId') {
                    $("#admissionNumber").val(null);
                }
                $("#userName").val(null);
                $("#gender").val(null);
                $("#bedNo").val(null);
                $("#deptName").val(null);
                $("#admissDate").val(null);
                $("#responceType").val(null);
                $("#totalAmount").val(null);
                $("#balance").val(null);
                //listDepositFile();
                new PNotify({
                    title: '警告提示',
                    text: '没有查到合适的患者',
                    type: 'waring',
                    hide: true,
                    styling: 'bootstrap3'
                });
                return {
                    "total": 0,//总页数
                    "rows": {}   //数据
                };
            }
            if(res.data.length==1){
                fillPatinet(res.data[0].inpatientNo,res.data[0].admissTimes);
            }
            if(res.data.length>1){
                $("#patientModal").modal();
            }
            return {
                "total": ress.total,//总页数
                "rows": ress.data   //数据
            };
        },
        //双击触发的事件，当双击就会获取row，row就是该整行的内容，其中"row.playerName"中"playerName"是data-field定义的字段，（如果在js中定义，就是field定义的字段,）可以通过该方法获取该行所有列的值
        onDblClickRow: function (row) {
            $("#patientModal").modal("hide");
            fillPatinet(row.inpatientNo,row.admissTimes);
        }
    });
}

/**
 * 创建病人列表参数
 * @param params
 * @returns {{inpatientNo: *, admissTimes: *}}
 */
function queryPatientListParams(params) {
    var index = getIndex("regi_List_btn_group");
    var tableName = 'zy_actpatient';
    if (index == 1) {
        tableName = 'zy_inactpatient';
    }
    var temp = {
        "inpatientNo": $("#admissionNumber").val(),
        "mzNo": $("#patientId").val(),
        "tableName": tableName,
        "pageIndex":params.offset / params.limit,
        "pageSize":params.limit
    };
    return temp;
};


/**
 * 按照病人inpatientNo查询病人信息
 * @param patientId
 * @param admissTimes
 */
function fillPatinet(inpatientNo,admissTimes) {
    if (inpatientNo == null || inpatientNo == "") {
        return;
    }
    var index = getIndex("regi_List_btn_group");
    var tableName = 'zy_actpatient';
    if (index == 1) {
        tableName = 'zy_inactpatient';
    }
    $.ajax({
        type: "GET",
        url: '/thmz/getByInpatientNo?inpatientNo=' + inpatientNo +"&admissTimes="+admissTimes+ "&tableName=" + tableName,
        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) {
                    inpatientNoFull = res.data.inpatientNo.trim();
                    $("#admissionNumber").val(inpatientNoFull);
                    $("#patientId").val(res.data.mzNo);
                    $("#userName").val(res.data.name);
                    $("#gender").val(res.data.gender);
                    $("#bedNo").val(res.data.bedNo);
                    $("#deptName").val(res.data.deptName);
                    $("#admissDate").val(format(res.data.admissDate, "yyyy-MM-dd"));
                    $("#responceType").val(res.data.responceTypeName);
                    $("#totalAmount").val(res.data.totalCharge);
                    $("#balance").val(res.data.balance);
                    admissTimesFull = res.data.admissTimes;
                    listDepositFile();
                }
            } else {
                errorMesage(res);
            }
        }
    });
}


/**
 * 住院收费明细
 */
function listDepositFile() {
    $('#tb_table').bootstrapTable("destroy");
    $("#totalPay").text(0.00);
    $("#totalRefund").text(0.00);
    $('#tb_table').bootstrapTable({
        url: '/thmz/getZyDepositFileBYInpatientNoAndTimes',         //请求后台的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: 10,                       //每页的记录行数（*）
        pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
        search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
        strictSearch: true,
        showColumns: false,                  //是否显示所有的列
        showRefresh: false,                  //是否显示刷新按钮
        minimumCountColumns: 2,             //最少允许的列数
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
        showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
        cardView: false,                    //是否显示详细视图
        detailView: false,
        //rowStyle:rowStyle,//通过自定义函数设置行样式
        ajaxOptions: {
            headers: {
                'Accept': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem("token")
            }
        },
        columns: [
            {
                field: 'ledgerSn',
                title: '账页号',
                align: "center",
                valign: 'middle'
            }, {
                field: 'depoDate',
                title: '时间',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return format(value, "yyyy-MM-dd HH:mm:ss");
                }
            }, {
                field: 'statusName',
                title: '事务',
                align: "center",
                valign: 'middle',
            }, {
                field: 'depoAmount',
                title: '金额',
                align: "center",
                valign: 'middle',
            }, {
                field: 'receiptNo',
                title: '收据号',
                align: "center",
                valign: 'middle'
            }, {
                field: 'depoTypeName',
                title: '收费方式',
                align: "center",
                valign: 'middle'
            }, {
                field: 'chequeNo',
                title: '凭证号',
                align: "center",
                valign: 'middle',
            }, {
                field: 'opIdName',
                title: '操作员',
                align: "center",
                valign: 'middle'
            }, {
                title: '操作',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    var str='';
                    if(row.depoAmount>0){
                        //未结算且 是预交和未退费的可以退费
                        if(row.settleType==0 && row.status =='1' && row.reportFlag != 1){
                            str +='<button type="button" class="btn btn-primary  btn-sm" onclick="refundZyFee(\'' + row.receiptNo + '\',\'' + row.depoAmount + '\',\'' + row.depoType + '\')">退费</button>';
                        }
                        if(row.deleted!=1){
                            if(row.printed==0){
                                str +='<button type="button" class="btn btn-primary  btn-sm" onclick="prn1Print(\''+ row.inpatientNo + '\',\'' + row.receiptNo + '\',false)">打印收据</button>';
                            }else if(row.printed==1){
                                str +='<button type="button" class="btn btn-primary  btn-sm" onclick="prn1Print(\''+ row.inpatientNo + '\',\'' + row.receiptNo + '\',true)">重打收据</button>';
                            }
                        }
                    }
                    return [str].join('');
                }
            }
        ],
        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": {}   //数据
                };
            }
            $("#totalPay").text(ress.totalPay.toFixed(2));
            $("#totalRefund").text(ress.totalRefund.toFixed(2));
            return {
                "total": ress.total,//总页数
                "rows": ress.data   //数据
            };
        },
    });
}

/**
 * 构建列表查询参数
 * @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 temp = {
        inpatientNo: inpatientNoFull,
        admissTimes: admissTimesFull
    };
    return temp;
};


/**
 * 退费确认页面
 * @param receiptNo
 * @param depoAmount
 * @param depoType
 */
function refundZyFee(receiptNo,depoAmount,depoType) {
    $("#receiptNo").val(receiptNo);
    $("#refungZyFeeModal").modal("show");
    $("#refundDepoAmount").val(depoAmount);
    $('#refundDepoType').selectpicker('val', depoType);
    $('#refundDepoType').selectpicker('refresh');
}


/**
 * 退住院预交金
 * @param receiptNo
 */
function saveRefundZyFee() {
    $.ajax({
        type: "POST",
        url: '/thmz/saveZyDepositFile',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        async: false,
        data: JSON.stringify({
            "status": "2",
            "receiptNo": $("#receiptNo").val(),
            "depoType": $("#refundDepoType").val()
        }),
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                $('#tb_table').bootstrapTable("refresh");
                $("#refungZyFeeModal").modal("hide");
                $("#receiptNo").val(null);
                successMesage(res);
            } else {
                errorMesage(res);
            }
        }
    });
}


/**
 * 清空
 */
function clearInput() {
    $("#admissionNumber").val(null);
    $("#patientId").val(null);
    $("#userName").val(null);
    $("#gender").val(null);
    $("#bedNo").val(null);
    $("#deptName").val(null);
    $("#admissDate").val(null);
    $("#responceType").val(null);
    $("#totalAmount").val(null);
    $("#balance").val(null);
}

/**
 * @param inpatientNo  住院号
 * @param receiptNo  票据号
 * @param flag 是否重打  true 重打 false 打印
 */
function prn1Print(inpatientNo,receiptNo,flag) {
    setPrint();
    if(flag){
        //重打
        prn1PrintReal(inpatientNo,receiptNo,flag);
    }else {
        //直接打印
        $.ajax({
            type: "GET",
            url: '/thmz/printZyDepositFile?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) {
                    prn1PrintReal(inpatientNo,receiptNo,flag);
                    $('#tb_table').bootstrapTable("refresh");
                } else {
                    errorMesage(res);
                }
            }
        });
    }
}


/**
 * 打印收据的底层方法
 * @param inpatientNo
 * @param receiptNo
 * @param flag
 */
function prn1PrintReal(inpatientNo,receiptNo,flag) {
    $.ajax({
        type: "GET",
        url: '/thmz/getZyDepositFileByReceiptNo?receiptNo=' + receiptNo+"&inpatientNo="+inpatientNo,
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                if (res.data != null) {
                    inpatientNo = inpatientNo.trim();
                    $("#inpatientNo").text(inpatientNo);
                    $("#icCardNo").text(res.mzPatientMi.icCardNo);
                    $("#name").text(res.mzPatientMi.name);
                    $("#admissDept").text(res.zyActpatient.admissDept);
                    $("#depoTypeName").text(res.zdChequeType.name);
                    $("#depoAmountPj").text(res.data.depoAmount.toFixed(2));
                    $("#chequeNoPj").text(res.data.chequeNo);
                    $("#depoAmountDx").text(res.depoAmountDx);
                    $("#cashName").text(res.employee.employeeName);
                    $("#receiptNoPj").text(receiptNo.trim());
                    $("#printDate").text(format(new Date(), "yyyy-MM-dd"));
                    if(flag){
                        $("#cdFlag").text("重打");
                    }
                    LODOP = getLodop();
                    //设置默认打印机
                    LODOP.SET_PRINTER_INDEX(printIndex);
                    LODOP.SET_PRINT_STYLE("FontSize", 9); //字体大小
                    LODOP.SET_SHOW_MODE("BKIMG_WIDTH", "192mm");
                    LODOP.SET_SHOW_MODE("BKIMG_HEIGHT", "97mm");
                    LODOP.SET_PRINT_PAGESIZE(1, "192mm", "97mm", "CreateCustomPage");
                    LODOP.SET_PRINT_MODE("CREATE_CUSTOM_PAGE_NAME", "住院发票");//对新建的纸张重命名
                    var strStyle="<style>table{width: 170mm;} table,td,th {border-width: 1px;border-style: solid;border-collapse: collapse;padding: 8px;}</style>"
                    LODOP.ADD_PRINT_HTM("0mm", "8mm", "120mm", "280mm", strStyle+ document.getElementById("report_table_1").innerHTML);
                    LODOP.PRINT();
                    //LODOP.PREVIEW();
                    $("#inpatientNo").text("");
                    $("#icCardNo").text("");
                    $("#name").text("");
                    $("#admissDept").text("");
                    $("#depoTypeName").text("");
                    $("#depoAmountPj").text("");
                    $("#chequeNoPj").text("");
                    $("#depoAmountDx").text("");
                    $("#cashName").text("");
                    $("#receiptNoPj").text("");
                    $("#printDate").text("");
                    $("#cdFlag").text("");
                }
            } else {
                errorMesage(res);
            }
        }
    });
}


/**
 * 查询默认打印机
 */
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;
            }
        }
    });
}