$(document).ready(function () {
    LoadVisitType();
    LoadBranch();    
});



////filter_branch_refund
function LoadBranch() {

    //Only KinderSurge
    //var dml = ''
    //if (parseInt($('#hiddenRole_id').val()) == 1) {
    //    dml = 'DLBRAN'
    //}
    //else {
    //    dml = 'LBRAN'
    //}

    var subdepartment = {
        Dml_Indicator: "LBRAN",
        //Dml_Indicator: dml,
        name: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            $('#ldabranch_id').empty();
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    var SubDepartment;
                    var default_opt = '<option value="0">All</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#ldabranch_id').append(SubDepartment);
                        $('#SelBranchSearchPopup').append(SubDepartment);
                        //$('#ldabranch_id').change();
                    }
                    else {
                        if ($('#hiddenRole_id').val() == 1) {
                            $('#ldabranch_id').append(SubDepartment);
                            $('#SelBranchSearchPopup').append(SubDepartment);

                        }
                        else {
                            $('#ldabranch_id').append(default_opt + SubDepartment);
                            $('#SelBranchSearchPopup').append(SubDepartment);
                        }
                       
                    }

                    //if ($('#hiddenRole_id').val() == 1) {
                    //    $('#ldabranch_id').val($('#HospitalBranchID').val());
                    //}
                    //else 
                    if ($('#hiddenRole_id').val() != 2) {
                        $('#ldabranch_id').val($('#HospitalBranchID').val());
                        $('#ldabranch_id').attr('disabled', true);
                        //For Patient details PopUP
                        $('#SelBranchSearchPopup').val($('#HospitalBranchID').val());
                        $('#SelBranchSearchPopup').attr('disabled', true);
                    }

                    //if ($('#hdnbilling_type').val() != '') {
                    //    $('#ldabranch_id').val($('#hdnBranch_id').val());
                    //}
                    ShowRefund();
                 
             
                   
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}


$('#btnfilter').on('click', function () {
    debugger;
    ShowRefundfilter();
})



$('#btnclear').click(function () {
    debugger;
    fileclear();
   
    ShowRefund();
    
})

function fileclear() {
    debugger;
    if ($('#hiddenRole_id').val() == 2) {
        $('#ldabranch_id').val("0");
    }
    
    $('#RF_visit_type').val("0");
    $('#RF_refund_type').val("0");
    $('#RF_refund_mode').val("0");
    $('#RF_status').val("0");
    $('#txtfrom_date').val('');
    $('#txtto_date').val('');
    $('#RF_refund_number').val('');
    $('#RF_bill_number').val('');
}



