$(document).ready(function () {
    LoadInsuranceClaim()
    LoadBank()
});

var selectedRowId;
$("#role_create").click(function () {
    role_create();
});
//Insurance Autocomplete
$('#ddInsuranceName').autocomplete({

    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Ipmanagement/AutoEntity',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, is_insurance: $('#EntityType').val(), entity_name: $('#ddInsuranceName').val(), branchid: $('#SelBranch').val(), is_entity: $('#HdnIsTpa').val() },
            success: function (data) {
                $('#HdnEntityid').val('');
                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, type: item.entity_type };
                }))

            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        debugger
        $('#HdnEntityid').val(ui.item.id);
        $('#HdnEntitytype').val(ui.item.type);
        //   entitychange()
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }

});

$('#ChkID').change(function () {
    debugger
    var is_tpa;
    if ($("#ChkID").prop('checked') == true) {
        is_tpa = '1';
    }
    else {
        is_tpa = '0';
    }
    $('#HdnIsTpa').val(is_tpa)
})

//function entitychange() {
//    debugger
//   var entitytype = $('#HdnEntitytype').val()
//   if (entitytype == 1) {
//       $('#divtpa').show()
//       LoadTPA()
//    }
//else{
//       $('#divtpa').hide()
//}
//}

//function LoadTPA(tpaid) {
//    var tpa_data = {
//        P_Dml_Indicator: 'ICTPA',
//        amount: $('#HdnEntityid').val()
//    }
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/InsuranceClaim/InsClaimDetail',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(tpa_data),
//        success: function (data) {
//            var data = JSON.parse(data);
//            if (data.msg == "Success") {
//                var data1 = data.data.Table;            
//                console.log(data1);
//                if (jQuery.isEmptyObject((data))) {
//                }
//                else {

//                    $('#ddtpa').empty();
//                    var service1 = '';
//                    var default_opt = '<option value="0">--Select--</option>';

//                    $.each(data1, function (i, emp) {
//                        service1 = service1 + '<option value="' + emp.tpa_id + '">' + emp.name + '</option>';
//                    });
//                    $('#ddtpa').append(default_opt + service1);

//                    if (tpaid != 0 || tpaid != null) {
//                        $('#ddtpa').val(tpaid)
//                    }
//                }
//            }
//            else {
//                console.log(data1);
//            }
//        }
//    })
//}

