
$(document).ready(function () {
    LoadBranch();
    debugger;
    ShowEstimation();
});

function LoadBranch() {
    document.getElementById("Tblbranch_id").innerHTML = null;

    //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) {
            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) {
                        $('#Tblbranch_id').append(SubDepartment);
                    }
                    else {
                        if ($('#hiddenRole_id').val() == 1) {
                            $('#Tblbranch_id').append(SubDepartment);
                        }
                        else {
                            $('#Tblbranch_id').append(default_opt + SubDepartment);
                        }
                        
                    }

                    //if ($('#hiddenRole_id').val() == 1) {
                    //    $('#Tblbranch_id').val($('#HospitalBranchID').val());
                    //}
                    //else 
                    if ($('#hiddenRole_id').val() != 2) {
                        $('#Tblbranch_id').val($('#HospitalBranchID').val());
                        $('#Tblbranch_id').attr('disabled', true);
                    }
                    LoadWardCategory();
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

var from_date='',to_date ='' ;
$('#btn_filter').click(function () {
     from_date = $('#txtfrom_date').val();
     to_date = $('#txtto_date').val();
    if (from_date != "") {
        if (to_date == "") {
            $('#Ptxtto_date').show();
            $('#Ptxtto_date').fadeOut(8000);
            $('#Ptxtto_date').html('Please Select The To Date');
            $('#txtto_date').focus();
            $('#txtto_date').val('');
            return false;
        }
    }
    
    if (from_date != "")
    {
        from_date = from_date.split('/');
        from_date = from_date[2] + "-" + from_date[1] + "-" + from_date[0];
    }
    if (to_date != "")
    {
        to_date = to_date.split('/');
        to_date = to_date[2] + "-" + to_date[1] + "-" + to_date[0];
    }
    
    

    ShowEstimation()
});

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

    if (from_date == null || from_date == "")
    {

       from_date = "";
    }
    if (to_date == null || to_date == "") {

        to_date = "";
    }

    if ($('#ftype').val() == '' || $('#ftype').val() == null) {

        $('#ftype').val(0)
    }
    else{
        $('#ftype').val()
    }
    if ($('#Tblbranch_id').val() == 0) {
        var indicator='ESA'
    }
    else {
        indicator = 'ESS'
    }
    var RefundTbldata = {

        Dml_Indicator: indicator,
        branch_id: $('#Tblbranch_id').val(),
        Patient_Name: $('#estm_patient_name').val(),
        patient_id: $('#estm_patient_id').val(),
        insurance: $('#ftype').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) {
            debugger;
            $('#tblEstimation_body').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject(data)) {

            }
            else {
                $('#tblEstimation').DataTable().destroy();
                $('#shade_slot').hide();
                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    var row_data = '';
                    $.each(data1.Table, function (i, emp) {

                        
                        view = '<a title="Edit" class="edit_icon btn_r" data-id="EST_E1" data-type="role_rights_edit" data-nav="redirect" data-name="/BillingMaster/estimation?Patient_Id=' + emp.patient_id + "&visittype=" + emp.visit_type + "&Estimation_id=" + emp.estimation_no + "&Branch_id=" + emp.branch_id + '"><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                        Del = '<a title="Delete" class="delete_icon" data-id="EST_D1" data-type="role_rights_delete" data-nav="sp_div" data-name="delete_Estimation_form" onclick=DELestimation(this,"' + emp.estimation_no + '");><i class="fa fa-trash-o" aria-hidden="true"></i></a>';
                        Details = '<a title="Details"  data-id="EST_F1" data-type="role_rights_function" data-nav="popup" data-name="function_Estimation_form" onclick=EstDetails(this,"' + emp.estimation_no + '");>Details</a>';
                        preview = '<a title="View" data-id="EST_F1" data-type="role_rights_function" data-nav="popup" data-name="function_Estimation_form" onclick=estimation_preview(this,' + emp.estimation_no + ',' + emp.patientid + ',' + emp.hospitalid + ',' + emp.branch_id + ')>View</a>'
                        print = '<a title="Prinrt" onclick=estimation_report(' + emp.estimation_no + ',' + emp.patientid + ',' + emp.hospitalid + ',' + emp.branch_id + ')>Print</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"><div class="disp_if mb-10"><li>' + view + '</li><li>' + Del + '</li></div><li>' + Details + '</li><li>' + preview + '</li><li>' + print + '</li></ul></div>';

                        row_data = row_data + "<tr><td>" + (i + 1) + "</td><td>" + emp.estimation_code + "</td><td>" + emp.branch_name + "</td><td>" + emp.visit_Name + "</td><td class='tbl-name'>" + emp.PatientName + "</td><td class='tbl-price'><span class='rup-sym'>&#8377</span>" + emp.total_net_amount + "</td><td class='tbl-price'><span class='rup-sym'>&#8377</span>" + emp.total_discount_amount + "</td><td>" + other_info + "</td></tr>";

                    });
                    $('#tblEstimation_body').html(row_data);
                   // $('#tblEstimation').DataTable();
                    datatable('tblEstimation', 'Table_Estimation', 'Legal');

                }

                else {
                    console.log(data);
                }
            }
        },
        error: function (data) {

        }

    });
    


}