function ShowRefund() {
    debugger;
    $('#shade_slot').show();

    var from_date = '', to_date=''
    if ($('#txtfrom_date').val() != '' && $('#txtto_date').val() != '') {
        from_date = $('#txtfrom_date').val();
        to_date = $('#txtto_date').val();
        from_date = from_date.split('/');
        from_date = from_date[2] + "-" + from_date[1] + "-" + from_date[0];
        to_date = to_date.split('/');
        to_date = to_date[2] + "-" + to_date[1] + "-" + to_date[0];
    }

   
    var RefundTbldata = {

        Dml_Indicator: 'RVS',
        //branch_id: $('#ldabranch_id').val(),
        billing_no: $('#RF_bill_number').val(),
        refund_no: $('#RF_refund_number').val(),
        billing_type: $('#RF_visit_type').val() == "" || $('#RF_visit_type').val() == null ? 0 : $('#RF_visit_type').val(),
        billing_refund_type: $('#RF_refund_type').val(),
        refund_mode: $('#RF_refund_mode').val(),
        status: $('#RF_status').val(),
        from_date: from_date,
        to_date: to_date

    }

    return $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/Refund_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RefundTbldata),
        success: function (data) {
            $('#refund_view_body').empty();
            var data2 = JSON.parse(data);
            $('#shade_slot').hide();
            if (jQuery.isEmptyObject(data)) {
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var row_data = "";
                    

                    //tr = $('<table id="example1" class="table table-bordered dt-responsive" />');


                    //tr.append("<thead><tr><th>S.No</th><th>Patient Name</th><th>Bill Code</th><th>Refund Code</th><th>Billing Refund Type</th><th>Refund Type</th><th>Refund Mode</th><th>Vocher Code</th><th>Refund Amount</th><th>Visit Type</th><th>Status</th><th>Action</th></tr></thead><tbody>");

                    $('#tblrefund').dataTable().fnClearTable();
                    $('#tblrefund').dataTable().fnDraw();
                    $('#tblrefund').dataTable().fnDestroy();

                    $.each(data1.Table, function (i, emp) {

                        var RefundStatus = '';
                        var InorRef = '';
                        var channel = '';
                        var refund_print = '';

                        if (emp.billing_channel == 2)
                        {
                            channel = 'Mobile channel';
                            
                        }
                        else
                        {
                            channel = 'Web channel';
                        }


                        if (emp.refund_status == 1) {
                            RefundStatus = '<span class="label label-warning">Pending Approval</span>';
                            InorRef = '<a  title="Initiate" data-toggle="modal" id="bill_refund_'+emp.billing_no+'" data-target="#details_popup" type="button" href="#" data-id="RF_F1" data-type="role_rights_function" data-nav="popup" data-name="add_refund_details" onclick=Refund_Initiate(this,"' + emp.billing_no + '","' + emp.patient_id + '","' + emp.visit_type + '","' + emp.branch_id + '","' + emp.visit_report_id + '","' + emp.billing_refundid + '")>Initiate</a>';
                        }
                        else if (emp.billing_type == 2 && emp.refund_status == 3) {
                            RefundStatus = '<span class="label label-danger">Requested</span>';
                            InorRef = '<a  title="Initiate" class="btn_r" data-id="RF_F1" data-type="role_rights_function" data-nav="redirect" data-name="/BillingMaster/refund?Patient_Id=' + emp.patient_id + "&Work_order_detailsid=" + emp.work_order_detailsid + "&Billcode=" + emp.billing_no + "&refund_code=" + emp.billing_refund_code + "&billing_type=" + emp.billing_type + "&Branch_id=" + emp.branch_id + '">Refund</a>';
                        }
                        //else if(emp.billing_type == 2 && emp.refund_status == 1)
                        //{
                        //    RefundStatus = '<button type="button" class="btn btn-warning btn-xs">Pending Approval</button>';
                        //    InorRef = '<a data-toggle="modal" data-target="#details_popup" type="button" href="#" class="btn btn-primaryuse btn-xs" data-id="RF_F1" data-type="role_rights_function" data-nav="popup" data-name="add_refund_details" onclick=Refund_Initiate(this,"' + emp.billing_no + '","' + emp.patient_id + '","' + emp.visit_type + '","' + emp.branch_id + '","' + emp.visit_report_id + '","' + emp.billing_refundid + '")>Initiate</a>';
                        //}
                        else if (emp.refund_status == 2) {
                            RefundStatus = '<span class="label label-success">Completed</span>';
                            InorRef = "";
                            refund_print = '<a onclick=refund_print(' + emp.billing_no + ',' + emp.patientid + ',' + emp.hospitalid + ',' + emp.branch_id + ')> Print </a>';
                        }
                        else {

                        }

                        

                        //Details = '<a data-toggle="modal" data-target="#details_popup" type="button" href="#" class="btn btn-info btn-xs" data-id="RF_F1" data-type="role_rights_function" data-nav="popup" data-name="add_refund_details" onclick=RefundDetails(this,"' + emp.billing_no + '","' + emp.patient_id + '","' + emp.visit_type + '","' + emp.branch_id + '","' + emp.visit_report_id + '");>Details</a>';
                        info = '<a title="View" data-toggle="modal" onclick=RefundInfo("' + emp.billing_refundid + '","' + emp.patient_id + '","' + emp.visit_type + '","' + emp.branch_id + '","' + emp.visit_report_id + '");><input type="hidden" id="RR_' + emp.billing_refundid + '" value="' + emp.refund_reason + '"/>View</a>';
                        other_info = '<div class="dropdown"><i class="fa fa-ellipsis-h dropdown-toggle pull-right" data-toggle="dropdown" aria-expanded="true"></i> <ul class="dropdown-menu info-dropdown-new"><li>' + info + '</li><li>' + InorRef + '</li><li>' + refund_print + '</li></ul></div>';


                        row_data = row_data + "<tr><td>" + emp.RowNo + "</td><td class='tbl-name'>" + '<a data-toggle="modal" style="cursor: pointer;" data-target="#patientdetailsmodel" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.PatientName + '\",\"' + emp.phone_number_1 + '\",\"' + emp.Due_Status + '\",this)\'>' + emp.PatientName + "</a></td><td>" + emp.billing_code + "</td><td>" + emp.billing_refund_code + "</td><td>" + emp.billing_refund_type + "</td><td>" + emp.refund_type + "</td><td>" + channel + "</td><td>" + emp.refund_mode + "</td><td>" + emp.voucher_code + "</td><td><span class='rup-sym'>&#8377</span><span class='tbl-price'>" + emp.refund_amount + "</span></td><td>" + emp.VisitName + "</td><td>" + emp.refund_date + "</td><td>" + RefundStatus + "</td><td>" + other_info + "</td></tr>";
                        //tr.append(row_data);
                    });
                   // tr.append("</tbody></table>");
                    $('#refund_view_body').append(row_data);
                    if ($('#hdnBill').val() != null && $('#hdnBill').val() != 0) {
                        $('#bill_refund_' + $('#hdnBill').val()).click();
                    }
                    datatable('tblrefund', 'Bill_Refund', 'Legal');
                   
                    //var table = $('#tblrefund').DataTable({

                    //});
                    //$('a.toggle-vis').on('click', function (e) {
                    //    e.preventDefault();

                    //    var column = table.column($(this).attr('data-column'));
                    //    column.visible(!column.visible());
                    //});
                }
                else {
                    console.log(data);
                }

            }
        },
        error: function (data) {

        }
    });

}
//
function RefundBill() {
    if ($('#hdnBill').val() != null && $('#hdnBill').val() != 0) {
        window.location.href = '/BillingMaster/refund_view';
    }
    else {
        ShowRefund()
    }
}
//filter function

