var billing_type = "";   //op 1, ip 2
$(document).ready(function () {
    if ($('#hdnRequestId').val()) {
        debugger
        LoadRequestDetails();
    }

    if ($('#hdnEstimationid').val() != "") {

        Estimationload();
    }
    else {
        LoadDoctor();
        if (!$('#hdnRequestId').val()) {
            LoadBranch();
            LoadVisitType();
        }
    }

});

function LoadBranch() {
    document.getElementById("pkg_branch_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) {
            debugger;
            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">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#pkg_branch_id').append(SubDepartment);
                        $('#pkg_branch_id').change();
                    }
                    else {
                        $('#pkg_branch_id').append(default_opt + SubDepartment);
                    }

                    //Only KinderSurge
                    //if ($('#hiddenRole_id').val() == 1) {
                    //    $('#pkg_branch_id').val($('#HospitalBranchID').val());

                    //    LoadDoctor();
                    //    WardNo();
                    //    Show_Billing();
                    //    authorized_person();
                    //}
                    //else 
                    if ($('#hiddenRole_id').val() != 2) {
                        $('#pkg_branch_id').val($('#HospitalBranchID').val());
                        $('#pkg_branch_id').attr('disabled', true);

                        LoadDoctor();
                        WardNo(0);
                        Show_Billing(0);
                        authorized_person();
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

$('#pkg_branch_id').change(function () {

    $('#hdnpatient_id').val('');
    $('#txtPaitentSearch_1').val('');
    $('#Insurance_type').val('');
    $('#div_InsuranceName').addClass('hide');
    $('#div_BillingName').addClass('hidden');
    $('#dd_BillingName').val('');
    $('#hdInsBilling_class').val('');
    //$('#div_InsuranceName').hide();
    $('#ddInsuranceName').val('');
    ClearClaim();
    LoadDoctor();
    WardNo(0);
    Show_Billing(0);
    authorized_person();


});

function LoadDoctor() {
    var roleId = $('#hiddenRole_id').val();
    var DoctorId = $('#HiddenDoctorID').val();
    var DoctorData = {
        Dml_Indicator: "DL",
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#pkg_branch_id').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data1 = JSON.parse(data)
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    var tr = '';
                    var SelRole = '';
                    $('#SelDoctor').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    var j = 0;
                    if (data1.data.length > 0) {
                        for (var i = 0; i < data1.data.length; i++) {
                            j++;
                            SelRole = SelRole + '<option value="' + data1.data[i].doctor_id + '">' + data1.data[i].first_name + '</option>';
                        }
                        $('#SelDoctor,.txt_doctor_name').html(default_opt + SelRole);
                    }

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

function authorized_person() {
    var DoctorData = {
        dml_indicator: 'AU',
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#pkg_branch_id').val()
    }
    $.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);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                debugger;
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var SelRole = '';
                    var default_opt = '<option value="0">--Select--</option>';
                    console.log('data1---------->' + data1.Table);
                    if (data1.Table.length > 0) {
                        debugger;
                        for (var i = 0; i < data1.Table.length; i++) {
                            SelRole = SelRole + '<option value="' + data1.Table[i].maximum_Discount_authorization + '" data-id="' + data1.Table[i].maximum_discount_authorization_Type + '">' + data1.Table[i].first_name + '</option>';
                        }
                        $('#sel_authorized_person').html(default_opt + SelRole);
                        $('#sel_authorized_person').val($('#Hdnauthorizedid').val());

                    }
                }
            }
        }
    });
}

// Authorized Person dropdrop change function
$('#sel_authorized_person').change(function () {

    debugger;
    var DiscountType = $('#sel_authorized_person option:selected').data('id');
    $('#authorized_discount').addClass('disabled');
    $('#max_percentage').val($('#sel_authorized_person').val());
    if (DiscountType == 1) {
        $('#max_percentage').html('₹' + $('#sel_authorized_person').val());
        $('#authorized_discount').val(1);

    }
    else {
        $('#max_percentage').html($('#sel_authorized_person').val() + '%');
        $('#authorized_discount').val(2);
    }


    if ($('#sel_authorized_person').val() != 0) {
        $('#max_percentage_div').show();
    }
    else {
        $('#max_percentage_div').hide();
    }
});


// Authorized Person calculation
$('#txt_tot_discount_amt').change(function () {

    debugger;
    var DiscountType = $('#sel_authorized_person option:selected').data('id');
    var max_percentage = $('#max_percentage').val();
    var tot_discount_amt = $('#txt_tot_discount_amt').val();
    var total_net_amount = $('#total_net_amount').html();
    var collect_payment = $('#collect_payment').html();

    if (tot_discount_amt > max_percentage) {
        toastr.warning('Please check the maximum Discount Price');
        return false;
    }
    if (max_percentage == '') { max_percentage = 0 }
    if (tot_discount_amt == '') { tot_discount_amt = 0 }
    if (total_net_amount == '') { total_net_amount = 0 }
    if (collect_payment == '') { collect_payment = 0 }

    var check_collected_amt = parseFloat(total_net_amount) - parseFloat(collect_payment);
    if (DiscountType == 1) {
        total_net_amount = check_collected_amt - tot_discount_amt;
    }
    else {
        total_net_amount = check_collected_amt - ((check_collected_amt / 100) * tot_discount_amt);
    }

    var total_discount = parseFloat(check_collected_amt) - parseFloat(total_net_amount);
    total_discount = parseFloat(total_discount) + parseFloat($('#total_discount').html());
    if (total_net_amount > check_collected_amt) {
        toastr.warning('Please check the Collected Amount');
        $('#txt_tot_discount_amt').val('');
        $('#txt_tot_discount_amt').focus();
        return false;
    }
    $('#total_net_amount').html(total_net_amount);
    $('#total_discount').html(total_discount.toFixed());

});


function service_code(currentRow, serive_val, id) {
    var indicator_id = '';
    if (serive_val == 0) {
        indicator_id = 'SMDD'
    }
    else {
        indicator_id = 'SMD'
    }

    var DoctorData = {
        price_matrix_id: serive_val,
        dml_indicator: indicator_id,
        master_service_id: id
    }
    $.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);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                debugger;
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    if (data1.Table.length > 0) {
                        if (data1.Table[0].base_amount_type == 1 || data1.Table[0].base_amount_type == 3) {
                            $('.txt_unitRate').prop('disabled', false);
                            if (data1.Table[0].base_amount_type == 3) {
                                $('#Ptxt_unitRate').html("Enter the amount between " + data1.Table[0].range_min + ' - ' + data1.Table[0].range_max);
                                $('#Hrange_min').val(data1.Table[0].range_min);
                                $('#Hrange_max').val(data1.Table[0].range_max);
                            }
                        }
                        else {
                            $('#Ptxt_unitRate').html('');
                            $('.txt_unitRate').prop('disabled', true);
                        }
                        $('.base_amount_type').val(data1.Table[0].base_amount_type);
                        $('.txt_quantity').val(1);
                        $('.txt_unitRate').val(data1.Table[0].actual_amount);
                        $('.txt_totalamt').html(data1.Table[0].actual_amount);
                        $('.master_service_id').val(data1.Table[0].master_service_id);
                        $('#His_tax').val(data1.Table[0].is_tax);
                        $('#Htax_percentage').val(data1.Table[0].tax_percentage);
                        $('.package_id').val(data1.Table[0].package_id);
                    }
                }
            }
        }
    })
}
$('.txt_unitRate').change(function () {
    debugger;
    if ($('.base_amount_type').val() == 1) {
        if ($('.txt_unitRate').val() == '' || $('.txt_unitRate').val() == 0) {
            $('#Ptxt_unitRate').show();
            $('#Ptxt_unitRate').fadeOut(8000);
            $('#Ptxt_unitRate').html('Enter the amount');
            $('.txt_unitRate').focus();
            $('.txt_unitRate').val('');
            $('.txt_totalamt').html(0.00);
            return false;
        }
    }
    if ($('.base_amount_type').val() == 3) {
        debugger;
        var range_min = $('#Hrange_min').val();
        var range_max = $('#Hrange_max').val();

        if ($('.txt_unitRate').val() == '' || $('.txt_unitRate').val() == 0 || (parseInt($('.txt_unitRate').val()) < parseInt(range_min) || parseInt($('.txt_unitRate').val()) > parseInt(range_max))) {

            $('.txt_unitRate').val(range_min)
        }
    }
    var quantity = $('.txt_quantity').val();
    var unit = $('.txt_unitRate').val();
    var total = parseFloat(unit) * parseFloat(quantity);
    $('.txt_totalamt').html(total.toFixed(2));
})

$('.txt_quantity').change(function () {

    var totval = '';
    var quantity = $('.txt_quantity').val();
    var unitRate = $('.txt_unitRate').val()
    var txt_discount = $('.txt_discount').val();
    var sel_discount_type = $('.sel_discount_type').val();
    totval = quantity * unitRate;

    $('.txt_totalamt').html(totval);
});


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

    if ($('#btn_add').html() == 'Update') {
        debugger;
        serviceupdate();
    }
    else {
        serviceadd();
    }

});

