//Billing Dashboard
$(document).ready(function () {
    card_count();
    table_request_view();
    table_receipt_view();
    billing_list();
    ShowRefund();
})
//Dashboard Card Count
function card_count() {
    var indicator_id = '';
    var branch_id = ($('#HospitalBranchID').val() == '') ? 0 : $('#HospitalBranchID').val();
    var request_data = {
        Dml_Indicator: 'DC',
        branch_id: branch_id,
        hospital_id: $('#HospitalId').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Billing_Dashboard',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                //var data1 = data1.data.Table;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    $('#opreq_count').html(data1.data.Table[0].op_count);
                    $('#ipreq_count').html(data1.data.Table1[0].ip_count);
                    $('#bill_count').html(data1.data.Table2[0].bill);
                    $('#total_amount_count').html('&#8377;' + data1.data.Table2[0].total_amount);
                    $('#total_received_count').html('&#8377;' + data1.data.Table2[0].received_amount);
                    $('#total_due_count').html('&#8377;' + data1.data.Table2[0].due_amount);
                    $('#total_discount_count').html('&#8377;' + data1.data.Table2[0].discount_amount);
                    $('#total_advance_count').html('&#8377;' + data1.data.Table3[0].advance_amount);
                    $('#total_refund_count').html('&#8377;' + data1.data.Table2[0].refund_amount);
                }
            }
        }
    })
}

//Loading Request View Table 
function table_request_view() {
    var indicator_id = '';
    if ($('#hiddenRole_id').val() == 2) {
        indicator_id = 'RV'
    }
    else {
        indicator_id = 'RVB'
    }
    var branch_id = ($('#HospitalBranchID').val() == '') ? 0 : $('#HospitalBranchID').val();
    var request_data = {
        Dml_Indicator: 'OPR',
        branch_id: branch_id,
        hospital_id: $('#HospitalId').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Billing_Dashboard',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                //var data1 = data1.data.Table;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    table_view_binding(data1);
                }
            }
        }
    })
}