function ShowRefundfilter() {
    debugger;
    $('#shade_slot').show();

    var from_date = '', to_date = ''
    if ($('#txtfrom_date').val() != '' && $('#txtto_date').val() != '') {
        from_date = $('#txtfrom_date').val();
        to_date = $('#txtto_date').val();
        from_date = from_date.split('/');
        from_date = from_date[2] + "-" + from_date[1] + "-" + from_date[0];
        to_date = to_date.split('/');
        to_date = to_date[2] + "-" + to_date[1] + "-" + to_date[0];
    }


    var RefundTbldata = {

        Dml_Indicator: 'RVA',
        branch_id: $('#ldabranch_id').val(),
        billing_no: $('#RF_bill_number').val(),
        refund_no: $('#RF_refund_number').val(),
        billing_type: $('#RF_visit_type').val() == "" || $('#RF_visit_type').val() == null ? 0 : $('#RF_visit_type').val(),
        billing_refund_type: $('#RF_refund_type').val(),
        refund_mode: $('#RF_refund_mode').val(),
        status: $('#RF_status').val(),
        from_date: from_date,
        to_date: to_date

    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/Refund_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RefundTbldata),
        success: function (data) {
            $('#refund_view_body').empty();
            var data2 = JSON.parse(data);
            $('#shade_slot').hide();
            if (jQuery.isEmptyObject(data)) {
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var row_data = "";


                    //tr = $('<table id="example1" class="table table-bordered dt-responsive" />');


                    //tr.append("<thead><tr><th>S.No</th><th>Patient Name</th><th>Bill Code</th><th>Refund Code</th><th>Billing Refund Type</th><th>Refund Type</th><th>Refund Mode</th><th>Vocher Code</th><th>Refund Amount</th><th>Visit Type</th><th>Status</th><th>Action</th></tr></thead><tbody>");

                    $('#tblrefund').dataTable().fnClearTable();
                    $('#tblrefund').dataTable().fnDraw();
                    $('#tblrefund').dataTable().fnDestroy();

                    $.each(data1.Table, function (i, emp) {

                        var RefundStatus = '';
                        var InorRef = '';
                        var channel = '';
                        var refund_print = '';

                        if (emp.billing_channel == 2) {
                            channel = 'Mobile channel';

                        }
                        else {
                            channel = 'Web channel';
                        }


                        if (emp.refund_status == 1) {
                            RefundStatus = '<span class="label label-warning">Pending Approval</span>';
                            InorRef = '<a title="Initiate" data-toggle="modal" data-target="#details_popup" href="#" data-id="RF_F1" data-type="role_rights_function" data-nav="popup" data-name="add_refund_details" onclick=Refund_Initiate(this,"' + emp.billing_no + '","' + emp.patient_id + '","' + emp.visit_type + '","' + emp.branch_id + '","' + emp.visit_report_id + '","' + emp.billing_refundid + '")>Initiate</a>';
                        }
                        else if (emp.billing_type == 2 && emp.refund_status == 3) {
                            RefundStatus = '<span class="label label-danger">Requested</span>';
                            InorRef = '<a title="Initiate"  class="btn_r" data-id="RF_F1" data-type="role_rights_function" data-nav="redirect" data-name="/BillingMaster/refund?Patient_Id=' + emp.patient_id + "&Work_order_detailsid=" + emp.work_order_detailsid + "&Billcode=" + emp.billing_no + "&refund_code=" + emp.billing_refund_code + "&billing_type=" + emp.billing_type + "&Branch_id=" + emp.branch_id + '">Refund</a>';
                        }
                            //else if(emp.billing_type == 2 && emp.refund_status == 1)
                            //{
                            //    RefundStatus = '<button type="button" class="btn btn-warning btn-xs">Pending Approval</button>';
                            //    InorRef = '<a data-toggle="modal" data-target="#details_popup" type="button" href="#" class="btn btn-primaryuse btn-xs" data-id="RF_F1" data-type="role_rights_function" data-nav="popup" data-name="add_refund_details" onclick=Refund_Initiate(this,"' + emp.billing_no + '","' + emp.patient_id + '","' + emp.visit_type + '","' + emp.branch_id + '","' + emp.visit_report_id + '","' + emp.billing_refundid + '")>Initiate</a>';
                            //}
                        else if (emp.refund_status == 2) {
                            RefundStatus = '<span class="label label-success">Completed</span>';
                            InorRef = "";
                            refund_print = '<a  class="" onclick=refund_print(' + emp.billing_no + ',' + emp.patientid + ',' + emp.hospitalid + ',' + emp.branch_id + ')> Print </a>';
                        }
                        else {

                        }



                        //Details = '<a data-toggle="modal" data-target="#details_popup" type="button" href="#" class="btn btn-info btn-xs" data-id="RF_F1" data-type="role_rights_function" data-nav="popup" data-name="add_refund_details" onclick=RefundDetails(this,"' + emp.billing_no + '","' + emp.patient_id + '","' + emp.visit_type + '","' + emp.branch_id + '","' + emp.visit_report_id + '");>Details</a>';
                        info = '<a data-placement="bottom" title="View" data-toggle="modal"  onclick=RefundInfo("' + emp.billing_refundid + '","' + emp.patient_id + '","' + emp.visit_type + '","' + emp.branch_id + '","' + emp.visit_report_id + '");><input type="hidden" id="RR_' + emp.billing_refundid + '" value="' + emp.refund_reason + '"/>View</a>';
                        other_info = '<div class="dropdown"><i class="fa fa-ellipsis-h dropdown-toggle pull-right" data-toggle="dropdown" aria-expanded="true"></i> <ul class="dropdown-menu info-dropdown-new"><li>' + info + '</li><li>' + InorRef + '</li><li>' + refund_print + '</li></ul></div>';


                        row_data = row_data + "<tr><td>" + emp.RowNo + "</td><td class='tbl-name'>" + '<a data-toggle="modal" style="cursor: pointer;" data-target="#patientdetailsmodel" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.PatientName + '\",\"' + emp.phone_number_1 + '\",\"' + emp.Due_Status + '\",this)\'>' + emp.PatientName + "<a></td><td>" + emp.billing_code + "</td><td>" + emp.billing_refund_code + "</td><td>" + emp.billing_refund_type + "</td><td>" + emp.refund_type + "</td><td>" + channel + "</td><td>" + emp.refund_mode + "</td><td>" + emp.voucher_code + "</td><td><span class='rup-sym'>&#8377</span><span class='tbl-price'>" + emp.refund_amount + "</span></td><td>" + emp.VisitName + "</td><td>" + emp.refund_date + "</td><td>" + RefundStatus + "</td><td>" + other_info + "</td></tr>";
                        //tr.append(row_data);
                    });
                    // tr.append("</tbody></table>");
                    $('#refund_view_body').append(row_data);
                    datatable('tblrefund', 'Bill_Refund', 'Legal');
                    //var table = $('#tblrefund').DataTable({

                    //});
                    $('a.toggle-vis').on('click', function (e) {
                        e.preventDefault();

                        var column = table.column($(this).attr('data-column'));
                        column.visible(!column.visible());
                    });
                }
                else {
                    console.log(data);
                }

            }
        },
        error: function (data) {

        }
    });

}