function serviceadd() {
    if ($('.txt_service_name').val() == "") {
        $('#Ptxt_service_name').show();
        $('#PtxtPaitentSearch_bill').fadeOut(8000);
        $('#PtxtPaitentSearch_bill').html('Please select The service name');
        $('.txtPaitentSearch_bill').focus();
        $('.txtPaitentSearch_bill').val('');
        return false;
    }
    if ($('.txt_unitRate').val() == '' || $('.txt_unitRate').val() == 0) {
        $('#Ptxt_unitRate').show();
        $('#Ptxt_unitRate').fadeOut(8000);
        $('#Ptxt_unitRate').html('Enter the amount');
        $('.txt_unitRate').focus();
        $('.txt_unitRate').val('');
        $('.txt_totalamt').html(0.00);
        return false;
    }
    if ($('.txt_quantity').val() == "") {
        $('#Ptxt_quantity').show();
        $('#Ptxt_quantity').fadeOut(8000);
        $('#Ptxt_quantity').html('Please enter the quantity');
        $('.txt_quantity').focus();
        $('.txt_quantity').val('');
        return false;
    }

    //var rowCount = $('#estimation_tbl tbody tr').length;
    //if (rowCount == 0) {
    //    rowCount = 1
    //}
    //else {
    //    var id = $('#estimation_tbl tbody tr:last').attr('id');
    //    id = id.split('_');
    //    rowCount = parseInt(id[1]) + (1);
    //}
    var rowCount = $('#estimation_tbl >tbody >tr').length;
    if (rowCount == 0) {
        rowCount = 1
    }
    else {

        var max = 0;

        $('.number').each(function () {

            var value = parseInt($(this).data('id'));

            max = (value > max) ? value : max;

        });
        rowCount = Number(max) + 1;
    }
    debugger;
    var discount_amount = 0.0;
    var d_amt = $('.txt_discount').val() == "" ? 0 : $('.txt_discount').val();
    var sel_discount_type = $('.sel_discount_type').val();
    if (sel_discount_type == 1) {
        sel_discount_type = '₹';
        discount_amount = parseFloat(d_amt);
    }
    else {
        sel_discount_type = '%';
        discount_amount = parseFloat($('.txt_totalamt').html()) * (parseFloat(d_amt) / 100);
    }
    var tax_amount = 0.0;
    if ($('#Htax_percentage').val() != 0) {
        tax_amount = (parseFloat($('.txt_totalamt').html()) * parseFloat($('#Htax_percentage').val()) / 100)
    }

    debugger;
    var tot_net_amt = parseFloat($('.txt_totalamt').html()) - discount_amount

    var tr = '<tr id="tr_' + rowCount + '" class="number" data-id=' + rowCount + '><td><input type="checkbox" class="chkServices" name="chkrow_' + rowCount + '" /></td><td id="tdSerName_' + rowCount + '">' + $('.txt_service_name').val() + '</td><td id="tdSerQty_' + rowCount + '">' + $('.txt_quantity').val() + '</td><td id="tdSerUnit_' + rowCount + '">' + $('.txt_unitRate').val() + '</td>'
    tr += '<td id="tdSerAmt_' + rowCount + '">' + $('.txt_totalamt').html() + '</td><td id="tdSerDis_' + rowCount + '">' + $('.txt_discount').val() + ' ' + sel_discount_type + '</td><td class="hide" id="tdSerCreatedOn_' + rowCount + '">' + $('.txt_date').val() + '</td><td class="hide" id="tdSerDocName_' + rowCount + '">' + $('.txt_doctor_name option:selected').text() + '</td><td class="hide" id="tdSerdoctorid_' + rowCount + '">' + $('.txt_doctor_name option:selected').val() + '</td><td class="hide" id="tdSerId_' + rowCount + '">' + $('.master_service_id').val() + '</td><td class="hide" id="tdSerEstId_' + rowCount + '">' + $('#hdnEst_details_id').val() + '</td><td class="hide" id="tdSerBType_' + rowCount + '">' + $('.base_amount_type').val() + '</td><td class="hide" id="tdSerRMin_' + rowCount + '">' + $('#Hrange_min').val() + '</td><td class="hide" id="tdSerRMax_' + rowCount + '">' + $('#Hrange_max').val() + '</td><td class="hide" id="tdSerReqDetId_' + rowCount + '">0</td>'
    tr += '<td class="hide" id="tdSerIsTax_' + rowCount + '">' + $('#His_tax').val() + '</td><td class="hide" id="tdSerDisType_' + rowCount + '">' + $('.sel_discount_type').val() + '</td><td id="tdSerIsPrice_' + rowCount + '" class="hide">1</td><td class="hide" id="tdSerPack_' + rowCount + '">' + $('.package_id').val() + '</td><td class="hide" id="tdSerReqId_' + rowCount + '">0</td>'
    tr += '<td id="tdSerDisAmt_' + rowCount + '">' + discount_amount + '</td><td id="tdSerTax_' + rowCount + '">' + $('#Htax_percentage').val() + '%</td><td id="tdSerNetAmt_' + rowCount + '">' + parseFloat(parseFloat(tax_amount) + parseFloat(tot_net_amt)).toFixed(2) + '</td><td id="tdSerReqDate_' + rowCount + '">' + $('.txt_requestdate').val() + '</td><td id="tdSerPrefTime_' + rowCount + '">' + $('.txt_prefertime').val() + '</td><td class="hide" id="tdDayNo_' + rowCount + '"></td><td><span class="btn btn-xs btn-primary service_edit mr-10"><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" ><i class="fa fa-trash" aria-hidden="true"></i></span> </td></tr>';


    $('#estimation_tbl tbody').append(tr);
    $('.txt_servibtn_submitce_name').val('');
    $('.txt_quantity').val('');
    $('.txt_unitRate').val('');
    $('.txt_discount').val('');
    $('.txt_totalamt').html('');
    $('.base_amount_type').val('');
    $('.txt_requestdate').val('');
    $('.txt_prefertime').val('');
    //$('.txt_doctor_name').val(0);
    $('.master_service_id').val('');
    //$('.txt_date').val('');
    $('.txt_service_name').val('');
    $('#Ptxt_unitRate').html('');
    $('.txt_unitRate').prop('disabled', true);
    debugger;
    AmountCalculation()
}


function serviceupdate() {
    if ($('.txt_service_name').val() == "") {
        $('#Ptxt_service_name').show();
        $('#PtxtPaitentSearch_bill').fadeOut(8000);
        $('#PtxtPaitentSearch_bill').html('Please select The service name');
        $('.txtPaitentSearch_bill').focus();
        $('.txtPaitentSearch_bill').val('');
        return false;
    }
    if ($('.txt_unitRate').val() == '' || $('.txt_unitRate').val() == 0) {
        $('#Ptxt_unitRate').show();
        $('#Ptxt_unitRate').fadeOut(8000);
        $('#Ptxt_unitRate').html('Enter the amount');
        $('.txt_unitRate').focus();
        $('.txt_unitRate').val('');
        $('.txt_totalamt').html(0.00);
        return false;
    }
    if ($('.txt_quantity').val() == "") {
        $('#Ptxt_quantity').show();
        $('#Ptxt_quantity').fadeOut(8000);
        $('#Ptxt_quantity').html('Please enter the quantity');
        $('.txt_quantity').focus();
        $('.txt_quantity').val('');
        return false;
    }

    debugger;
    var discount_amount = 0.0;
    var d_amt = $('.txt_discount').val() == "" ? 0 : $('.txt_discount').val();
    var sel_discount_type = $('.sel_discount_type').val();
    if (sel_discount_type == 1) {
        sel_discount_type = '₹';
        discount_amount = parseFloat(d_amt);
    }
    else {
        sel_discount_type = '%';
        discount_amount = parseFloat($('.txt_totalamt').html()) * (parseFloat(d_amt) / 100);
    }

    debugger;
    var tot_net_amt = parseFloat($('.txt_totalamt').html()) - discount_amount
    var tax_amount = 0.0;
    if ($('#Htax_percentage').val() != 0) {
        tax_amount = (parseFloat($('.txt_totalamt').html()) * parseFloat($('#Htax_percentage').val()) / 100)
    }
    var rowCount = $('#' + trid).attr("data-id");
    $('#tdSerName_' + rowCount + '').html($('.txt_service_name').val());
    $('#tdSerQty_' + rowCount + '').html($('.txt_quantity').val());
    $('#tdSerUnit_' + rowCount + '').html($('.txt_unitRate').val());
    $('#tdSerDis_' + rowCount + '').html($('.txt_discount').val() + ' ' + sel_discount_type);
    $('#tdSerAmt_' + rowCount + '').html($('.txt_totalamt').html());
    $('#tdSerCreatedOn_' + rowCount + '').html($('.txt_date').val());
    $('#tdSerDocName_' + rowCount + '').html($('.txt_doctor_name option:selected').text());
    $('#tdSerdoctorid_' + rowCount + '').html($('.txt_doctor_name option:selected').val());
    $('#tdSerDisAmt_' + rowCount + '').html(discount_amount);
    $('#tdSerNetAmt_' + rowCount + '').html(parseFloat(parseFloat(tax_amount) + parseFloat(tot_net_amt)).toFixed(2));
    $('#tdSerId_' + rowCount + '').html($('.master_service_id').val());

    $('#tdSerReqDate_' + rowCount + '').html($('.txt_requestdate').val());
    $('#tdSerPrefTime_' + rowCount + '').html($('.txt_prefertime').val());
    $('#tdDayNo_' + rowCount + '').html($('.txt_DayNo').val());

    //var tr = '<td>' + $('.txt_service_name').val() + '</td><td>' + $('.txt_quantity').val() + '</td><td>' + $('.txt_unitRate').val() + '</td>'
    //tr += '<td>' + $('.txt_discount').val() + ' ' + sel_discount_type + '</td><td>' + $('.txt_totalamt').html() + '</td><td class="hide">' + $('.txt_date').val() + '</td><td class="hide">' + $('.txt_doctor_name option:selected').text() + '</td><td class="hide">' + $('.txt_doctor_name option:selected').val() + '</td><td class="hide">' + $('.master_service_id').val() + '</td><td class="hide">' + $('#hdnEst_details_id').val() + '</td><td class="hide">' + $('.base_amount_type').val() + '</td><td class="hide">' + $('#Hrange_min').val() + '</td><td class="hide">' + $('#Hrange_max').val() + '</td>'
    //tr += '<td>' + discount_amount + '</td><td>' + tot_net_amt + '</td><td><span class="btn btn-xs btn-primary service_edit mr-10"><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete"><i class="fa fa-trash" aria-hidden="true"></i></span> </td>';
    //$('#' + trid).html(tr);
    $('.txt_service_name').val('');
    $('.txt_quantity').val('');
    $('.txt_unitRate').val('');
    $('.txt_discount').val('');
    $('.txt_totalamt').html('');
    $('.txt_Discountamt').html('');
    $('.txt_totalnetamt').html('');
    $('.txt_doctor_name').val(0);
    $('.master_service_id').val('');
    $('#hdnEst_details_id').val(0);
    $('#btn_add').html('Add');
    $('.txt_date').val('');
    $('.txt_requestdate').val('');
    $('.txt_prefertime').val('');
    $('.txt_service_name').val('');
    $('#Ptxt_unitRate').html('');
    $('.txt_unitRate').prop('disabled', true);
    $('.base_amount_type').val(0);

    AmountCalculation();

    //var Net_Amount = 0, Total_Net_Amount = 0, total_discount = 0;
    //$("#estimation_tbl tbody tr").each(function () {
    //    debugger;
    //    var discount_type = $(this).find("td").eq(3).html();
    //    var dis_amt = '', dis_type = '', cur_val = '';
    //    cur_val = $(this).find("td").eq(4).html();
    //    if (discount_type != '') {
    //        discount_type = discount_type.split(' ');
    //        dis_amt = discount_type[0];
    //        dis_type = discount_type[1];
    //        if (dis_type == '₹') {
    //            cur_val = cur_val - dis_amt
    //        }
    //        else if (dis_type == '%') {
    //            cur_val = cur_val - ((cur_val / 100) * dis_amt)
    //        }
    //    }
    //    Total_Net_Amount = parseFloat(Total_Net_Amount) + parseFloat(cur_val);

    //    Net_Amount = parseFloat(Net_Amount) + parseFloat($(this).find("td").eq(4).html());

    //    total_discount = parseFloat(Net_Amount) - parseFloat(Total_Net_Amount);
    //});
    //$('#net_amount').html(Net_Amount);
    //$('#total_net_amount').html(Total_Net_Amount);
    //$('#total_discount').html(total_discount);
}