//Show/hide service subtable-Request
function servicedetails1(e, id) {
    debugger;
    var tr = e.closest('tr');
    var row = $('#request_view').DataTable().row(tr);
    console.log(row);
    //var row = $('#request_view').DataTable().row(tr);

    if (row.child.isShown()) {
        // This row is already open - close it
        row.child.hide();
        tr.removeClass('shown');
    }
    else {
        // Open this row
        row.child(getservicedetails1(id)).show();
        tr.addClass('shown');
    }
}
//getting service details for subtable-Request
function getservicedetails1(id) {
    debugger;
    div = $('<div/>')
    .addClass('loading')
    .addClass('table_child')
    .addClass('table-responsive');
    var service_data = {
        request_id: id,
        Dml_Indicator: 'SD'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(service_data),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                var tr = '', j = 1;

                if (jQuery.isEmptyObject((data1))) {
                }

                else {
                    div.removeClass('loading')

                    var row = 2;
                    var tr, row_data;
                    tr = $('<table class="table table-condensed body-borderless table_borderless">');
                    tr.append('<thead><tr><th>S.No</th><th>Service Code</th><th>Service Name</th><th>Number of Usage</th><th>Status</th></tr></thead><tbody>');
                    $.each(data1, function (i, emp) {
                        if (emp.is_bill == 1) {
                            row_data = '<tr><td>' + j + '</td><td>' + emp.service_code + '</td><td>' + emp.service_name + '</td><td>' + emp.quantity + '</td><td>Converted to bill</td></tr>';

                        }
                        else {
                            row_data = '<tr><td>' + j + '</td><td>' + emp.service_code + '</td><td>' + emp.service_name + '</td><td>' + emp.quantity + '</td><td></td></tr>';
                        }
                        j = j + 1;
                        tr.append(row_data);
                    })
                    tr.append("</tbody>");

                    div.append(tr);

                }
            }
            else {
                console.log(data);
            }
        }
    });
    return div;
}
//table binding-request
function table_view_binding(data) {
    debugger;
    console.log(data);
    var data1 = data.data.Table;
    var data2 = data.data.Table1;
    $('#request_view').DataTable().destroy();
    $('#request_view tbody').empty();
    var row_data = '', j = 1;
    $.each(data1, function (i, emp) {
        
            if (emp.convert_bill == 0) {
                //row_data = row_data + '<tr id=reqv' + j + '><td>' + (j) + '</td><td>' + emp.request_code + '</td><td>' + emp.request_date + '</td><td>' + emp.patient_id + '</td><td>' + emp.first_name + '</td><td class="details-control" id=service' + j + ' onclick=servicedetails1(this,"' + emp.request_id + '");>' + emp.service_count + '<i class="fa fa-angle-double-down ml-20"></i></td><td>' + emp.visit_type + '</td><td>' + emp.visit_report_id + '</td><td> <button type="button" class="btn btn-primaryuse btn-xs " onclick=convertTobill("' + emp.request_id + '","' + emp.visit_report_id + '","' + emp.branchid + '")>Convert To Bill</button> </td></tr>'
                row_data = row_data + '<tr id=reqv' + j + '><td>' + (j) + '</td><td>' + emp.request_code + '</td><td>' + emp.request_date + '</td><td>' + emp.patient_id + '</td><td>' + emp.first_name + '</td><td class="details-control" id=service' + j + ' onclick=servicedetails1(this,"' + emp.request_id + '");>' + emp.service_count + '<i class="fa fa-angle-double-down ml-20"></i></td><td>' + emp.visit_type + '</td><td>' + emp.visit_report_id + '</td></tr>'

            }
            else {
                //row_data = row_data + '<tr id=reqv' + j + '><td>' + (j) + '</td><td>' + emp.request_code + '</td><td>' + emp.request_date + '</td><td>' + emp.patient_id + '</td><td>' + emp.first_name + '</td><td class="details-control" id=service' + j + ' onclick=servicedetails1(this,"' + emp.request_id + '");>' + emp.service_count + '<i class="fa fa-angle-double-down ml-20"></i></td><td>' + emp.visit_type + '</td><td>' + emp.visit_report_id + '</td><td>Converted to Bill</td></tr>';
                row_data = row_data + '<tr id=reqv' + j + '><td>' + (j) + '</td><td>' + emp.request_code + '</td><td>' + emp.request_date + '</td><td>' + emp.patient_id + '</td><td>' + emp.first_name + '</td><td class="details-control" id=service' + j + ' onclick=servicedetails1(this,"' + emp.request_id + '");>' + emp.service_count + '<i class="fa fa-angle-double-down ml-20"></i></td><td>' + emp.visit_type + '</td><td>' + emp.visit_report_id + '</td></tr>';

            }
        

        j = j + 1;
    })
    $.each(data2, function (i, emp) {

        if (emp.convert_bill == 0) {
            //row_data = row_data + '<tr id=reqv' + j + '><td>' + (j) + '</td><td>' + emp.request_code + '</td><td>' + emp.request_date + '</td><td>' + emp.patient_id + '</td><td>' + emp.first_name + '</td><td class="details-control" id=service' + j + ' onclick=servicedetails1(this,"' + emp.request_id + '");>' + emp.service_count + '<i class="fa fa-angle-double-down ml-20"></i></td><td>' + emp.visit_type + '</td><td>' + emp.visit_report_id + '</td><td> <button type="button" class="btn btn-primaryuse btn-xs " onclick=convertTobill("' + emp.request_id + '","' + emp.visit_report_id + '","' + emp.branchid + '")>Convert To Bill</button> </td></tr>'
            row_data = row_data + '<tr id=reqv' + j + '><td>' + (j) + '</td><td>' + emp.request_code + '</td><td>' + emp.request_date + '</td><td>' + emp.patient_id + '</td><td>' + emp.first_name + '</td><td class="details-control" id=service' + j + ' onclick=servicedetails1(this,"' + emp.request_id + '");>' + emp.service_count + '<i class="fa fa-angle-double-down ml-20"></i></td><td>' + emp.visit_type + '</td><td>' + emp.visit_report_id + '</td></tr>'

        }
        else {
            //row_data = row_data + '<tr id=reqv' + j + '><td>' + (j) + '</td><td>' + emp.request_code + '</td><td>' + emp.request_date + '</td><td>' + emp.patient_id + '</td><td>' + emp.first_name + '</td><td class="details-control" id=service' + j + ' onclick=servicedetails1(this,"' + emp.request_id + '");>' + emp.service_count + '<i class="fa fa-angle-double-down ml-20"></i></td><td>' + emp.visit_type + '</td><td>' + emp.visit_report_id + '</td><td>Converted to Bill</td></tr>';
            row_data = row_data + '<tr id=reqv' + j + '><td>' + (j) + '</td><td>' + emp.request_code + '</td><td>' + emp.request_date + '</td><td>' + emp.patient_id + '</td><td>' + emp.first_name + '</td><td class="details-control" id=service' + j + ' onclick=servicedetails1(this,"' + emp.request_id + '");>' + emp.service_count + '<i class="fa fa-angle-double-down ml-20"></i></td><td>' + emp.visit_type + '</td><td>' + emp.visit_report_id + '</td></tr>';

        }


        j = j + 1;
    })
    $('#request_view tbody').append(row_data);
    $("#request_view").dataTable({
        "searching": true
    });
    //var table = $('#request_view').DataTable();
    //$("#request_view.dataTables_filter").append($("#categoryFilter"));
    //var categoryIndex = 0;
    //$("#request_view th").each(function (i) {
    //    if ($($(this)).html() == "Visit Type") {
    //        categoryIndex = i; return false;
    //    }
    //});
    //$.fn.dataTable.ext.search.push(
    //    function (settings, data, dataIndex) {
    //        debugger;
    //        var selectedItem = $('#categoryFilter').val()
    //        var category = data[categoryIndex];
    //        if (selectedItem === "" || category.includes(selectedItem)) {
    //            return true;
    //        }
    //        return false;
    //    }
    //  );
    //$("#categoryFilter").change(function (e) {
    //    table.draw();
    //});
    //table.draw();
}
//Converting to Bill
function convertTobill(id, visitid, branchid) {
    window.location.href = "/BillingMaster/index?visit_report_id=" + visitid + "&request_id=" + id + "&branch_id=" + branchid + "";
}
//Receipt list 
function table_receipt_view() {
    var indicator_id = '';
    //if ($('#hiddenRole_id').val() == 2) {
    //    indicator_id = 'TV'
    //}
    //else {
    //    indicator_id = 'TVB'
    //}
    var branch_id = ($('#HospitalBranchID').val() == '') ? 0 : $('#HospitalBranchID').val();
    var request_data = {
        Dml_Indicator: 'TV',
        branch_id: branch_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Billing_Receipt',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data.Table;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    table_view_binding_receipt(data1);
                }
            }
        }
    })
}
//Table view binding-receipt
function table_view_binding_receipt(data1) {
    debugger;
    console.log(data1);
    $('#receipt_view').DataTable().destroy();
    $('#receipt_view tbody').empty();
    var row_data = '', j = 1, others = 0;
    $.each(data1, function (i, emp) {
        if (emp.others == "") {
            others = 0;
        }
        else {
            others = emp.others;
        }
        debugger;
        if (emp.receipt_type == 1) {
            row_data = row_data + '<tr><td id=rec_' + i + '>' + (i + 1) + '</td><td>' + emp.receipt_code + '</td><td>' + emp.receipt_date + '</td><td class="col-sm-2">' + emp.billing_code + '</td><td>' + emp.patient_name + '</td><td>' + emp.patient_id + '</td><td class="col-sm-2">' + emp.visit_report_id + '</td><td>' + emp.visit_type_name + '</td><td>' + (parseFloat(emp.amount) + parseFloat(emp.TDS) + parseFloat(emp.MOU_Discount) + parseFloat(others)) + '</td><td>' + emp.due_amount + '</td><td>' + emp.payment_mode + '</td><td class="col-sm-2">' + emp.branch_name + '</td><td>-</td><td><button type="button" class="btn btn-primaryuse btn-xs">Advance</button></td></tr>'
        }
        else if (emp.receipt_type == 2 && emp.due_amount != 0 && emp.due_amount != '-') {
            row_data = row_data + '<tr><td id=rec_' + i + '>' + (i + 1) + '</td><td>' + emp.receipt_code + '</td><td>' + emp.receipt_date + '</td><td>' + emp.billing_code + '</td><td>' + emp.patient_name + '</td><td>' + emp.patient_id + '</td><td class="col-sm-2">' + emp.visit_report_id + '</td><td>' + emp.visit_type_name + '</td><td>' + (parseFloat(emp.amount) + parseFloat(emp.TDS) + parseFloat(emp.MOU_Discount) + parseFloat(others)) + '</td><td>' + emp.due_amount + '</td><td>' + emp.payment_mode + '</td><td class="col-sm-2">' + emp.branch_name + '</td><td>'+emp.entity_name+'</td><td><button type="button" class="btn btn-warning btn-xs">Pending</button></td></tr>'
        }
        else if (emp.receipt_type == 2 || emp.due_amount == 0 || emp.due_amount == '-') {
            row_data = row_data + '<tr><td id=rec_' + i + '>' + (i + 1) + '</td><td>' + emp.receipt_code + '</td><td>' + emp.receipt_date + '</td><td>' + emp.billing_code + '</td><td>' + emp.patient_name + '</td><td>' + emp.patient_id + '</td><td class="col-sm-2">' + emp.visit_report_id + '</td><td>' + emp.visit_type_name + '</td><td>' + (parseFloat(emp.amount) + parseFloat(emp.TDS) + parseFloat(emp.MOU_Discount) + parseFloat(others)) + '</td><td>' + emp.due_amount + '</td><td>' + emp.payment_mode + '</td><td class="col-sm-2">' + emp.branch_name + '</td><td>'+emp.entity_name+'</td><td><button type="button" class="btn  btn-success btn-xs">Completed</button></td></tr>'
        }


    })
    $('#receipt_view tbody').append(row_data);
    $("#receipt_view").dataTable({
        "searching": true
    });
    //var table1 = $('#receipt_view').DataTable();
    //$("#receipt_view.dataTables_filter").append($("#categoryFilter_Receipt"));
    //var categoryIndex = 0;
    //$("#receipt_view th").each(function (i) {
    //    if ($($(this)).html() == "Status") {
    //        categoryIndex = i; return false;
    //    }
    //});
    //$.fn.dataTable.ext.search.push(
    //    function (settings, data, dataIndex) {
    //        debugger;
    //        var selectedItem = $('#categoryFilter_Receipt').val()
    //        var category = data[categoryIndex];
    //        if (selectedItem === "" || category.includes(selectedItem)) {
    //            return true;
    //        }
    //        return false;
    //    }
    //  );
    //$("#categoryFilter_Receipt").change(function (e) {
    //    table1.draw();
    //});
    //table1.draw();
}
//billing list
function billing_list() {
   
    var branch_id = ($('#HospitalBranchID').val() == '') ? 0 : $('#HospitalBranchID').val();
    var request_data = {
        Dml_Indicator: 'BV',
        branch_id: branch_id,
        hospital_id: $('#HospitalId').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Billing_Dashboard',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        success: function (data) {
            var data1 = JSON.parse(data)
            console.log(data1);
            debugger;
            $('#tbl_billing_view').empty();
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    var data1 = data1.data;
                    var row_data = "";
                    if (data1.Table.length > 0) {
                        for (var i = 0; i < data1.Table.length; i++) {
                            //row_data = row_data + '<tr id=reqv' + i + '><td>' + (i + 1) + '</td><td>' + data1.Table[i].billing_code + '</td><td>' + data1.Table[i].visit_report_id + '</td><td>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].due_amount + '</td><td>' + data1.Table[i].received_amount + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '");>' + data1.Table[i].billing_no + '<i class="fa fa-angle-double-down ml-20"></i></td><td><button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=requestedit(' + data1.Table[i].billing_no + ')><i class="fa fa-pencil-square-o" aria-hidden="true"></i></button><button type="button" class="btn btn-danger btn-xs mr-5" onclick=requestdelete(' + data1.Table[i].billing_no + ')><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>'
                            row_data = row_data + '<tr id=reqv' + i + '><td>' + (i + 1) + '</td><td>' + data1.Table[i].branch_id + '</td><td>' + data1.Table[i].billing_code + '</td><td>' + data1.Table[i].patient_id + '</td><td>' + data1.Table[i].patient_name + '</td><td>' + data1.Table[i].total_amount + '</td><td>' + data1.Table[i].due_amount + '</td><td>' + data1.Table[i].discount_type + '</td><td>' + data1.Table[i].total_discount_amount + '</td><td class="details-control" id=service' + i + ' onclick=billingdetails(this,"' + data1.Table[i].billing_no + '");>' + data1.Table[i].total_net_amount + '<i class="fa fa-angle-double-down ml-20"></i></td><td>'+data1.Table[i].entity_name+'</td></tr>'
                        }
                        $('#tbl_billing_view').html(row_data);
                        $('#tbl_billing').DataTable();
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

//Show/hide service subtable-billing
function billingdetails(e, id) {
    debugger;
    var tr = e.closest('tr');
    var row = $('#tbl_billing').DataTable().row(tr);
    console.log(row);
    //var row = $('#request_view').DataTable().row(tr);

    if (row.child.isShown()) {
        // This row is already open - close it
        row.child.hide();
        tr.removeClass('shown');
    }
    else {
        // Open this row
        row.child(getservicedetails(id)).show();
        tr.addClass('shown');
    }
}

function getservicedetails(id) {
    debugger;
    div = $('<div/>')
    .addClass('loading')
    .addClass('table_child')
    .addClass('table-responsive');
    var service_data = {
        billing_no: id,
        Dml_Indicator: 'BDV'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(service_data),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data1 = data.data;
                var tr = '', j = 1;

                if (jQuery.isEmptyObject((data1))) {
                }

                else {
                    div.removeClass('loading')

                    var row = 2;
                    var tr, row_data, j = 1;
                    tr = $('<table class="table table-condensed body-borderless table_borderless">');
                    tr.append('<thead><tr><th>S.No</th><th>Service Code</th><th>Service Name</th><th>Request Date</th><th>Doctor Name</th></tr></thead><tbody>');
                    //var data1 = data1.data;
                    if (data1.Table.length > 0) {
                        for (var i = 0; i < data1.Table.length; i++) {
                            row_data = '<tr><td>' + j + '</td><td>' + data1.Table[i].service_code + '</td><td>' + data1.Table[i].service_name + '</td><td>' + data1.Table[i].request_date + '</td><td>' + data1.Table[i].doctor_name + '</td></tr>';
                            j = j + 1;
                            tr.append(row_data);
                        }
                    }
                    tr.append("</tbody>");
                    div.append(tr);
                }
            }
            else {
                console.log(data);
            }
        }
    });
    return div;
}
//Refund List
function ShowRefund() {

    var branch_id = ($('#HospitalBranchID').val() == '') ? 0 : $('#HospitalBranchID').val();
    var request_data = {
        Dml_Indicator: 'RVS',
        branch_id: branch_id,
        hospital_id: $('#HospitalId').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Billing_Dashboard',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(request_data),
        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>Patient Name</th><th>Bill No</th><th>Refund Service</th><th>Refund Type</th><th>Refund Mode</th><th>Vocher Code</th><th>Refund Amount</th><th>Status</th><th>Action</th></tr></thead><tbody>");



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

                        var RefundStatus = '';
                        var InorRef = '';

                        if (emp.billing_channel == 1 && emp.refund_status == 1) {
                            RefundStatus = '<button type="button" class="btn btn-warning btn-xs">Pending Approval</button>';
                            InorRef = '<a type="button" class="btn btn-primaryuse btn-xs">Initiate</a>';
                        }
                        else if (emp.billing_channel == 2 && emp.refund_status == 1) {
                            RefundStatus = '<button type="button" class="btn btn-primaryuse btn-xs">Requested</button>';
                            InorRef = '<a type="button" href="/BillingMaster/refund?Patient_Id=' + emp.patient_id + "&visittype=" + emp.visit_type + "&Billcode=" + emp.billing_code + '" class="btn btn-primaryuse btn-xs">Refund</a>';
                        }
                        else if (emp.refund_status == 2) {
                            RefundStatus = '<button type="button" class="btn btn-success btn-xs">Completed</button>';
                            InorRef = "";
                        }
                        else {

                        }


                        Details = '<a data-toggle="modal" data-target="#details_popup" type="button" href="#" class="btn btn-info btn-xs" onclick=RefundDetails("' + emp.billing_no + '","' + emp.patient_id + '","' + emp.visit_type + '","' + emp.branch_id + '","' + emp.visit_report_id + '");>Details</a>';
                        info = '<a data-toggle="modal" class="btn btn-primaryuse btn-xs" onclick=RefundInfo("' + emp.billing_no + '");><input type="hidden" id="' + emp.billing_no + '" value="' + emp.refund_reason + '"/><i class="fa fa-eye" aria-hidden="true"></i></a>';


                        row_data = "<tr><td>" + emp.RowNo + "</td><td>" + emp.PatientName + "</td><td>" + emp.billing_code + "</td><td>" + emp.RefundService + "</td><td>" + emp.refund_type + "</td><td>" + emp.refund_mode + "</td><td>" + emp.voucher_code + "</td><td>" + emp.totalrefund_amount + "</td><td>" + RefundStatus + "</td></tr>";
                        $('#tblrefund tbody').append(row_data);
                    });
                    //tr.append("</tbody></table>");
                   
                    $('#tblrefund').DataTable();
                }
                else {
                    console.log(data);
                }

            }
        },
        error: function (data) {

        }
    });

}