//UTR Claim Insert/Update
function role_create() {
    var receiptdate = $("#receiptdate").val().trim();
    var bankname = $("#bankname").val();
    var utrnumber = $("#utrnumber").val().trim();
    var ddInsuranceName = $('#HdnEntityid').val();
    var amount = $("#amount").val().trim();
    var createdBy = $("#hiddenUser_id").val();

    if (receiptdate === '') {
        $("#Preceiptdate").show();
        $("#Preceiptdate").html("Please enter receipt date").fadeOut(8000);
        $('#receiptdate').focus();
        return false;
    }

    if (!bankname) {
        $("#Pbankname").show();
        $("#Pbankname").html("Please enter bank name").fadeOut(8000);
        $('#bankname').focus();
        return false;
    }

    if (utrnumber === '') {
        $("#Putrnumber").show();
        $("#Putrnumber").html("Please enter UTR number").fadeOut(8000);
        $('#utrnumber').focus();
        return false;
    }

    if (!ddInsuranceName || !$('#ddInsuranceName').val()) {
        $("#PddInsuranceName").show();
        $("#PddInsuranceName").html("Please select insurance").fadeOut(8000);
        $('#PddInsuranceName').focus();
        return false;
    }

    if (amount === '') {
        $("#Pamount").show();
        $("#Pamount").html("Please enter amount").fadeOut(8000);
        $('#amount').focus();
        return false;
    }
    var is_tpa;
    if ($("#ChkID").prop('checked') == true) {
        is_tpa = '1';
    }
    else {
        is_tpa = '0';
    }
    debugger;
    var InsClaim = {
        P_Dml_Indicator: selectedRowId ? "ICU" : "ICI",
        receiptdate: $("#receiptdate").val(),
        bankname: $("#bankname").val(),
        utrnumber: $("#utrnumber").val(),
        insurance: $('#HdnEntityid').val(),
        amount: $("#amount").val(),
        //createdon: selectedRowId ? undefined : new Date(),
        id: selectedRowId,
        createdby: $('#hiddenUser_id').val(),
        tpaid: is_tpa
        //modifiedby: selectedRowId ? $("#hiddenUser_id").val() : undefined  //commented by Tharuni
    };

    $.ajax({
        type: "POST",
        url: '/InsuranceClaim/InsClaimDetail',
        data: InsClaim,
        success: function (response) {
            console.log(response);
            var data1 = JSON.parse(response);
            if (data1.msg == "Success") {
                var data2 = data1.data.Table[0]
                if (data2.msg == "insert successfully") {
                    toastr.success('Inserted Successfully')
                }
                else if (data2.msg == "Update Successful") {
                    toastr.success('Updated Successfully')
                }
                else {
                    toastr.warning('Something went wrong')
                }
            }
            //commented by Tharuni
            //if (selectedRowId) {
            //    var row = $("tr[data-id='" + selectedRowId + "']");
            //    row.find("td:eq(2)").text(receiptdate);
            //    row.find("td:eq(3)").text(bankname);
            //    row.find("td:eq(4)").text(utrnumber);
            //    row.find("td:eq(5)").text(ddInsuranceName);
            //    row.find("td:eq(6)").text(amount);
            //} 

            $("#receiptdate").val("");
            $("#bankname").val("");
            $("#utrnumber").val("");
            $("#ddInsuranceName").val("");
            $("#amount").val("");
            $("#ChkID").prop("checked", false);
            //$('#ddtpa').val("")
            //$('#divtpa').hide()
            selectedRowId = undefined;
            $("#role_create").text("Save")
            $("#amount").attr('disabled', false);
            LoadInsuranceClaim()

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

}
//Laod UTR Data
function LoadInsuranceClaim() {
    debugger;
    var InsClaimDetail = {
        P_Dml_Indicator: "ICS",
        //receiptdate: $("#receiptdate").val(),
        //bankname: $("#bankname").val(),
        //utrnumber: $("#utrnumber").val(),
        //insurance: $('#ddInsuranceName').val(),
        //amount: $("#amount").val()
    };
    debugger;
    $.ajax({
        type: "POST",
        url: '/InsuranceClaim/InsClaimDetail',
        contentType: 'application/json',
        data: JSON.stringify(InsClaimDetail),
        success: function (data) {

            var InsuranceCD = JSON.parse(data);

            $('#insuranceclaim_body').empty();
            $('#insuranceclaim').dataTable().fnClearTable();
            $('#insuranceclaim').dataTable().fnDraw();
            $('#insuranceclaim').dataTable().fnDestroy();

            InsuranceCD = InsuranceCD.data.Table
            var $insuranceclaim_body = $("#insuranceclaim");
            debugger;
            for (var i = 0; i < InsuranceCD.length; i++) {
                //commented by Tharuni
                //var receiptdate = new Date(InsuranceCD[i].receiptdate);
                //var day = receiptdate.getDate().toString().padStart(2, '0');
                //var month = (receiptdate.getMonth() + 1).toString().padStart(2, '0');
                //var year = receiptdate.getFullYear();
                //var formattedBillDate = day + '/' + month + '/' + year;
                var row = "<tr id=row_" + (i + 1) + ">" +
                    "<td>" + (i + 1) + "</td>" +
                    "<td style='display:none;' id=claimid_" + (i + 1) + ">" + InsuranceCD[i].id + "</td>" +
                    //"<td style='display:none;' id=tpaid_" + (i + 1) + ">" + InsuranceCD[i].tpaid + "</td>" +
                    "<td id=tpaid_" + (i + 1) + " style='display:none;'>" + InsuranceCD[i].tpaid + "</td>" +
                     "<td id=receiptdate_" + (i + 1) + ">" + InsuranceCD[i].receiptdate + "</td>" +
                    "<td data-id=" + InsuranceCD[i].bankid + " id=bankname_" + (i + 1) + ">" + InsuranceCD[i].bankname + "</td>" +
                    "<td id=utrnumber_" + (i + 1) + ">" + InsuranceCD[i].utrnumber + "</td>" +
                    "<td data-id=" + InsuranceCD[i].insurance + " id=insurance_" + (i + 1) + ">" + InsuranceCD[i].insurance_name + "</td>" +
                    "<td id=amount_" + (i + 1) + ">" + InsuranceCD[i].amount + "</td>" +
                     "<td id=collectedamount_" + (i + 1) + ">" + InsuranceCD[i].CollectedAmount + "</td>" +
                     "<td id=balaceamount_" + (i + 1) + ">" + (parseFloat(InsuranceCD[i].amount) - parseFloat(InsuranceCD[i].CollectedAmount)) + "</td>" +
                   "<td class='tbl-action'>" +
       "<div class='disp_if'>" +
            "<button class='btn btn-sm btn-primary btn-edit' data-id='" + InsuranceCD[i].id + "' title='Edit' onclick=claimEdit(" + (i + 1) + ")><i class='fa fa-pencil fa-xs'></i></button>&nbsp;" +
            "<button class='btn btn-sm btn-danger btn-delete' data-id='" + InsuranceCD[i].id + "' title='Delete'  onclick=claimDelete(" + (i + 1) + ")><i class='fas fa-trash-alt fa-xs'></i></button>" +
        "</div>" + "</td>" + "</tr>";
                $insuranceclaim_body.append(row);
            }

            datatable('insuranceclaim', 'Insclamd', 'Legal');
        },
        error: function (error) {
            console.log(error);
        }
    });
}
//UTR Delete   
function claimDelete(row) {
    debugger;
    var id = $('#claimid_' + row).text();
    //Added By Tharuni
    var CollectedAmount = $('#collectedamount_' + row).html();
    if (parseFloat(CollectedAmount) > 0) {
        toastr.warning('Amount Collected.Unable To Delete');
        return false;
    }
    else {
        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes</button><button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No</button>", 'Are you sure want to delete?',
    {
        closeButton: true,
        progressBar: true,
        allowHtml: true,
        timeOut: 20000000,

        onShown: function (toast) {
            $("#confirmationRevertYes").click(function () {


                var Insdel = {
                    P_Dml_Indicator: "ICD",
                    id: id,
                };

                $.ajax({
                    type: "POST",
                    url: '/InsuranceClaim/InsClaimDetail',
                    data: Insdel,
                    success: function (response) {
                        console.log(response);
                        // location.reload();
                        LoadInsuranceClaim();
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            })
            $("#confirmationRevertNo").click(function () {

            })
        }
    })
    }

}

//UTR Edit-changed By Tharuni
function claimEdit(id) {

    debugger;
    selectedRowId = $('#claimid_' + id).text();
    var receiptdate = $('#receiptdate_' + id).text();
    var bankname = $('#bankname_' + id).text();
    var bankid = $('#bankname_' + id).attr('data-id');
    var utrnumber = $('#utrnumber_' + id).text();
    var ddInsuranceName = $('#insurance_' + id).text();
    var ddInsuranceId = $('#insurance_' + id).attr('data-id');
    var amount = $('#amount_' + id).text();
    var CollectedAmount = $('#collectedamount_' + id).text();
    var tpaid = $('#tpaid_' + id).text();

    //var InsuranceS = {
    //    id: selectedRowId,
    //    receiptdate: receiptdate,
    //    bankname: bankname,
    //    utrnumber: utrnumber,
    //    ddInsuranceName: ddInsuranceName,
    //    amount:amount
    //};

    $("#receiptdate").val(receiptdate);
    $("#bankname").val(bankid);
    $("#utrnumber").val(utrnumber);
    $("#ddInsuranceName").val(ddInsuranceName);
    $("#amount").val(amount);
    $('#HdnEntityid').val(ddInsuranceId);
    (parseFloat(CollectedAmount) > 0) ? $("#amount").attr('disabled', true) : ''


    if (tpaid != '0') {
        $("#ChkID").prop("checked", true);
    }
    else {
        $("#ChkID").prop("checked", false);
    }

    $("#role_create").text("Update");
}

//Loading Bank Type-Added by Tharuni
function LoadBank() {
    var receipt_data = {
        Dml_Indicator: 'PL',
        branch_id: $('#pkg_branch_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Billing_Receipt',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(receipt_data),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data1 = data.data.Table;
                var data2 = data.data.Table1;
                console.log(data1);
                if (jQuery.isEmptyObject((data))) {
                }
                else {

                    $('#bankname').empty();
                    var Service = '', service1 = '';
                    var default_opt = '<option value="0">--Select--</option>';

                    $.each(data2, function (i, emp) {
                        service1 = service1 + '<option value="' + emp.master_servie_type_id + '">' + emp.master_service_name + '</option>';
                    });
                    $('#bankname').append(default_opt + service1);
                }
            }
            else {
                console.log(data1);
            }
        }
    })
}