var trid = "";
$("#estimation_tbl").on('click', '.service_edit', function () {
    // get the current row
    debugger;
    trid = $(this).closest('tr').attr('id');
    let rowCount = $('#' + trid).attr("data-id");
    var currentRow = $(this).closest("tr");


    var col1 = $('#tdSerName_' + rowCount + '').html(); // get current row 1st TD value
    var col2 = $('#tdSerQty_' + rowCount + '').html(); // get current row 2nd TD
    var col3 = $('#tdSerUnit_' + rowCount + '').html(); // get current row 3rd TD
    var col4 = $('#tdSerDis_' + rowCount + '').html(); // get current row 3rd TD
    var col5 = $('#tdSerAmt_' + rowCount + '').html(); // get current row 3rd TD
    var col6 = $('#tdSerCreatedOn_' + rowCount + '').html(); // get current row 3rd TD
    var col7 = $('#tdSerDocName_' + rowCount + '').html(); // get current row 3rd TD
    var col8 = $('#tdSerdoctorid_' + rowCount + '').html(); // get current row 3rd TD
    var col9 = $('#tdSerId_' + rowCount + '').html(); // get current row 3rd TD
    var col10 = $('#tdSerEstId_' + rowCount + '').html();
    var col11 = $('#tdSerBType_' + rowCount + '').html();
    var col12 = $('#tdSerRMin_' + rowCount + '').html();
    var col13 = $('#tdSerRMax_' + rowCount + '').html();
    var col14 = $('#tdSerReqDetId_' + rowCount + '').html();
    var col15 = $('#tdSerIsTax_' + rowCount + '').html();
    var col16 = $('#tdSerDisType_' + rowCount + '').html();
    var col17 = $('#tdSerDisAmt_' + rowCount + '').html();
    var col18 = $('#tdSerTax_' + rowCount + '').html();
    var col19 = $('#tdSerNetAmt_' + rowCount + '').html();
    var col20 = $('#tdSerReqDate_' + rowCount + '').html();
    var col21 = $('#tdSerPrefTime_' + rowCount + '').html();
    var col22 = $('#tdDayNo_' + rowCount + '').html();
    col4 = $('#tdSerDis_' + rowCount + '').html().split(' ');
    var discount = col4[0];
    var type = col4[1];
    if (type == '₹') { type = 1; }
    else if (type == '%') { type = 2; }
    else { type = ''; }
    if (col11 == 1 || col11 == 3) {
        $('.txt_unitRate').prop('disabled', false)
        if (col11 == 3) {
            $('#Ptxt_unitRate').html("Enter the amount between " + col12 + ' - ' + col13);
            $('#Hrange_min').val(col12);
            $('#Hrange_max').val(col13);
        }
    }
    else {
        $('.txt_unitRate').prop('disabled', true)
    }
    $('#Htax_percentage').val(col18.split('%')[0]);
    $('.base_amount_type').val(col11);
    $('.txt_service_name').val(col1);
    $('.txt_quantity').val(col2);
    $('.txt_unitRate').val(col3);
    $('.txt_discount').val(discount);
    $('.sel_discount_type').val(type);
    $('.txt_totalamt').html(col5);
    $('.txt_date').val(col6);
    $(".txt_doctor_name option").each(function () {
        if ($(this).text() == col7) {
            $(this).prop('selected', 'selected');
        }
    });
    $('.master_service_id').val(col9);
    $('#hdnEst_details_id').val(col10);
    //$('.txt_Discountamt').html(col14);
    //$('.txt_totalnetamt').html(col15);
    $('.txt_requestdate').val(col20);
    $('.txt_prefertime').val(col21);
    $('.txt_DayNo').val(col22);
    $('#btn_add').html('Update');
});

$("#estimation_tbl").on('click', '.service_delete', function () {
    //"$(this).closest(\'tr\').remove();"
    $(this).closest("tr").remove();

    var Net_Amount = 0, Total_Net_Amount = 0, total_discount = 0;
    $("#estimation_tbl tbody tr").each(function () {
        debugger;
        var discount_type = $(this).find("td").eq(3).html();
        var dis_amt = '', dis_type = '', cur_val = '';
        cur_val = $(this).find("td").eq(4).html();
        if (discount_type != '') {
            discount_type = discount_type.split(' ');
            dis_amt = discount_type[0];
            dis_type = discount_type[1];
            if (dis_type == '₹') {
                cur_val = cur_val - dis_amt
            }
            else if (dis_type == '%') {
                cur_val = cur_val - ((cur_val / 100) * dis_amt)
            }
        }
        Total_Net_Amount = parseFloat(Total_Net_Amount) + parseFloat(cur_val);
        Net_Amount = parseFloat(Net_Amount) + parseFloat($(this).find("td").eq(4).html());
        total_discount = parseFloat(Net_Amount) - parseFloat(Total_Net_Amount);
    });
    $('#net_amount').html(Net_Amount);
    $('#total_net_amount').html(Total_Net_Amount);
    $('#total_discount').html(total_discount);
    AmountCalculation()
});


