$(document).ready(function () {
    debugger;
    LoadBagType();
});
$('#plbag_type').click(function () {
    debugger;
    LoadBagType();
    $('.asidefilterclass').addClass('hidden');
    $('#asideBag_Type').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asideBag_Typeclassgroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asideBag_TypeclassFilterclass').removeClass('hidden');

});
$('#BT_filter').click(function () {
    debugger;

    if ($('#BTFProductName').val() == "") {
        $('#BTFProductName').val(0)
    }
    LoadBagType($('#BTFBagType').val(), $('#BTFProductName').val());
})
$('#BT_clear').click(function () {
    debugger;
    $('#BTFBagType').val('');
    $('#BTFProductName').val('');
    LoadBagType();
})
function LoadBagType(FBagType, FProductName) {
    debugger;

    values = {
        Dml_Indicator: "S",
        hospital_id: $('#HospitalId').val(),
        Bag_type: FBagType,
        Product_id: FProductName
    }


    $.ajax({
        async: true,
        type: 'POST',
        url: '/BloodBank/insert_update_deleteBagType',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(values),
        success: function (data) {
            console.log(data);
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                debugger;
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    $('#tbl_bagtype tbody').empty();
                    $('#tbl_bagtype').dataTable().fnClearTable();
                    $('#tbl_bagtype').dataTable().fnDraw();
                    $('#tbl_bagtype').dataTable().fnDestroy();

                    var j = 0, b = '', tr = '', edit = '', del = '', active_inactive = '', active = '', other_info = '';

                    b = data1.Table;
                    $.each(b, function (i, emp) {
                        j++

                        edit = '<a data-toggle="tooltip" title="Edit" class="btn btn-edit btn-xs" data-id="SM_E1" data-type="role_rights_edit" data-nav="sp_div" data-name="c_details_form"  href="javascript:void(0);" onclick=Bagedit(this,"' + emp.bag_type_id + '")><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                        del = ' <a  data-toggle="tooltip" title="Delete"  id="Bagdel_' + emp.bag_type_id + '" class="btn deleteicon-btn btn-xs"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form"  href="javascript:void(0);" onclick=Bagdel(this,"' + emp.bag_type_id + '","D")><i class="fa fa-trash" aria-hidden="true"></i></a>';
                        // other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + ' ' + del + ' </div></div>';
                        if (emp.status == '1') {
                            active_inactive = '<span class="label label-success">Active</span>';
                            active = '<a  data-toggle="tooltip" title="Make In Active" class="btn btn-xs btn-blue mr-10" href="javascript:void(0);"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form" onclick= Bagdel(this,"' + emp.bag_type_id + '","INACT")><i class="fa fa-minus-square-o mr-5" aria-hidden="true"></i></a>';
                            other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + ' ' + del + ' ' + active + '</div></div>';
                        }
                        else if (emp.status == '2') {
                            active_inactive = '<span class="label label-warning">Inactive</span>';
                            active = '<a  data-toggle="tooltip" title="Make Active" class="btn btn-xs btn-blue mr-10" href="javascript:void(0);"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form" onclick= Bagdel(this,"' + emp.bag_type_id + '","ACT")><i class="fa fa-check-square-o mr-5" aria-hidden="true"></i></a>';
                            other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + del + ' ' + active + '</div></div>';
                        }
                        tr = tr + '<tr' + j + '"><td>' + j + '</td><td>' + emp.bag_type + '</td><td>' + emp.UOM + '</td><td >' + emp.bag_type + '</td><td>' + active_inactive + '</td><td>' + other_info + '</td></tr>';

                    });
                    $('#tbl_bagtype tbody').html(tr);
                    datatable('tbl_bagtype', 'bag_type', 'Legal');

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

$('#bagtypesubmit').on("click", function () {
    debugger;

    if ($.trim($('#bagtype').val()) == "") {
        $('#Pbagtype').show();
        $('#Pbagtype').fadeOut(8000);
        $('#Pbagtype').html('Enter Bag Type');
        $('#bagtype').focus();
        return false;
    }

    var indicator = '', Bagtype_id = ''
    if ($('#bagtypesubmit').html() == 'Submit') {
        indicator = 'IS',
        Bagtype_id = 0
    }
    else {
        indicator = 'UP',
        Bagtype_id = $('#HdBagid').val()
    }

    var submit = {
        Dml_Indicator: indicator,
        Bag_type: $('#bagtype').val(),
        UOM: $('#HdUOMid').val(),
        Hospital_id: $('#HospitalId').val(),
        Created_by: $('#hiddenUser_id').val(),
        Bag_type_id: Bagtype_id,
        Branch_id: '0'
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/BloodBank/insert_update_deleteBagType',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(submit),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                debugger;
                var data2 = data1.data;

                $('#HdBagid').val(data2.Table[0].Last_id)
                var insert_Checkproduct = Checkproduct()
                $.when(insert_Checkproduct)
                    .then(function (data) {
                        debugger
                        if (data2.Table[0].Message == 'Inserted') {
                            toastr.success('Inserted Successfully');
                            //setTimeout(function () {
                            //    location.reload();
                            //}, 1000)
                        }
                        else if (data2.Table[0].Message == 'Updated') {
                            toastr.success('Updated Successfully');
                            //setTimeout(function () {
                            //    location.reload();
                            //}, 1000)
                        }
                        else if (data2.Table[0].Message == 'Already Exist') {
                            toastr.warning('Bag Type Already Exist');
                            //setTimeout(function () {
                            //    location.reload();
                            //}, 1000)
                        }
                        else {
                            toastr.success('Somthing Went Wrong');
                        }
                        $('.nav-tabs li').removeClass('active');
                        $('a[href="#bag_type"]').tab('show');
                        gobackbagtype()
                        LoadBagType();
                    });
            }
            else {
                toastr.success('Somthing Went Wrong');
            }
        },
    });
});

function Checkproduct() {
    debugger

    var productArray = new Array();



    $('input[type="checkbox"]:checked').each(function () {
        var Obj = {};

        Obj.Dml_Indicator = 'BP';
        Obj.Bag_type_id = $('#HdBagid').val();
        Obj.Product_id = $(this).val();
        Obj.Bag_type = $(this).closest('tr').find('td:nth-child(2)').text();
        Obj.created_by = $('#hiddenUser_id').val();

        productArray.push(Obj);
    });


    return $.ajax({
        async: true,
        type: 'POST',
        url: '/BloodBank/productxml',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(productArray),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {

                }
            }
            else {
                console.log(data1);
                toastr.success('Somthing Went Wrong');
                return;
            }
        }
    });
};