function estimation_preview(event, estimationno, patientid, hospitalid, branch_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 {
                     var load_data = {
                         indicator_id: "LRD",
                         ReportId: '64'
                     }
                     $.ajax({
                         async: true,
                         type: 'POST',
                         url: '/reports/Hospital_Reports',
                         contentType: 'application/json; charset=UTF-8',
                         data: JSON.stringify(load_data),
                         success: function (data) {
                             var data1 = JSON.parse(data);
                             if (data1.msg == "Success") {
                                 data1 = data1.data;
                                 if (jQuery.isEmptyObject((data1))) {
                                 }
                                 else {
                                     debugger;
                                     var ReportName = ''; var reportparameters = "";
                                     if (data1.Table[0] != null) {
                                         ReportName = data1.Table[0].report_form_name;
                                         var dml_indicator = data1.Table[0].dml_indicator;
                                         reportparameters = data1.Table[0].report_parameters_list;

                                         $('#iframeHeader').html(ReportName);


                                         var load_data = {
                                             dmlind: dml_indicator,
                                             report_name: ReportName,
                                             branchid: branch_id,
                                             hospitalid: hospitalid,
                                             patientid: patientid,
                                             Estimationno: estimationno,
                                             reportparameters: reportparameters

                                         }
                                         $.ajax({
                                             async: true,
                                             type: 'POST',
                                             url: '/reports/SetReportParameters',
                                             contentType: 'application/json; charset=UTF-8',
                                             data: JSON.stringify(load_data),
                                             success: function (data) {
                                                 $('#iframepopup').modal('toggle');
                                                 $('#dvReport').html('<iframe src="/Webform/WebForm1.aspx" id="dvLoadingReport" style="width: 100%;min-height: 450px; max-height: 450px; overflow: auto;"></iframe>');
                                             }
                                         });
                                     }
                                 }
                             }
                             else {
                                 console.log(data2);
                             }
                         }
                     });
                 }
             }
         }
     });

   
}


function estimation_report(estimationno, patientid, hospitalid, branch_id) {
    debugger;     

    var load_data = {
        formid: '64',
        branchid: branch_id,
        hospitalid: hospitalid,
        patientid: patientid,
        Estimationno: estimationno

    }

    $.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);
            };
        }
    });

}


function DELestimation(event,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 {
                     var r = confirm("Are You Sure You Want to delete?");
                     if (r == true) {

                         var SCDTbldata = {

                             Dml_Indicator: 'ESDEL',
                             billing_no: id
                         }

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

                                 }
                                 else {

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

                                         toastr.success('Deleted Successfully');
                                         ShowEstimation();

                                     }
                                     else {
                                         console.log(data);
                                     }

                                 }
                             },
                             error: function (data) {

                             }
                         });

                     } else {

                     }
                 }
             }
         }
     });

   
}

$('#Est_clear').click(function () {
    debugger;
    $('#Tblbranch_id').val(0);
    $('#estm_patient_name').val('');
    $('#txtfrom_date').val('');
    $('#ftype').val('');
    $('#txtto_date').val('');
    $('#estm_patient_id').val('');
    LoadBranch();
    ShowEstimation();

});

function EstDetails(event,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 {
                     $('#EstDetails_popup').modal('show');

                     var RefundTbldata = {

                         Dml_Indicator: 'ESTDS',
                         billing_no: id
                     }

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

                             }
                             else {

                                 if (data2.msg == "Success") {

                                     var data1 = data2.data;

                                     var discount_type = '';
                                     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><th>Discount Amt</th><th>Total Net Amt</th></tr></thead><tbody>");



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

                                         if (emp.discount_type == 1) {
                                             discount_type = '₹';
                                         }
                                         else {
                                             discount_type = '%';
                                         }

                                         row_data = "<tr><td>" + (i + 1) + "</td><td>" + emp.service_name + "</td><td>" + emp.service_quantity + "</td><td>" + emp.service_quantity_amount + "</td><td>" + emp.discount + " " + discount_type + "</td><td>" + emp.amount + "</td><td>" + emp.discount_amount + "</td><td>" + emp.net_amount + "</td></tr>";
                                         tr.append(row_data);
                                     });
                                     tr.append("</tbody></table>");
                                     $('#tblEstDetails').html(tr);
                                 }
                                 else {
                                     console.log(data);
                                 }

                             }
                         },
                         error: function (data) {

                         }
                     });
                 }
             }
         }
     });

    
}