$('#btn_submit').click(function () {
    debugger;


    EstimateSubmit('');

});
function EstimateSubmit(Flag) {
    var rowCount = $('#estimation_tbl tbody tr').length
    //if ($('#Hvisitid').val() == "") {
    //    alert('Please Select Patient');
    //    return false;
    //}
    if (rowCount == 0) {
        toastr.warning('Please Add Estimation Details');
        return false;
    }
    if ($.trim($('#pkg_branch_id').val()) == '' || $('#pkg_branch_id').val() == 0) {
        $('#Ppkg_branch_id').show();
        $('#Ppkg_branch_id').fadeOut(8000);
        $('#PddWardNo').html('Select Branch');
        $('#pkg_branch_id').focus();
        $('#pkg_branch_id').val('');
        return false;
    }
    if ($('#visit_type').val() == "" || $('#visit_type').val() == 0) {
        $('#Pvisit_type').show();
        $('#Pvisit_type').fadeOut(8000);
        $('#Pvisit_type').html('Select Visit Type');
        $('#visit_type').focus();
        $('#visit_type').val('');
        return false;
    }

    if ($('#Insurance_type').val() == "") {
        $('#PInsurance_type').show();
        $('#PInsurance_type').fadeOut(8000);
        $('#PInsurance_type').html('Please select The Insurance');
        $('#Insurance_type').focus();
        $('#Insurance_type').val('');
        return false;
    }
    if ($.trim($('#Insurance_type').val()) == 1) {
        if ($.trim($('#EntityType').val()) == '') {
            $('#PEntityType').show();
            $('#PEntityType').fadeOut(8000);
            $('#PEntityType').html('Select Claim Type');
            $('#ddInsuranceName').focus();
            return false;
        }
    }

    if ($.trim($('#EntityType').val()) != '') {
        if ($.trim($('#HdnEntityid').val()) == '') {
            $('#PddInsuranceName').show();
            $('#PddInsuranceName').fadeOut(8000);
            $('#PddInsuranceName').html('Select Entity Name');
            $('#ddInsuranceName').focus();
            return false;
        }
        if ($('#CMultiPay').prop('checked') == true) {
            if ($.trim($('#MPCIName').val()) == '') {
                $('#PMPCIName').show();
                $('#PMPCIName').fadeOut(8000);
                $('#PMPCIName').html('Select the field');
                $('#PMPCIName').focus();
                return false;
            }
        }

    }

    if ($('#ddWard').val() == 0 || $('#ddWard').val() == "") {
        $('#PddWard').show();
        $('#PddWard').fadeOut(8000);
        $('#PddWard').html('Please select The Ward');
        $('#ddWard').focus();
        $('#ddWard').val(0);
        return false;
    }
    let count = 0
    $("#estimation_tbl tbody tr").each(function () {
        let id = $(this).prop("id");
        let rowCount = $('#' + id).attr('data-id');
        if (parseInt($('#tdSerIsPrice_' + rowCount).html()) == 2) {
            count = 1;

            return false;
        }
    })
    if (count == 1) {
        toastr.warning('Set Price Matrix');
        return false;
    }
    $('#shade_slot_submit').show();
    $('#btn_submit').attr('disabled', true);
    $('#btn_submitandPrint,#btnConvertBill,#btnConvertTask,#btnConvertSchedule').attr('disabled', true);
    var EstimationArray = [];
    var status = "";

    var visit_type = $("#visit_type").val();
    var due_amount = "";

    var d = new Date();
    var month = d.getMonth() + 1;
    var day = d.getDate();
    var curDate = d.getFullYear() + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;

    $("#estimation_tbl tbody tr").each(function () {
        var list = {};
        let id = $(this).prop("id");
        let rowCount = $('#' + id).attr('data-id');
        var discount = $('#tdSerDis_' + rowCount + '').html();
        var discount_type = '', discount_val = '';
        discount = discount.split(' ');
        discount_val = discount[0]
        discount_type = discount[1];
        if (discount_type == '₹') {
            discount_type = 1;
        }
        else {
            discount_type = 2;
        }

        if (discount_val == '' || discount_val == 0) {
            discount_val = 0.00;
        }

        if ($('#hdnEstimationid').val() == "" || $('#hdnEstimationid').val() == null) {
            $('#hdnEstimationid').val(0);
        }
        list.entity_id = $('#HdnEntityid').val() || 0,
            list.estimation_no = $('#hdnEstimationid').val(),
            list.insurance = $('#Insurance_type').val()
        list.patient_id = $('#hdnpatient_id').val(),
            list.patientid = $('#hdnpatientid').val(),
            list.visit_report_id = $('#hdnVisitReportId').val(),
            list.visit_reportid = $('#Hvisitid').val(),
            list.hospital_id = $('#HospitalId').val(),
            list.visit_type = visit_type
        list.created_by = $('#hiddenUser_id').val(),
            list.due_amount = due_amount,
            list.total_amount = $('#net_amount').html(),
            list.total_net_amount = $('#total_net_amount').html(),
            list.branch_id = $('#pkg_branch_id').val(),
            list.h_discount = $('#txt_tot_discount_amt').val(),
            list.h_discount_type = $('#authorized_discount').val(),
            list.h_total_discount_amount = $('#total_discount').html(),
            list.discount_authorization_by = $('#sel_authorized_person').val(),
            list.patient_type_id = '1',//1. self 2. insurance
            list.status = status,
            list.billing_channel = 1,
            list.created_on = curDate,
            list.discharge_date = curDate,


            list.master_service_id = $('#tdSerId_' + rowCount + '').html(),
            list.estimation_details_id = $('#tdSerEstId_' + rowCount + '').html(),
            list.amount = $('#tdSerAmt_' + rowCount + '').html(),
            list.service_quantity = $('#tdSerQty_' + rowCount + '').html(),
            list.discount = discount_val
        list.discount_type = discount_type,
            list.package_id = $('#tdSerPack_' + rowCount + '').html(),
            list.billing_type = 2, //1. work order initiated\n2. appointment initiated'
            list.discharge_type = 1,
            list.ward_id = $('#ddWard').val(),
            list.billing_class = $('#dd_BillingName').val(), // $('#hndbilling_class').val(),
            list.doctor_id = $('#tdSerdoctorid_' + rowCount + '').html(),
            list.service_quantity_amount = $('#tdSerUnit_' + rowCount + '').html(),
            list.discount_amount = $('#tdSerDisAmt_' + rowCount + '').html(),
            list.net_amount = $('#tdSerNetAmt_' + rowCount + '').html(),
            list.RequestId = $('#tdSerReqId_' + rowCount + '').html() || 0
        list.RequestDetailsId = $('#tdSerReqDetId_' + rowCount + '').html() || 0
        list.is_insurance = $('#EntityType').val() || 0,
            list.is_MultiPay = $('#CMultiPay').val() || 0,
            list.Corporate_Insuranceid = $('#MPCIName').val() || 0,
            EstimationArray.push(list);
    });
    return $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Estimation_Ins_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(EstimationArray),
        success: function (data) {
            if (Flag != 'bill') {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    $('#shade_slot_submit').hide();
                    $('#btn_submit').attr('disabled', false);
                    $('#btn_submitandPrint').attr('disabled', false);
                    var data1 = data.data;


                    if ($('#hdnEstimationid').val() == "" || $('#hdnEstimationid').val() == 0) {
                        toastr.success('Estimation Billing Details Added Successfully.');

                    }
                    else {
                        toastr.success('Estimation Billing Details Updated Successfully.');

                    }

                    //toastr.success('Estimation Billing Details Inserted Successfully',
                    //    {
                    //        progressBar: true,
                    //        allowHtml: true,
                    //        timeOut: 0,
                    //    });
                    setTimeout(function () {
                        window.location = "/BillingMaster/estimation_view";
                    }, 2000);


                }
            }
        }
    });
}

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

    if (parseInt($('#hdnPrint_EstimationNo').val()) != 0) {
        alert('Estimation details already created.Please go to view estimation view page.');
        return false;
    }

    var rowCount = $('#estimation_tbl tbody tr').length

    if (rowCount == 0) {
        toastr.warning('Please Add Estimation Details');
        return false;
    }


    if ($.trim($('#Insurance_type').val()) == 1) {
        if ($.trim($('#EntityType').val()) == '') {
            $('#PEntityType').show();
            $('#PEntityType').fadeOut(8000);
            $('#PEntityType').html('Select Claim Type');
            $('#ddInsuranceName').focus();
            return false;
        }
    }

    if ($.trim($('#EntityType').val()) != '') {
        if ($.trim($('#HdnEntityid').val()) == '') {
            $('#PddInsuranceName').show();
            $('#PddInsuranceName').fadeOut(8000);
            $('#PddInsuranceName').html('Select Entity Name');
            $('#ddInsuranceName').focus();
            return false;
        }
        if ($('#CMultiPay').prop('checked') == true) {
            if ($.trim($('#MPCIName').val()) == '') {
                $('#PMPCIName').show();
                $('#PMPCIName').fadeOut(8000);
                $('#PMPCIName').html('Select the field');
                $('#PMPCIName').focus();
                return false;
            }
        }

    }

    if ($('#ddWard').val() == 0) {
        $('#PddWard').show();
        $('#PddWard').fadeOut(8000);
        $('#PddWard').html('Please select The Ward');
        $('#ddWard').focus();
        $('#ddWard').val(0);
        return false;
    }
    let count = 0
    $("#estimation_tbl tbody tr").each(function () {
        let id = $(this).prop("id");
        let rowCount = $('#' + id).attr('data-id');
        if (parseInt($('#tdSerIsPrice_' + rowCount).html()) == 2) {
            count = 1;

            return false;
        }
    })
    if (count == 1) {
        toastr.warning('Set Price Matrix');
        return false;
    }
    $('#btn_submit').attr('disabled', true);
    $('#btn_submitandPrint,#btnConvertBill,#btnConvertTask,#btnConvertSchedule').attr('disabled', true);

    var EstimationArray = [];
    var status = "";

    var visit_type = $("#visit_type").val();
    var due_amount = "";

    var d = new Date();
    var month = d.getMonth() + 1;
    var day = d.getDate();
    var curDate = d.getFullYear() + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;

    $("#estimation_tbl tbody tr").each(function () {
        var list = {};
        let id = $(this).prop("id");
        let rowCount = $('#' + id).attr('data-id');
        var discount = $('#tdSerDis_' + rowCount + '').html();
        var discount_type = '', discount_val = '';
        discount = discount.split(' ');
        discount_val = discount[0]
        discount_type = discount[1];
        if (discount_type == '₹') {
            discount_type = 1;
        }
        else {
            discount_type = 2;
        }

        if (discount_val == '' || discount_val == 0) {
            discount_val = 0.00;
        }

        if ($('#hdnEstimationid').val() == "" || $('#hdnEstimationid').val() == null) {
            $('#hdnEstimationid').val(0);
        }
        list.entity_id = $('#HdnEntityid').val() || 0,
            list.estimation_no = $('#hdnEstimationid').val(),
            list.insurance = $('#Insurance_type').val()
        list.patient_id = $('#hdnpatient_id').val(),
            list.patientid = $('#hdnpatientid').val(),
            list.visit_report_id = $('#hdnVisitReportId').val(),
            list.visit_reportid = $('#Hvisitid').val()
        list.hospital_id = $('#HospitalId').val(),
            list.visit_type = visit_type
        list.created_by = $('#hiddenUser_id').val(),
            list.due_amount = due_amount,
            list.total_amount = $('#net_amount').html(),
            list.total_net_amount = $('#total_net_amount').html(),
            list.branch_id = $('#pkg_branch_id').val(),
            list.h_discount = $('#txt_tot_discount_amt').val(),
            list.h_discount_type = $('#authorized_discount').val(),
            list.h_total_discount_amount = $('#total_discount').html(),
            list.discount_authorization_by = $('#sel_authorized_person').val(),
            list.patient_type_id = '1',//1. self 2. insurance
            list.status = status,
            list.billing_channel = 1,
            list.created_on = curDate,
            list.discharge_date = curDate,


            list.master_service_id = $('#tdSerId_' + rowCount + '').html(),
            list.estimation_details_id = $('#tdSerEstId_' + rowCount + '').html(),
            list.amount = $('#tdSerAmt_' + rowCount + '').html(),
            list.service_quantity = $('#tdSerQty_' + rowCount + '').html(),
            list.discount = discount_val
        list.discount_type = discount_type,
            list.package_id = $('#tdSerPack_' + rowCount + '').html(),
            list.billing_type = 2, //1. work order initiated\n2. appointment initiated'
            list.discharge_type = 1,
            list.ward_id = $('#ddWard').val(),
            list.billing_class = $('#dd_BillingName').val(), // $('#hndbilling_class').val(),
            list.doctor_id = $('#tdSerdoctorid_' + rowCount + '').html(),
            list.service_quantity_amount = $('#tdSerUnit_' + rowCount + '').html(),
            list.discount_amount = $('#tdSerDisAmt_' + rowCount + '').html(),
            list.net_amount = $('#tdSerNetAmt_' + rowCount + '').html(),
            list.RequestId = $('#tdSerReqId_' + rowCount + '').html() || 0
        list.RequestDetailsId = $('#tdSerReqDetId_' + rowCount + '').html() || 0
        list.is_insurance = $('#EntityType').val() || 0,
            list.is_MultiPay = $('#CMultiPay').val() || 0,
            list.Corporate_Insuranceid = $('#MPCIName').val() || 0,
            EstimationArray.push(list);
    });
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Estimation_Ins_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(EstimationArray),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                debugger;
                var data1 = data.data;

                $('#hdnPrint_EstimationNo').val(data1.Table[0].estimation_no);

                var load_data = {
                    formid: '64',
                    branchid: $('#pkg_branch_id').val(),
                    hospitalid: data1.Table[0].hospitalid,
                    patientid: data1.Table[0].patientid,
                    Estimationno: data1.Table[0].estimation_no
                }
                $.ajax({
                    async: true,
                    type: 'POST',
                    url: '/reports/PrintCrystalReport',
                    contentType: 'application/json; charset=UTF-8',
                    data: JSON.stringify(load_data),
                    success: function (data) {
                        $('#btn_submit').attr('disabled', false);
                        $('#btn_submitandPrint').attr('disabled', false);
                        var byteArray = new Uint8Array(data);
                        var blob = new Blob([byteArray], { type: "application/pdf" });
                        var link = window.URL.createObjectURL(blob);
                        window.open(link, '_blank');
                        setTimeout(function () {
                            window.location = "/BillingMaster/estimation_view";
                        }, 2000);
                        //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);
                        //};
                    }
                });

            }
        }
    });
});

$('#Insurance').change(function () {

    if ($('#Insurance').val() == 1) {
        $('#divInsurance_type').show();
    }
    else {
        $('#divInsurance_type').hide();
    }


});

//function LoadInsurance() {

//    var DoctorData = {
//        Dml_Indicator: "INSS",
//        hospital_id: $('#HospitalId').val(),
//        branch_id: $('#pkg_branch_id').val()
//    }

//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/BillingMaster/Refund_Ins_Upd_sel',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(DoctorData),
//        success: function (data) {
//            var data1 = JSON.parse(data)
//            if (data1.msg == "Success") {
//                if (jQuery.isEmptyObject((data1.data))) {
//                }
//                else {
//                    var tr = '';
//                    var SelIns = '';
//                    $('#SelDoctor').empty();
//                    var default_opt = '<option value="0">--Select--</option>';
//                    var j = 0;
//                    if (data1.data.length > 0) {
//                        for (var i = 0; i < data1.data.length; i++) {
//                            j++;
//                            SelIns = SelIns + '<option value="' + data1.data[i].master_entity_id + '">' + data1.data[i].entity_name + '</option>';
//                        }
//                        $('#Insurance_type').html(default_opt + SelIns);
//                    }