//added by nandhini on 03/08/2022 for refund payment print

function refund_print(bill_no, patientid, hospitalid, branch_id) {
    debugger;
    var load_data = {
        formid: "17",
        branchid: branch_id,
        hospitalid: hospitalid,
        patientid: patientid,
        billno: bill_no

    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_data),
        success: function (data) {
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            //window.open(link, '_blank');
            iframe = document.createElement('iframe'); //load content in an iframe to print later
            document.body.appendChild(iframe);

            iframe.style.display = 'none';
            iframe.src = link;
            iframe.onload = function () {
                setTimeout(function () {
                    iframe.focus();
                    iframe.contentWindow.print();
                }, 1);
            };
        }
    });

}

// Refund Information click function //
function RefundInfo(id, patient_id, type, branch_id, visit_id) {

    $('#refundinfo_popup').modal('show');
    PatientSearch(patient_id, type, branch_id, visit_id);
   // bank_details_patient(patient_id);
    debugger;
    var Refund_Reason = $('#RR_' + id).val();
    $('#txtReasonforrefunds').val(Refund_Reason);

    

    var RefundDetailsdata = {

        Dml_Indicator: 'RSD',
        billing_refundid: id
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/Refund_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RefundDetailsdata),
        success: function (data) {

            $('#RDetailstbl').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject(data)) {

            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    debugger;

                    tr = $('<table class="table table-bordered table-hover dt-responsive" />');

                    if (data1.Table[0].billing_refund_type == 1)
                    {
                        $('#SP_refund_type').html('Refund Service Details');
                        tr.append("<thead><tr><th>Service Name</th><th>Service Quantity</th><th>Total Service Amount</th><th>Refund Service Quantity</th><th>Refund Service Amount</th></tr></thead><tbody>");


                        $.each(data1.Table, function (i, emp) {

                            row_data = "<tr><td>" + emp.service_name + "</td><td>" + emp.service_quantity + "</td><td>" + emp.amount + "</td><td>" + emp.refund_quantity + "</td><td>" + emp.refund_amount + "</td></tr>";
                            tr.append(row_data);

                        });
                    }
                    else {
                        $('#SP_refund_type').html('Billing Repaid Refund');
                        tr.append("<thead><tr><th>Refund Amount</th></tr></thead><tbody>");

                        row_data = "<tr><td>" + data1.Table[0].mbr_refund_amount + "</td></tr>";
                            tr.append(row_data);

                    }
                    
                    tr.append("</tbody></table>");
                    $('#RDetailstbl').html(tr);
                    bank_details_patient(patient_id);


                }
                else {
                    console.log(data);
                }

            }
        },
        error: function (data) {

        }
    });

}