$('#bagtypeuom').autocomplete({
    source: function (request, response) {
        debugger
        $.ajax({
            async: true,
            url: "/BloodBank/VendorAutoCompleteData?DName=" + $('#bagtypeuom').val(),
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "UOM" },
            success: function (data) {
                response($.map(data, function (item) {
                    return { label: item.Printing_name, value: item.Printing_name, id: item.Vendor_master_id };
                }));
            },
        });
    },
    minLength: 1,
    select: function (event, ui) {
        $('#HdUOMid').val(ui.item.id);
    },
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);
    }
});

function Bagedit(event, id) {
    debugger
    //$('#form_back').show();
    //$('#bagtype_form').show();
    //$('#bagtype_table_div').hide();
    $('#bagtype_form').show();
    $('#bagtype_table_div').hide();
    $('#divmaster').hide();
    $('#regtab').hide();
    $('#divbagtype').show();

    $('#bagtypesubmit').html('Update')


    var Edit = {
        Bag_type_id: id,
        Dml_Indicator: 'E'
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/BloodBank/insert_update_deleteBagType',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Edit),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            var emp = data1.data.Table;
            var emp1 = data1.data.Table1;
            $("#bagtype").val(emp[0].bag_type);
            $("#bagtypeuom").val(emp[0].unit_name);
            $('#HdUOMid').val(emp[0].UOM);
            $('#HdBagid').val(emp[0].bag_type_id);
            $.each(emp1, function (i, a) {
                $('#check' + a.product_id + '').prop('checked', true);
                $('#check' + a.product_id + '').val(a.product_id);
            });

        }
    })
}

function Bagdel(event, val, Dml_Indicator) {
    debugger;

    var status = "";
    if (Dml_Indicator == 'ACT') {
        status = "Are You Sure, Do you Want to Active the Bag Type?";
    }
    else if (Dml_Indicator == 'INACT') {
        status = "Are You Sure, Do you Want to In-active the Bag Type?";
    }
    else if (val != '') {

        status = "Are You Sure, Do you want to Delete?";
    }
    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>", status,
{

    closeButton: true,
    progressBar: true,
    allowHtml: true,
    timeOut: 20000000,

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

            var servicevalues = {
                Bag_type_id: val,
                Dml_Indicator: Dml_Indicator

            }


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

                    var data2 = JSON.parse(data);


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

                    }
                    else {

                        if (data2.msg == "Success") {
                            debugger;
                            data1 = data2.data;
                            if (Dml_Indicator == 'D') {
                                toastr.success("Deleted Successfully ");
                                LoadBagType();

                            }
                            else if (Dml_Indicator == 'ACT') {
                                toastr.success("Activated Successfully");
                                LoadBagType();
                            }
                            else if (Dml_Indicator == 'INACT') {
                                toastr.success("In-activated Successfully");
                                LoadBagType();

                            }
                            else {
                                toastr.warning("Somthing Went Wrong");
                                return false;
                            }
                        }
                    }
                }
            });
        });
    }
});
}

function clearbag() {
    $('#bagtype').val('')
    $('#bagtypeuom').val('')
    $('.check').prop('checked', false);
}