//                }
//            }
//            else {
//                console.log(data1);
//            }
//        }
//    });
//}

$('#Est_search').click(function () {
    debugger;
    if ($('#pkg_branch_id').val() == 0) {
        $('#Ppkg_branch_id').show();
        $('#Ppkg_branch_id').fadeOut(8000);
        $('#Ppkg_branch_id').html('Please select The Branch name');
        $('#pkg_branch_id').focus();
        $('#pkg_branch_id').val(0);
        return false;
    }
    if ($('#visit_type').val() == "" || $('#visit_type').val() == 0) {
        $('#Pvisit_type').show();
        $('#Pvisit_type').fadeOut(8000);
        $('#Pvisit_type').html('Select Visit Type');
        $('#visit_type').focus();
        $('#visit_type').val('');
        return false;
    }

    if ($('#txtPaitentSearch_1').val() == "") {
        $('#PtxtPaitentSearch_1').show();
        $('#PtxtPaitentSearch_1').fadeOut(8000);
        $('#PtxtPaitentSearch_1').html('Please Search the Patient');
        $('#txtPaitentSearch_1').focus();
        $('#txtPaitentSearch_1').val('');
        return false;
    }

    if ($('#Insurance_type').val() == "") {
        $('#PInsurance_type').show();
        $('#PInsurance_type').fadeOut(8000);
        $('#PInsurance_type').html('Please select patient type');
        $('#Insurance_type').focus();
        $('#Insurance_type').val('');
        return false;
    }

    if ($('#Insurance_type').val() == 1) {
        if ($.trim($('#EntityType').val()) == '') {
            $('#PEntityType').show();
            $('#PEntityType').fadeOut(8000);
            $('#PEntityType').html('Select Claim Type');
            $('#ddInsuranceName').focus();
            return false;
        }
        if ($.trim($('#EntityType').val()) != '') {
            if ($('#HdnEntityid').val() == 0) {
                $('#PddInsuranceName').show();
                $('#PddInsuranceName').fadeOut(8000);
                $('#PddInsuranceName').html('Please Enter Entity Name');
                $('#ddInsuranceName').focus();
                $('#ddInsuranceName').val('');
                return false;
            }
            if ($('#CMultiPay').prop('checked') == true) {
                if ($.trim($('#MPCIName').val()) == '') {
                    $('#PMPCIName').show();
                    $('#PMPCIName').fadeOut(8000);
                    $('#PMPCIName').html('Select the field');
                    $('#PMPCIName').focus();
                    return false;
                }
            }
        }
    }

    if ($('#Insurance_type').val() == 2) {
        if ($('#dd_BillingName').val() == 0) {
            $('#Pdd_BillingName').show();
            $('#Pdd_BillingName').fadeOut(8000);
            $('#Pdd_BillingName').html('Please select The Billing Name');
            $('#dd_BillingName').focus();
            $('#dd_BillingName').val(0);
            return false;
        }
    }

    if ($('#ddWard').val() == 0) {
        $('#PddWard').show();
        $('#PddWard').fadeOut(8000);
        $('#PddWard').html('Please select The Ward');
        $('#ddWard').focus();
        $('#ddWard').val(0);
        return false;
    }
    if ($('#visit_type').val() == 2) {
        bedcharges();
    }
    //var patient_id = $('#txtPaitentSearch_1').val().split('/')[4];
    //$('#hdnpatient_id').val(patient_id);

    $('#div_Service').removeClass('hidden');

});

function bedcharges() {
    let fullPatientId = $('#txtPaitentSearch_1').val();
    let patientId = fullPatientId.split('/').pop();
    $('#txtPaitentSearch_1').val(patientId);

    var chargesdata = {
        Dml_Indicator: "ES",
        patient_id: patientId,
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#pkg_branch_id').val(),
        billing_class: $('#hdInsBilling_class').val(),
        wardid: $("#ddWard").val()
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(chargesdata),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (!jQuery.isEmptyObject(data2.data)) {
                bindTableData(data2.data.Table);
            }
        }
    });
}

function bindTableData(data) {
    var table = $('#estimation_tbl');
    table.find('tbody').empty();

    let netAmount = 0;
    let totalDiscount = 0;

    data.forEach(function (item) {
        //var row = '<tr>';
        //row += '<td>' + (item.ward_id + ' (' + item.ward_name + ')') + '</td>';
        //row += '<td>' + item.quantity + '</td>';
        //row += '<td>' + item.base_amount + '</td>';
        //row += '<td>' + item.net_total + '</td>';
        //row += '<td>' + "-" + '</td>';
        //row += '<td>' + "-" + '</td>';
        //row += '<td>' + "-" + '</td>';
        //row += '<td>' + item.total_amount + '</td>';
        //row += '</tr>';
        //table.find('tbody').append(row);

        //netAmount += parseFloat(item.total_amount);
        //totalDiscount += parseFloat(item.discount_amount || 0);


        var rowCount = $('#estimation_tbl >tbody >tr').length;
        if (rowCount == 0) {
            rowCount = 1
        }
        else {

            var max = 0;

            $('.number').each(function () {

                var value = parseInt($(this).data('id'));

                max = (value > max) ? value : max;

            });
            rowCount = Number(max) + 1;
        }
        debugger;
        var discount_amount = 0.0;

        var tr = '<tr id="tr_' + rowCount + '" class="number" data-id=' + rowCount + '><td><input type="checkbox" class="chkServices" name="chkrow_' + rowCount + '" /></td><td id="tdSerName_' + rowCount + '">' + item.service_name + '</td><td id="tdSerQty_' + rowCount + '">' + item.quantity + '</td><td id="tdSerUnit_' + rowCount + '">' + item.net_total + '</td>'
        tr += '<td id="tdSerAmt_' + rowCount + '">' + item.net_total + '</td><td id="tdSerDis_' + rowCount + '">' + ' ' + '</td><td class="hide" id="tdSerCreatedOn_' + rowCount + '">' + item.service_date + '</td><td class="hide" id="tdSerDocName_' + rowCount + '">' + item.DoctorName + '</td><td class="hide" id="tdSerdoctorid_' + rowCount + '">' + item.doctor_id + '</td><td class="hide" id="tdSerId_' + rowCount + '">' + item.master_service_id + '</td><td class="hide" id="tdSerEstId_' + rowCount + '">' + $('#hdnEst_details_id').val() + '</td><td class="hide" id="tdSerBType_' + rowCount + '">' + item.base_amount_type + '</td><td class="hide" id="tdSerRMin_' + rowCount + '">' + item.range_min + '</td><td class="hide" id="tdSerRMax_' + rowCount + '">' + item.range_max + '</td><td class="hide" id="tdSerReqDetId_' + rowCount + '">0</td>'
        tr += '<td class="hide" id="tdSerIsTax_' + rowCount + '">' + '' + '</td><td class="hide" id="tdSerDisType_' + rowCount + '">' + '' + '</td><td id="tdSerIsPrice_' + rowCount + '" class="hide">1</td><td class="hide" id="tdSerPack_' + rowCount + '">' + item.package_id + '</td><td class="hide" id="tdSerReqId_' + rowCount + '">0</td>'
        tr += '<td id="tdSerDisAmt_' + rowCount + '">' + discount_amount + '</td><td id="tdSerTax_' + rowCount + '">' + '' + '%</td><td id="tdSerNetAmt_' + rowCount + '">' + item.net_total + '</td><td id="tdSerReqDate_' + rowCount + '"></td><td id="tdSerPrefTime_' + rowCount + '"></td><td class="hide" id="tdDayNo_' + rowCount + '"></td><td><span class="btn btn-xs btn-primary service_edit mr-10"><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" ><i class="fa fa-trash" aria-hidden="true"></i></span> </td></tr>';


        $('#estimation_tbl tbody').append(tr);
    });
    // Recalculate total amounts after appending new rows
    AmountCalculation();
}