function Refund_Initiate(event, billno, patient_id, type, branch_id, visit_id,billing_refundid ) {
    debugger;
    $('#hdnrefundid').val(billing_refundid);

    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    debugger;
    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
     .then(function (data) {
         var data1 = JSON.parse(data);
         if (data1.msg == "Success") {
             var data1 = data1.data;
             if (jQuery.isEmptyObject((data1))) {
             }
             else {
                 var j = 0;
                 var status = data1.Table[0].role_rights_add
                 if (status == 0) {

                     return;
                 }
                 else {

                     $('#HdnPatiend_id').val(patient_id);

                     PatientSearch(patient_id, type, branch_id, visit_id);
                     Patient_BankDetails(patient_id);

                     var RefundDetailsdata = {

                         Dml_Indicator: 'RBD',
                         billing_no: billno
                     }

                     $.ajax({
                         async: true,
                         type: 'POST',
                         url: '/BillingMaster/Refund_Ins_Upd_sel',
                         contentType: 'application/json; charset=UTF-8',
                         data: JSON.stringify(RefundDetailsdata),
                         success: function (data) {
                             var data2 = JSON.parse(data);
                             if (jQuery.isEmptyObject(data)) {

                             }
                             else {

                                 if (data2.msg == "Success") {
                                     var data1 = data2.data;


                                     tr = $('<table class="table table-bordered table-hover dt-responsive" />');


                                     tr.append("<thead><tr><th>S.No</th><th>Service Name</th><th>Quantity</th><th>Unit Rate</th><th>Discount</th><th>Total Amt</th></tr></thead><tbody>");


                                     $.each(data1.Table, function (i, emp) {

                                         row_data = "<tr><td>" + emp.RowNo + "</td><td>" + emp.service_name + "</td><td>" + emp.service_quantity + "</td><td>" + emp.service_quantity_amount + "</td><td>" + emp.discount + "</td><td>" + emp.amount + "</td></tr>";
                                         tr.append(row_data);
                                     });
                                     tr.append("</tbody></table>");
                                     $('#TblBillingDetails').html(tr);

                                     $.each(data1.Table1, function (i, emp) {
                                         $('#PaymentMode').html(emp.PaymentMode);
                                         $('#ReceivedAmt').html(emp.received_amount);
                                         $('#TotalAmt').html(emp.total_amount);
                                         $('#RefundAmt').html(emp.refund_amount);
                                         //$('#totalpaid').html(emp.received_amount);
                                     });


                                 }
                                 else {
                                     console.log(data);
                                 }

                             }
                         },
                         error: function (data) {

                         }
                     });
                 }
             }
         }
     });
}