function WardNo(wardid) {
    debugger;
    var Warddata = {
        Dml_Indicator: "ESWNE",
        branchid: $('#pkg_branch_id').val(),
    }

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

            }
            else {

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

                    var WardNo;
                    $('#ddWard').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {

                        WardNo = WardNo + '<option value="' + emp.wardid + '">' + emp.ward_id + "/" + emp.ward_name + '</option>';

                    });
                    $('#ddWard').append(default_opt + WardNo);
                    $('#ddWard').val($('#Hwardid').val())
                    if (wardid != 0) {
                        $('#ddWard').val(wardid);
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

function Estimationload() {

    debugger;

    $('.Pdetails_disabled').addClass('disabled');
    $('#div_Service').removeClass('hidden');

    var SCDTbldata = {

        Dml_Indicator: 'ESDS',
        billing_no: $('#hdnEstimationid').val()
    }

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

                    $.each(data1.Table, function (i, emp) {
                        $("#pkg_branch_id").append('<option value="' + emp.branch_id + '">' + emp.branch_name + '</option>'),
                            $("#ddWard").append('<option value="' + emp.Wardid + '">' + emp.ward_name + '</option>'),
                            $("#visit_type").append('<option value="' + data1.Table[0].visit_type + '">' + data1.Table[0].visit_type_name + '</option>').attr('disabled', true),
                            $('#net_amount').html(emp.total_amount);
                        $('#total_net_amount').html(emp.total_net_amount);
                        $('#total_discount').html(emp.total_discount_amount);
                        $('#sel_authorized_person').val(emp.discount_authorization_by);
                        $('#Hdnauthorizedid').val(emp.discount_authorization_by);
                        $('#txt_tot_discount_amt').val(emp.discount);
                        $('#authorized_discount').val(emp.discount_type);
                        $('#ddWard').val(emp.Wardid);
                        $('#Insurance_type').val(emp.Insurance);
                        $("#dd_BillingName").append('<option value="' + emp.billing_class + '">' + emp.master_service_name + '</option>'),
                            $('#hdInsBilling_class').val(emp.billing_class);
                        $("#ddWard").val(emp.Wardid)
                        $('#txtPaitentSearch_1').val(emp.first_name);
                        $('#HdnEntityid').val(emp.entity_id);
                        $('#EntityType').val(emp.is_insurance);

                        if (emp.IsConvertedToBill == 1) {
                            $('#btnConvertBill,#btnConvertTask,#btnConvertSchedule').hide();
                        }
                        //if (emp.IsConvertedToTask == 1) {
                        //    $('#btnConvertTask').hide();
                        //}
                        $('.clsEst').addClass('disabled');
                        if (emp.Insurance == 1) {
                            $('#div_EntityType').removeClass('hide');
                            if ($('#EntityType').val() == 1) {
                                $('#EntityType_Insurance').click();
                                Corporate_Insurance($('#HdnEntityid').val(), data1.Table[0].Corporate_Insuranceid);
                            }
                            else {
                                $('#EntityType_Corporate').click()
                            }
                            $('#CMultiPay').val(data1.Table[0].is_MultiPay);
                            if ($('#CMultiPay').val() == 1) {
                                $('#CMultiPay').prop('checked', true);
                                $('#CMultiPay').change()
                            }
                        }
                        else {
                            $('#div_BillingName').removeClass('hidden');
                        }
                        $('#ddInsuranceName').val(emp.entity_name);
                        authorized_person();
                    });

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

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



                        var tr = '<tr id="tr_' + i + '" class="number" data-id=' + i + '><td><input type="checkbox" class="chkServices" name="chkrow_' + i + '" /></td><td id="tdSerName_' + i + '">' + emp.service_name + '</td><td id="tdSerQty_' + i + '">' + emp.service_quantity + '</td><td id="tdSerUnit_' + i + '">' + emp.service_quantity_amount + '</td><td id="tdSerAmt_' + i + '">' + emp.amount + '</td>'
                        tr += '<td id="tdSerDis_' + i + '">' + emp.discount + ' ' + sel_discount_type + '</td><td id="tdSerTax_' + i + '">' + emp.tax_percentage + '%</td><td class="hide" id="tdSerCreatedOn_' + i + '">' + emp.created_on + '</td><td class="hide" id="tdSerDocName_' + i + '">' + emp.doctor_id + '</td><td class="hide" id="tdSerdoctorid_' + i + '">' + $('.txt_doctor_name option:selected').val() + '</td><td class="hide" id="tdSerId_' + i + '">' + emp.master_service_id + '</td><td class="hide" id="tdSerEstId_' + i + '">' + emp.estimation_details_id + '</td><td class="hide" id="tdSerBType_' + i + '">' + emp.base_amount_type + '</td><td class="hide" id="tdSerRMin_' + i + '">' + emp.range_min + '</td><td class="hide" id="tdSerRMax_' + i + '">' + emp.range_max + '</td><td class="hide" id="tdSerReqDetId_' + i + '">' + emp.request_details_id + '</td><td class="hide" id="tdSerIsTax_' + i + '">' + emp.is_tax + '</td><td class="hide" id="tdSerDisType_' + i + '">' + emp.discount_type + '</td>'
                        tr += '<td id="tdSerIsPrice_' + i + '" class="hide">1</td><td class="hide" id="tdSerPack_' + i + '">' + emp.package_id + '</td><td class="hide" id="tdSerReqId_' + i + '">' + emp.request_id + '</td>'
                        tr += '<td id="tdSerDisAmt_' + i + '">' + emp.discount_amount + '</td><td id="tdSerNetAmt_' + i + '">' + emp.net_amount + '</td><td id="tdSerReqDate_' + i + '"></td><td id="tdSerPrefTime_' + i + '"></td><td class="hide" id="tdDayNo_' + i + '">'+ emp.dayno +'</td><td><span class="btn btn-xs btn-primary service_edit mr-10"><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" ><i class="fa fa-trash" aria-hidden="true"></i></span> </td></tr>';
                        $('#estimation_tbl tbody').append(tr);

                    });

                }
                else {
                    console.log(data);
                }

            }
        },
        error: function (data) {

        }
    });

}


//function Show_Insurance() {

//    var Insurancedata = {
//        Dml_Indicator: 'IDS',
//        branchid: $('#pkg_branch_id').val()

//    }

//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/Ipmanagement/AdmitPatient_Ins_Upd_Sel',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(Insurancedata),
//        success: function (data) {
//            var data2 = JSON.parse(data);

//            if (jQuery.isEmptyObject((data2.data))) {

//            }
//            else {

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

//                    var Insurance;
//                    $('#ddInsuranceName').empty();
//                    var default_opt = '<option value="0">--Select--</option>';
//                    $.each(data1, function (i, emp) {

//                        Insurance = Insurance + '<option value="' + emp.master_entity_id + '">' + emp.entity_name + '</option>';

//                    });
//                    $('#ddInsuranceName').append(default_opt + Insurance);

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

//}

function Show_Billing(billingClass) {

    var Billingata = {
        Dml_Indicator: 'BDSE'
        // ,branchid: $('#pkg_branch_id').val()

    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/AdmitPatient_Ins_Upd_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Billingata),
        success: function (data) {
            var data2 = JSON.parse(data);

            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

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

                    var Billing = '';
                    $('#dd_BillingName').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {

                        Billing = Billing + '<option value="' + emp.master_servie_type_id + '">' + emp.master_service_name + '</option>';

                    });
                    $('#dd_BillingName').append(default_opt + Billing);
                    if (billingClass != 0) {
                        $('#dd_BillingName').val(billingClass);
                    }

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

}

$('#Insurance_type').change(function () {
    debugger;
    if ($('#Insurance_type').val() == 1) {
        $('#div_EntityType').removeClass('hide');
        $('#div_BillingName').addClass('hidden');
    }
    else if ($('#Insurance_type').val() == 2) {
        $('#div_BillingName').removeClass('hidden');
        $('#dd_BillingName').val('');
        ClearClaim()
    }
    else {
        $('#div_EntityType').addClass('hide');
        $('#div_BillingName').addClass('hidden');
        $('#dd_BillingName').val('');
        ClearClaim()
    }

});
function ClearClaim() {
    $('#div_EntityType').addClass('hide');
    $('#div_InsuranceName').addClass('hide');
    $('#EntityType_Insurance').removeClass('active');
    $('#EntityType_Corporate').removeClass('active');
    $('#EntityType_Insurance').addClass('not-active');
    $('#EntityType_Corporate').addClass('not-active');
    $('#EntityType').val('');
    $('#HdnEntityid').val('');
    $('#CMultiPay').prop('checked', false);
    $('#divMultiPay').addClass('hide');
    $('#divTPA').addClass('hide');
    $('#MPCIName').empty();
    $('#CMultiPay').val(0);

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

    $('#divMultiPay').show();
    var entity_type = $('#EntityType').val();
    $('#ddInsuranceName').val('');
    $('#div_InsuranceName').removeClass('hide');
    $('#divMultiPay').removeClass('hide');
    $('#divTPA').addClass('hide');
    $('#MPCIName').empty();
    $('#CMultiPay').prop('checked', false);
    $('#CMultiPay').val(0);
    if (entity_type == 1) {
        $('#ins_chk_lbl').html('Indirect');
        $('#ins_sel_lbl').html('TPA<span class="red">*</span>');
        $('.divEmp').addClass('hide');

    }
    else {
        $('#ins_chk_lbl').html('MultiPay');
        $('#ins_sel_lbl').html('Insurance Name<span class="red">*</span>');



    }
});

$('#ddInsuranceName').change(function () {

    $('#hdInsBilling_class').val($('#HdnEntityid').val());
    ServiceAmtChange();
});

$('#dd_BillingName').change(function () {

    $('#hdInsBilling_class').val($('#dd_BillingName').val());
    ServiceAmtChange();
});