$('#Btn_Initiate').click(function () {

    //if ($('#PatientBanktbl >tbody >tr').length <= 0) {

    //    toastr.warning('Please Enter Patient Bank Details..',
    //                   {
    //                       //closeButton: false,
    //                       progressBar: true,
    //                       allowHtml: true,
    //                       timeOut: 0,
    //                   });
    //    return false;
    //}

    var RefundDetailsdata = {

        Dml_Indicator: 'RIN',
        billing_refundid: $('#hdnrefundid').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/Refund_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RefundDetailsdata),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject(data)) {

            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;


                    toastr.success('Refund Initiated Successfully',
                        {
                            //closeButton: false,
                            progressBar: true,
                            allowHtml: true,
                            timeOut: 0,
                        });
                    $('#details_popup').modal('toggle');
                    setTimeout(function () {
                        RefundBill();
                        }, 3000);
                    
                   

                }
                else {
                    console.log(data);
                }

            }
        },
        error: function (data) {

        }
    });
});

function RefundDetails(event,billno, patient_id, type, branch_id, visit_id) {


    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    debugger;
    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
     .then(function (data) {
         var data1 = JSON.parse(data);
         if (data1.msg == "Success") {
             var data1 = data1.data;
             if (jQuery.isEmptyObject((data1))) {
             }
             else {
                 var j = 0;
                 var status = data1.Table[0].role_rights_add
                 if (status == 0) {

                     return;
                 }
                 else {
                     $('#HdnPatiend_id').val(patient_id);

                     PatientSearch(patient_id, type, branch_id, visit_id);
                     Patient_BankDetails(patient_id);

                     var RefundDetailsdata = {

                         Dml_Indicator: 'RBD',
                         billing_no: billno
                     }

                     $.ajax({
                         async: true,
                         type: 'POST',
                         url: '/BillingMaster/Refund_Ins_Upd_sel',
                         contentType: 'application/json; charset=UTF-8',
                         data: JSON.stringify(RefundDetailsdata),
                         success: function (data) {
                             var data2 = JSON.parse(data);
                             if (jQuery.isEmptyObject(data)) {

                             }
                             else {

                                 if (data2.msg == "Success") {
                                     var data1 = data2.data;


                                     tr = $('<table class="table table-bordered table-hover dt-responsive" />');


                                     tr.append("<thead><tr><th>S.No</th><th>Service Name</th><th>Quantity</th><th>Unit Rate</th><th>Discount</th><th>Total Amt</th></tr></thead><tbody>");


                                     $.each(data1.Table, function (i, emp) {

                                         row_data = "<tr><td>" + emp.RowNo + "</td><td>" + emp.service_name + "</td><td>" + emp.service_quantity + "</td><td>" + emp.service_quantity_amount + "</td><td>" + emp.discount + "</td><td>" + emp.amount + "</td></tr>";
                                         tr.append(row_data);
                                     });
                                     tr.append("</tbody></table>");
                                     $('#TblBillingDetails').html(tr);

                                     $.each(data1.Table1, function (i, emp) {
                                         $('#PaymentMode').html(emp.PaymentMode);
                                         $('#ReceivedAmt').html(emp.received_amount);
                                         //$('#totalpaid').html(emp.received_amount);
                                     });


                                 }
                                 else {
                                     console.log(data);
                                 }

                             }
                         },
                         error: function (data) {

                         }
                     });
                 }
             }
         }
     });
}