$('#ddInsuranceName').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Ipmanagement/AutoEntity',  //+ '&branchid=' + $('#pkg_branch_id').val(),
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, is_insurance: $('#EntityType').val(), entity_name: $('#ddInsuranceName').val() },
            success: function (data) {
                debugger;
                console.log(data);
                var data2 = JSON.parse(data);
                var data = data2.data;
                response($.map(data, function (item) {
                    return { label: item.entity_name, value: item.entity_name, id: item.master_entity_id };
                }))

            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#HdnEntityid').val(ui.item.id);
        Corporate_Insurance($('#HdnEntityid').val(), 0);
        $('#MPCIName').val(0);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }

});
//Load Insurance Name when corporate is choosed
function Corporate_Insurance(Corporateid, CIid) {
    debugger;
    var dml = '', EntityType = $('#EntityType').val();

    if (EntityType == 1) {
        dml = 'PITPA'
    }
    else if (EntityType == 2) {
        dml = 'PCIN'
    }

    var Billingata = {
        Dml_Indicator: dml,
        insurance_id: Corporateid

    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/AdmitPatient_Ins_Upd_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Billingata),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            $('#MPCIName').empty();

            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

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

                    var CInsurance;

                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {

                        CInsurance = CInsurance + '<option value="' + emp.master_entity_billing_id + '">' + emp.entity_name + '</option>';

                    });
                    $('#MPCIName').append(default_opt + CInsurance);

                    if (CIid != '' || CIid != 0) {
                        $('#MPCIName').val(CIid);
                    }


                }
                else {
                    console.log(data);
                }
                var sel = ''
                sel = $('#MPCIName').val();
                if (sel == null) {
                    debugger;
                    $('#divMultiPay').hide();
                    $('#divTPA').hide();
                }
                else {
                    $('#divMultiPay').show();
                    $('#divTPA').show();
                }

            }
        }
    });

}
//Indirect or Multipay onchange
$('#CMultiPay').change(function () {
    debugger;
    this.value = this.checked ? 1 : 0;
    if (this.value == '1') {
        $('#divTPA').removeClass('hide');
    }
    else {
        $('#divTPA').addClass('hide');
        $('#MPCIName').val('');
    }
})
//-----Calculation Part Start----
function AmountCalculation() {
    var Net_Amount = 0, Total_Net_Amount = 0, total_discount = 0;
    $("#estimation_tbl tbody tr").each(function () {
        debugger;
        var id = $(this).prop("id");
        var data_id = $('#' + id).attr("data-id");
        //var discount_type = $(this).find("td").eq(3).html();
        var discount_type = $('#tdSerDis_' + data_id).html();
        var dis_amt = '', dis_type = '', cur_val = '';
        //cur_val = $(this).find("td").eq(4).html();
        cur_val = $('#tdSerAmt_' + data_id).html();

        if (discount_type != '') {
            discount_type = discount_type.split(' ');
            dis_amt = discount_type[0];
            dis_type = discount_type[1];
            if (dis_type == '₹') {
                cur_val = cur_val - dis_amt
            }
            else if (dis_type == '%') {
                cur_val = cur_val - ((cur_val / 100) * dis_amt)
            }
        }
        Total_Net_Amount = parseFloat(Total_Net_Amount) + parseFloat(cur_val);

        Net_Amount = parseFloat(Net_Amount) + parseFloat($('#tdSerAmt_' + data_id).html());

        total_discount = parseFloat(Net_Amount) - parseFloat(Total_Net_Amount);
    });
    $('#net_amount').html(Net_Amount);
    $('#total_net_amount').html(Total_Net_Amount);
    $('#total_discount').html(total_discount);
}
//---Calculation Part Ends-----
//Convert To Bill Concept && Convert To Task Concept
function LoadRequestDetails() {
    debugger;
    // $('.Pdetails_disabled').addClass('disabled');
    $('#div_Service').removeClass('hidden');

    var SCDTbldata = {

        Dml_Indicator: 'LR',
        billing_no: $('#hdnRequestId').val()
    }

    $.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;
                    $("#pkg_branch_id").append('<option value="' + data1.Table[0].branch_id + '">' + data1.Table[0].branch_name + '</option>').attr('disabled', true),
                        $("#visit_type").append('<option value="' + data1.Table[0].visit_type + '">' + data1.Table[0].visit_type_name + '</option>').attr('disabled', true),
                        $("#pkg_branch_id").val(data1.Table[0].branch_id);
                    WardNo(data1.Table[0].Wardid);
                    // $("#ddWard").append('<option value="' + data1.Table[0].Wardid + '">' + data1.Table[0].ward_name + '</option>'),
                    //  $('#net_amount').html(data1.Table[0].total_amount);
                    //$('#total_net_amount').html(data1.Table[0].total_net_amount);
                    //$('#total_discount').html(data1.Table[0].total_discount_amount);
                    $('#txtPaitentSearch_1').val(data1.Table[0].PatientName).attr('disabled', true);
                    $('#hdnpatient_id').val(data1.Table[0].patient_id);
                    $('#hdnpatientid').val(data1.Table[0].patientid);
                    $('#ddWard').attr('disabled', true);
                    let Insurance = (data1.Table[0].is_entity == 1) ? 1 : 2;
                    $('#Insurance_type').val(Insurance);
                    Show_Billing(data1.Table[0].billing_class);
                    $("#dd_BillingName").val(data1.Table[0].billing_class);
                    //$("#dd_BillingName").append('<option value="' + data1.Table[0].billing_class + '">' + data1.Table[0].master_service_name + '</option>'),

                    //$('#txtPaitentSearch_1').val(data1.Table[0].first_name);
                    $('#HdnEntityid').val(data1.Table[0].entity_id);
                    $('#hWard').val(data1.Table[0].Wardid);
                    $('#hbillingClass,#hdInsBilling_class').val(data1.Table[0].billing_class);
                    $('#hInsuranceType').val(Insurance);
                    $('#hBillCount').val(data1.Table[0].billCount);

                    $('#HdnEntityid').val(data1.Table[0].entity_id);
                    $('#EntityType').val(data1.Table[0].is_insurance);
                    $('#Hvisitid').val(data1.Table[0].visit_reportid)


                    if (data1.Table[0].is_entity == 1) {
                        $('#div_EntityType').removeClass('hide');
                        if ($('#EntityType').val() == 1) {
                            $('#EntityType_Insurance').click();
                            Corporate_Insurance($('#HdnEntityid').val(), data1.Table[0].Corporate_Insuranceid);
                        }
                        else {
                            $('#EntityType_Corporate').click()
                        }
                        $('#CMultiPay').val(data1.Table[0].is_MultiPay);
                        if ($('#CMultiPay').val() == 1) {
                            $('#CMultiPay').prop('checked', true);
                            $('#CMultiPay').change()
                        }
                    }
                    else {
                        $('#div_BillingName').removeClass('hidden');
                    }
                    $('#ddInsuranceName').val(data1.Table[0].entity_name);
                    authorized_person();

                    let i = 0;
                    $.each(data1.Table, function (j, emp) {

                        var tax_amount = 0.0;
                        if (emp.is_tax == 1) {
                            tax_amount = (parseFloat(emp.amount)) * (parseFloat(emp.tax_percentage) / 100);
                        }
                        var total_tax = parseFloat(tax_amount);

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

                        var servicereqdate = '';
                        if (emp.dayno != null && emp.dayno != "" && emp.is_casesheet == 1) {
                            //servicereqdate = moment(emp.request_date).format('YYYY-MM-DD');
                            servicereqdate = emp.request_date.split('T')[0].split('-').reverse().join('-');
                        }
                        i = j + 1;
                        var tr = '<tr id="tr_' + i + '" class="number" data-id=' + i + '><td><input type="checkbox" class="chkServices" name="chkrow_' + i + '" /></td><td id="tdSerName_' + i + '">' + emp.service_name + '</td><td id="tdSerQty_' + i + '">' + emp.service_quantity + '</td><td id="tdSerUnit_' + i + '">' + emp.service_quantity_amount + '</td><td id="tdSerAmt_' + i + '">' + emp.amount + '</td>'
                        tr += '<td id="tdSerDis_' + i + '">' + emp.discount + ' ' + sel_discount_type + '</td><td id="tdSerTax_' + i + '">' + emp.tax_percentage + '%</td><td class="hide" id="tdSerCreatedOn_' + i + '">' + emp.created_on + '</td><td class="hide" id="tdSerDocName_' + i + '">' + emp.doctor_id + '</td><td class="hide" id="tdSerdoctorid_' + i + '">' + $('.txt_doctor_name option:selected').val() + '</td><td class="hide" id="tdSerId_' + i + '">' + emp.master_service_id + '</td><td class="hide" id="tdSerEstId_' + i + '">0</td><td class="hide" id="tdSerBType_' + i + '">' + emp.base_amount_type + '</td><td class="hide" id="tdSerRMin_' + i + '">' + emp.range_min + '</td><td class="hide" id="tdSerRMax_' + i + '">' + emp.range_max + '</td><td class="hide" id="tdSerReqDetId_' + i + '">' + emp.request_details_id + '</td><td class="hide" id="tdSerIsTax_' + i + '">' + emp.is_tax + '</td><td class="hide" id="tdSerDisType_' + i + '">' + emp.discount_type + '</td>'
                        tr += '<td id="tdSerIsPrice_' + i + '" class="hide">1</td><td class="hide" id="tdSerPack_' + i + '">' + emp.package_id + '</td><td class="hide" id="tdSerReqId_' + i + '">' + emp.request_id + '</td>'
                        tr += '<td id="tdSerDisAmt_' + i + '">' + emp.discount_amount + '</td><td id="tdSerNetAmt_' + i + '">' + (parseFloat(emp.net_amount) + parseFloat(total_tax)) + '</td><td id="tdSerReqDate_' + i + '">' + servicereqdate + '</td><td id="tdSerPrefTime_' + i + '"></td><td class="hide" id="tdDayNo_' + i + '">' + emp.dayno + '</td><td><span class="btn btn-xs btn-primary service_edit mr-10"><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" ><i class="fa fa-trash" aria-hidden="true"></i></span> </td></tr>';
                        $('#estimation_tbl tbody').append(tr);

                    })

                    AmountCalculation();

                }
                else {
                    console.log(data);
                }

            }
        },
        error: function (data) {

        }
    });
}
//Ward Change
$('#ddWard').change(function () {
    ServiceAmtChange()
})
//Change the Amt of Already Added Service based on new ward/Billing Class
function ServiceAmtChange() {
    debugger;
    var masterServiceId = [];
    $("#estimation_tbl tbody tr").each(function () {
        debugger;
        var id = $(this).prop("id");
        var data_id = $('#' + id).attr("data-id");
        masterServiceId.push($('#tdSerId_' + data_id).html());

    });
    var serviceData = {
        ServiceIds: masterServiceId.toString(),
        Dml_Indicator: 'SA',
        billing_class: $('#hdInsBilling_class').val(),
        ward_id: $("#ddWard").val(),
        billing_type: $('#Insurance_type').val(),
        branch_id: $("#pkg_branch_id").val(),

    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Estimation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(serviceData),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                debugger;
                if (data2.msg == 'Success') {
                    var data1 = data2.data.Table
                    $("#estimation_tbl tbody tr").each(function () {
                        debugger;
                        var id = $(this).prop("id");
                        var data_id = $('#' + id).attr("data-id");
                        var ServiceId = $('#tdSerId_' + data_id).html();
                        var ServiceRow = data1.find((item) => item.master_service_id == ServiceId);
                        $('#tdSerUnit_' + data_id).html(ServiceRow.base_amount);
                        var amount = parseFloat($('#tdSerQty_' + data_id).html()) * parseFloat($('#tdSerUnit_' + data_id).html());

                        var discount = $('#tdSerDisAmt_' + data_id).html();
                        if (parseInt($('#tdSerDisType_' + data_id).html()) != 1) {
                            let dis = $('#tdSerDis_' + data_id).html().split(' ')[0];
                            discount = (parseFloat(amount)) * (parseFloat(dis) / 100);

                        }
                        var taxPercentage = $('#tdSerTax_' + data_id).html();
                        var is_tax = $('#tdSerIsTax_' + data_id).html();
                        var tax_amount = 0.0;
                        if (is_tax == 1) {
                            tax_amount = (parseFloat(amount)) * (parseFloat(taxPercentage) / 100);
                        }
                        (ServiceRow.IsPriceMatrix == '2') ? $('#' + id).addClass('bill-input') : $('#' + id).removeClass('bill-input');

                        $('#tdSerIsPrice_' + data_id).html(ServiceRow.IsPriceMatrix);
                        $('#tdSerAmt_' + data_id).html(parseFloat(amount));
                        $('#tdSerDisAmt_' + data_id).html(parseFloat(discount));
                        $('#tdSerNetAmt_' + data_id).html(parseFloat(amount) + parseFloat(tax_amount) - parseFloat(discount));




                    });
                }

            }
        }
    });
}
//Price Matrix Indication
function PriceMatrixIndication(id1) {
    var color = ''
    if (id1 == 2) {
        color = 'bill-input'
    }

}



//Load visit type
function LoadVisitType() {
    debugger;
    var DoctorData = {
        dml_indicator: 'LVT',
    }
    return $.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);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                debugger;
                $('#visit_type').empty();
                let visit = '';
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var tr = '', hide = '';
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {

                        visit = visit + '<option value="' + emp.visit_typeid + '">' + emp.visit_type_name + '</option>';

                    });

                    $('#visit_type').append(default_opt + visit);

                }
            }
        }
    });
}
//Visit Type Change
$('#visit_type').change(function () {
    //debugger;
    //WardNo($('#visit_type').val(), true);
    ($('#visit_type').val() == 2) ? $('#btnConvertBill,#btnConvertTask,#btnConvertSchedule').hide() : $('#btnConvertBill,#btnConvertTask,#btnConvertSchedule').show();

    if ($('#visit_type').val() == 2) {
        $('#ddWard').find('option:contains("OP")').hide();
        $('#ddWard').find('option:contains("HOMECARE")').hide();
        $('#ddWard').find('option:contains("Healthcare Professional")').hide();
    }
    else {
        $('#ddWard').find('option:contains("OP")').show();
        $('#ddWard').find('option:contains("HOMECARE")').show();
        $('#ddWard').find('option:contains("Healthcare Professional")').show();
    }

})
//Convert To Bill
$('#btnConvertBill').click(function () {
    debugger;
    var bill = EstimateSubmit("bill");
    $.when(bill)
        .then(function (data) {
            debugger;
            var data = JSON.parse(data);
            var id = data.data.Table[0].estimation_no;
            window.location.href = "/BillingMaster/index?EstimateId=" + id + "";

        });
})
//Convert To Task
$('#btnConvertTask').click(function () {
    var bill = EstimateSubmit("bill");
    $.when(bill)
        .then(function (data) {
            debugger;
            var data = JSON.parse(data);
            var id = data.data.Table[0].estimation_no;
            var hosid = data.data.Table[0].hospitalid;
            var patid = data.data.Table[0].patientid;
            var serviceData = {
                estimation_no: id,
                dml_indicator: 'TAL'
            }
            $.ajax({
                async: true,
                type: 'POST',
                url: '/Billing/Estimation',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(serviceData),
                success: function (data) {
                    var data2 = JSON.parse(data);
                    if (jQuery.isEmptyObject((data2.data))) {
                    }
                    else {
                        debugger;
                        if (data2.msg == "Success") {
                            data2 = data2.data.Table;
                            if (data2.length == 0) {
                                toastr.warning("Add CRM Services");
                                $('#shade_slot_submit').hide();
                                $('#btn_submitandPrint,#btnConvertBill,#btnConvertTask,#btn_submit').attr('disabled', false);
                            }
                            else {
                                toastr.success('Converted To Task Successfully');
                                var data = JSON.parse(data);


                                var load_data = {
                                    formid: '64',
                                    branchid: $('#pkg_branch_id').val(),
                                    hospitalid: hosid,
                                    patientid: patid,
                                    Estimationno: id
                                }
                                $.ajax({
                                    async: true,
                                    type: 'POST',
                                    url: '/reports/PrintCrystalReport',
                                    contentType: 'application/json; charset=UTF-8',
                                    data: JSON.stringify(load_data),
                                    success: function (data) {
                                        $('#btn_submit').attr('disabled', false);
                                        $('#btn_submitandPrint').attr('disabled', false);
                                        var byteArray = new Uint8Array(data);
                                        var blob = new Blob([byteArray], { type: "application/pdf" });
                                        var link = window.URL.createObjectURL(blob);
                                        window.open(link, '_blank');
                                        setTimeout(function () {
                                            window.location = "/BillingMaster/estimation_view";
                                        }, 2000);

                                    }
                                });


                            }
                        }
                    }
                }
            });

        });
})

$('#estimation_tbl').on('change', '.chkAllServices', function () {

    var checkstatus = this.checked;
    $('.chkServices').prop('checked', checkstatus);
});

$('#btnConvertSchedule').click(function () {
    //get selected services
    if ($("#estimation_tbl tbody tr").find('.chkServices:checked').length <= 0) {
        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>OK</button>", 'There is no services selected in the list',
            {
                closeButton: true,
                progressBar: true,
                allowHtml: true,
                timeOut: 20000000,

            })
        return false;
    }

    var errorcount = 0;
    //check selected services have request date or not
    $("#estimation_tbl tbody tr").each(function () {
        let id = $(this).prop("id");
        let rowCount = $('#' + id).attr('data-id');

        if ($(this).find("td").eq(0).find('.chkServices').prop('checked')) {
            if (($('#tdSerReqDate_' + rowCount).html() == null || $('#tdSerReqDate_' + rowCount).html() == "") || ($('#tdSerPrefTime_' + rowCount).html() == null || $('#tdSerPrefTime_' + rowCount).html() == "")) {
                errorcount++;
            }
        }
    });

    if (errorcount > 0) {
        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>OK</button>", 'Please select request date and prefer time for the selected services',
            {
                closeButton: true,
                progressBar: true,
                allowHtml: true,
                timeOut: 20000000,

            })
        return false;
    }



    debugger;

    var bill = EstimateSubmit("bill");
    $.when(bill)
        .then(function (data) {
            debugger;
            var data = JSON.parse(data);
            var estimation_no = data.data.Table[0].estimation_no;
            var hosid = data.data.Table[0].hospitalid;
            var patid = data.data.Table[0].patientid;

            var master_service_id = '';
            var selectedrowArray = [];

            $("#estimation_tbl tbody tr").each(function () {
                debugger;
                let id = $(this).prop("id");
                let rowCount = $('#' + id).attr('data-id');
                var isExistsRow = false;
                let originalReqDateTime = $('#tdSerReqDate_' + rowCount).html();
                // let originalPrefTime = $('#tdSerPrefTime_' + rowCount).html();
                let formattedReqDate = formatDateToYYYYMMDD(originalReqDateTime);

                function isValidDate(dateString) {
                    let date = new Date(dateString);
                    return !isNaN(date.getTime());
                }
                function formatDateToYYYYMMDD(dateString) {
                    if (isValidDate(dateString)) {
                        let date = new Date(dateString);
                        let year = date.getFullYear();
                        let month = ('0' + (date.getMonth() + 1)).slice(-2);
                        let day = ('0' + date.getDate()).slice(-2);
                        return `${year}-${month}-${day}`;
                    }
                    let parts = dateString.split(/[-\/]/);
                    if (parts.length === 3) {
                        let day = parts[0];
                        let month = parts[1];
                        let year = parts[2];
                        return `${year}-${month}-${day}`;
                    }

                    return dateString;
                }

                //function formatTimeTo24Hours(timeString) {
                //    debugger;
                //    timeString = timeString.trim().replace(/\s+/g, ' ').replace(/(\d)(\s*:\s*)(\d)/g, '$1:$3');

                //    let timeParts = timeString.match(/(\d{1,2}):(\d{2})\s*(AM|PM)?/i);
                //    if (timeParts) {
                //        let hours = parseInt(timeParts[1], 10);
                //        let minutes = timeParts[2];
                //        let period = timeParts[3];

                //        if (period) {
                //            period = period.toUpperCase();
                //            if (period === 'PM' && hours < 12) {
                //                hours += 12;
                //            }
                //            if (period === 'AM' && hours === 12) {
                //                hours = 0;
                //            }
                //        }

                //        return ('0' + hours).slice(-2) + ':' + minutes;
                //    }

                //    let timeParts24 = timeString.match(/(\d{1,2}):(\d{2})/); 
                //    if (timeParts24) {
                //        let hours = parseInt(timeParts24[1], 10);
                //        let minutes = timeParts24[2];
                //        return ('0' + hours).slice(-2) + ':' + minutes;
                //    }

                //    console.error('Unrecognized time format:', timeString); 
                //    return '00:00';
                //}


                //let formattedPrefTime = formatTimeTo24Hours(originalPrefTime);   





                if ($(this).find("td").eq(0).find('.chkServices').prop('checked')) {

                    //if (selectedrowArray.length > 0) {
                    //    selectedrowArray.forEach(selectedrowArray => {
                    //        if (selectedrowArray.request_date_time.includes($('#tdSerReqDate_' + rowCount).html())) {
                    //            isExistsRow = true;
                    //            var serviceids = selectedrowArray.service_id;
                    //            selectedrowArray.service_id = serviceids + "," + $('#tdSerId_' + rowCount + '').html();
                    //        }
                    //    });
                    //}

                    if (isExistsRow == false) {
                        var customer = {};

                        customer.service_id = $('#tdSerId_' + rowCount).html(),
                            customer.estimation_id = estimation_no,
                            customer.DmlIndicator = 'I',
                            customer.patient_id = $('#hdnpatient_id').val(),
                            customer.request_date_time = formattedReqDate //$('#tdSerReqDate_' + rowCount).html(),
                        customer.branch_id = $('#pkg_branch_id').val(),
                            customer.hospital_id = $('#HospitalId').val(),
                            customer.created_by = $('#hiddenUser_id').val(),
                            customer.prefer_time = $('#tdSerPrefTime_' + rowCount + '').html(),//formattedPrefTime
                            customer.visit_type = $('#visit_type').val(),
                            customer.quantity = $('#tdSerQty_' + rowCount).html(),
                            customer.dayno = $('#tdDayNo_' + rowCount + '').html()
                        selectedrowArray.push(customer);
                    }

                }
            });

            $.ajax({
                async: true,
                type: 'POST',
                url: '/Calender/Schedule_Request_Ins_Upd',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(selectedrowArray),
                success: function (data) {
                    var data2 = JSON.parse(data);
                    if (jQuery.isEmptyObject((data2.data))) {
                    }
                    else {
                        debugger;
                        if (data2.msg == "Success") {
                            data2 = data2.data.Table;
                            if (data2.length == 0) {
                                $('#shade_slot_submit').hide();
                                $('#btn_submitandPrint,#btnConvertBill,#btnConvertTask,#btn_submit').attr('disabled', false);
                            }
                            else {
                                toastr.success('Schedule Request Created Successfully');
                                var data = JSON.parse(data);


                                var load_data = {
                                    formid: '64',
                                    branchid: $('#pkg_branch_id').val(),
                                    hospitalid: hosid,
                                    patientid: patid,
                                    Estimationno: estimation_no
                                }
                                $.ajax({
                                    async: true,
                                    type: 'POST',
                                    url: '/reports/PrintCrystalReport',
                                    contentType: 'application/json; charset=UTF-8',
                                    data: JSON.stringify(load_data),
                                    success: function (data) {
                                        $('#btn_submit').attr('disabled', false);
                                        $('#btn_submitandPrint').attr('disabled', false);
                                        var byteArray = new Uint8Array(data);
                                        var blob = new Blob([byteArray], { type: "application/pdf" });
                                        var link = window.URL.createObjectURL(blob);
                                        window.open(link, '_blank');
                                        setTimeout(function () {
                                            window.location = "/BillingMaster/estimation_view";
                                        }, 2000);

                                    }
                                });

                            }
                        }
                    }
                }
            });

        });
})