function Patient_BankDetails(patient_id)
    
{
    debugger;
    var RefundDetailsdata = {

        Dml_Indicator: 'PBD',
        patient_id: patient_id
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/Refund_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RefundDetailsdata),
        success: function (data) {
            $('#BtnBank_Submit').show();
            $('#Banktbl').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject(data)) {

            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;


                    tr = $('<table class="table table-bordered table-hover dt-responsive" id="PatientBanktbl" />');


                    tr.append("<thead><tr><th>Account Holder Name</th><th>Account No</th><th>Transaction ID</th><th>Bank Name</th><th>Branch</th><th>Phone No</th><th>Uploaded File</th></tr></thead><tbody>");


                    $.each(data1.Table, function (i, emp) {

                        row_data = '<tr><td>' + emp.account_holder_name + '</td><td>' + emp.account_no + '</td><td>'+ emp.transaction_id + '</td><td>' + emp.bank_name + '</td><td>' + emp.branch + '</td><td>' + emp.patient_phoneno + '</td><td><a href="' + $('#hdnBankfilepath1').val() + $('#HospitalId').val() + "/Patient_BankDetails/" + emp.bank_fileupload + '"target="_blank"><i class="fa fa-eye" aria-hidden="true"></i></a></td></tr>';
                        tr.append(row_data);

                        $('#BtnBank_Submit').hide();
                    });
                    tr.append("</tbody></table>");
                    $('#Banktbl').html(tr);
                    


                }
                else {
                    console.log(data);
                }

            }
        },
        error: function (data) {

        }
    });
}

$('#BtnBank_Submit').click(function () {
    debugger;
    if ($.trim($('#txtAccountHolderName').val()) == "") {
        $('#PtxtAccountHolderName').show();
        $('#PtxtAccountHolderName').fadeOut(8000);
        $('#PtxtAccountHolderName').html('Enter Account Holder Name');
        $('#txtAccountHolderName').focus();
        $('#txtAccountHolderName').val('');
        return false;
    }

    //if ($.trim($('#txtAccountNo').val()) == "") {
    //    $('#PtxtAccountNo').show();
    //    $('#PtxtAccountNo').fadeOut(8000);
    //    $('#PtxtAccountNo').html('Enter Account No');
    //    $('#txtAccountNo').focus();
    //    $('#txtAccountNo').val('');
    //    return false;
    //}

    //if ($.trim($('#txtIFSCNo').val()) == "") {
    //    $('#PtxtIFSCNo').show();
    //    $('#PtxtIFSCNo').fadeOut(8000);
    //    $('#PtxtIFSCNo').html('Enter IFSC No');
    //    $('#txtIFSCNo').focus();
    //    $('#txtIFSCNo').val('');
    //    return false;
    //}

    if ($.trim($('#txtBankName').val()) == "") {
        $('#PtxtBankName').show();
        $('#PtxtBankName').fadeOut(8000);
        $('#PtxtBankName').html('Enter Bank Name');
        $('#txtBankName').focus();
        $('#txtBankName').val('');
        return false;
    }
    if ($.trim($('#txtBranch').val()) == "") {
        $('#PtxtBranch').show();
        $('#PtxtBranch').fadeOut(8000);
        $('#PtxtBranch').html('Enter Branch');
        $('#txtBranch').focus();
        $('#txtBranch').val('');
        return false;
    }

    if ($.trim($('#txttransaction').val()) == "") {
        $('#Ptxttransaction').show();
        $('#Ptxttransaction').fadeOut(8000);
        $('#Ptxttransaction').html('Enter Transaction ID');
        $('#txttransaction').focus();
        $('#txttransaction').val('');
        return false;
    }

    if ($.trim($('#txtPhoneNo').val()) != "") {
        if ($('#txtPhoneNo').val().length < 10)
        {
            $('#PtxtPhoneNo').show();
            $('#PtxtPhoneNo').fadeOut(8000);
            $('#PtxtPhoneNo').html('Please Check Phone Number');
            $('#txtPhoneNo').focus();
            //$('#txtPhoneNo').val('');
            return false;
        }
    }


    var Bankdata = {
        Dml_Indicator: "BNK_I",
        account_holder_name: $('#txtAccountHolderName').val(),
        account_no: $('#txtAccountNo').val(),
        ifsc_No: $('#txtIFSCNo').val(),
        bank_name: $('#txtBankName').val(),
        bank_branch: $('#txtBranch').val(),
        bank_fileupload: $('#idpathvalue').val(),
        patient_id: $('#HdnPatiend_id').val(),
        patient_phoneno: $('#txtPhoneNo').val(),
        transaction_id: $('#txttransaction').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/Refund_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Bankdata),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    $.each(data1, function (i, emp) {

                            toastr.success('Bank Details Added Successfully',
                            {
                                //closeButton: false,
                                progressBar: true,
                                allowHtml: true,
                                timeOut: 0,
                            });
                       
                            Patient_BankDetails($('#HdnPatiend_id').val());
                            $('#txtAccountHolderName').val('');
                            $('#txtAccountNo').val('');
                            $('#txtIFSCNo').val('');
                            $('#txtBankName').val('');
                            $('#txttransaction').val('');
                            $('#txtBranch').val('');
                            $('#idpathvalue').val('');
                            $('#fileToUpload').val('');
                            $('#photolog').hide();
                            $('#photolog').empty();
                            $('#HdnPatiend_id').val('');

                    });
                }
                else {
                    console.log(data);
                }
            }
        }
    });

});

$('#fileToUpload').change(function () {
    debugger;
    Bankfileupload();
});

function Bankfileupload() {
    debugger;
    var uploadpath = $('#fileToUpload').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);
    if (window.FormData !== undefined) {
        var fileUpload = $("#fileToUpload").get(0);
        var files = fileUpload.files;
        var fileData = new FormData();
        for (var i = 0; i < files.length; i++) {
            fileData.append(files[i].name, files[i]);
        }
        fileData.append('username', 'Manas');
        $.ajax({
            url: '/BillingMaster/UploadPatientBankFiles',
            type: "POST",
            contentType: false,
            processData: false,
            data: fileData,
            success: function (result) {
                $.each(result, function (i, emp) {
                    debugger;
                    $('#photolog').empty();
                    $('#photolog').show();
                    $('#idpathvalue').val(emp);
                    $('#photolog').append('<a href="' + $('#hdnBankfilepath1').val() + $('#HospitalId').val() + "/Patient_BankDetails/" + emp + '" target="_blank">Bank</a>');
                });
            }
        });
    }
}

//Load visit type
function LoadVisitType() {
    var DoctorData = {
        dml_indicator: 'LVT',
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data2 = JSON.parse(data);
            $('#RF_visit_type').empty();
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                debugger;
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var option = "";
                    var default_option = "<option value='0'>--Select--</option>";
                    $.each(data1.Table, function (i, emp) {
                        option = option + "<option value=" + emp.visit_typeid + " >" + emp.visit_type_name + "</option>"
                    })
                    $('#RF_visit_type').append(default_option + option);
                }
            }
        }
    });
}


function bank_details_patient(patient_id) {
    debugger;
    var RefundDetailsdata = {

        Dml_Indicator: 'PBD',
        patient_id: patient_id
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/BillingMaster/Refund_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RefundDetailsdata),
        success: function (data) {
            // $('#BtnBank_Submit').show();
            $('#bank_details_body').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject(data)) {

            }
            else {



                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var tr = '';
                    var row_data = '';
                    // tr = $('<table class="table table-bordered table-hover dt-responsive" id="patient_bank_details" />');


                    //  tr.append("<thead><tr><th>Account Holder Name</th><th>Account No</th><th>Transaction ID</th><th>Bank Name</th><th>Branch</th><th>Phone No</th><th>Uploaded File</th></tr></thead><tbody>");


                    $.each(data1.Table, function (i, emp) {

                        row_data = row_data + "<tr><td>" + emp.account_holder_name + "</td><td>" + emp.account_no + "</td><td>" + emp.transaction_id + "</td><td>" + emp.bank_name + "</td><td>" + emp.branch + "</td><td>" + emp.patient_phoneno + '</td><td><a href="' + $('#hdnBankfilepath1').val() + $('#HospitalId').val() + "/Patient_BankDetails/" + emp.bank_fileupload + '"target="_blank"><i class="fa fa-eye" aria-hidden="true"></i></a></td></tr>';
                      //  tr.append(row_data);

                        // $('#BtnBank_Submit').hide();
                    });
                    //  tr.append("</tbody></table>");
                    $('#bank_details_body').html(row_data);



                }
                else {
                    console.log(data);
                }

            }
        },
        error: function (data) {

        }
    });
}