$(document).ready(function () {
    debugger;
    LoadBloodCollection()
    load_Bag_type()
});

//Insert

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

    if ($.trim($('#serial_no').val()) == "") {
        $('#Pserial_no').show();
        $('#Pserial_no').fadeOut(8000);
        $('#Pserial_no').html('Enter Serial No');
        $('#serial_no').focus();
        return false;
    }

    if ($.trim($('#donor_id').val()) == "") {
        $('#Pdonor_id').show();
        $('#Pdonor_id').fadeOut(8000);
        $('#Pdonor_id').html('Enter Donor');
        $('#donor_id').focus();
        return false;
    }
    if ($.trim($('#bag_type').val()) == "") {
        $('#Pbag_type').show();
        $('#Pbag_type').fadeOut(8000);
        $('#Pbag_type').html('Enter Bag Type');
        $('#bag_type').focus();
        return false;
    }

    if ($.trim($('#no_of_units').val()) == "") {
        $('#Pno_of_units').show();
        $('#Pno_of_units').fadeOut(8000);
        $('#Pno_of_units').html('Enter Unit');
        $('#no_of_units').focus();
        return false;
    }

    if ($.trim($('#quantity').val()) == "") {
        $('#Pquantity').show();
        $('#Pquantity').fadeOut(8000);
        $('#Pquantity').html('Enter Quantity');
        $('#quantity').focus();
        return false;
    }
    var date = ''
    if ($('#date').val() != '') {
        var date1 = $('#date').val().split('/');
        date = date1[2] + '-' + date1[1] + '-' + date1[0];
    }

    var indicator = '', bloodcollectionid = ''
    if ($('#btn_bc_Submit').html() == 'Submit') {
        indicator = 'IS',
        bloodcollectionid = 0
    }
    else {
        indicator = 'UP',
        bloodcollectionid = $('#HdBloodid').val()
    }
    var productname = $('#status1').val().toString()
    var submit = {
        Serial_no: $('#serial_no').val(),
        Donor_id: $('#HdDonorid').val(),
        Vendor_name: $('#Hdvendorid').val(),
        Bag_type: $('#bag_type').val(),
        Batch_no: $('#batch_no').val(),
        No_of_units: $('#no_of_units').val(),
        Qty: $('#quantity').val(),
        Date: date,
        Ref_camp: ($('#HdCampid').val() == '' || $('#HdCampid').val() == null) ? 0 : $('#HdCampid').val(),
        Remarks: $('#remarks').val(),
        Test_status: $('#test_status').val(),
        Dml_Indicator: indicator,
        Status: productname,
        Hospital_id: $('#HospitalId').val(),
        Branch_id: '0',
        Created_by: $('#hiddenUser_id').val(),
        Bloodcollection_id: bloodcollectionid
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/BloodBank/insert_update_deleteBloodCollection',
        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;

                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 {
                    toastr.success('Somthing Went Wrong');
                }
            }
            else {
                toastr.success('Somthing Went Wrong');
            }
        },
    });
});

// Load Bag Type
function load_Bag_type(bag1) {
    debugger

    var state = {
        Dml_Indicator: "S"
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/BloodBank/insert_update_deleteBagType',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(state),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var bag;
                    $('#bag_type').empty();
                    $('#a_bag_type').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        bag = bag + '<option value="' + emp.bag_type_id + '">' + emp.bag_type + '</option>';
                    });
                    $('#bag_type').append(default_opt + bag);
                    $('#a_bag_type').append(default_opt + bag);
                }
                else {
                    console.log(data);
                }
                if (bag1 != '' || bag1 != null) {
                    $('#bag_type').val(bag1)
                }
            }
        }
    });
}

//Autocomplete Donor
$('#donor_id').autocomplete({
    source: function (request, response) {
        debugger;
        $.ajax({
            async: true,
            url: "/BloodBank/DonorAutoCompleteData?DName=" + $('#donor_id').val(),
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "DI" },
            success: function (data) {
                debugger;
                console.log(data);
                response($.map(data, function (item) {
                    return { label: item.Donor_name, value: item.Donor_name, id: item.Donor_id };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        debugger;
        $('#HdDonorid').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
})


// Auto complete Bag no
$('#serial_no').autocomplete({
    source: function (request, response) {
        debugger;
        $.ajax({
            async: true,
            url: "/BloodBank/BagNoAutoCompleteData?BNO=" + $('#serial_no').val(),
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "BNI" },
            success: function (data) {
                debugger;
                console.log(data);
                response($.map(data, function (item) {
                    return { label: item.Bag_no, value: item.Bag_no, id: item.Donor_id, name: item.Donor_name };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        debugger;
        $('#HdDonorid').val(ui.item.id);
        $('#donor_id').val(ui.item.name)
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
})



//Autocomplete Vendor
$('#vendor_name').autocomplete({
    source: function (request, response) {
        debugger;
        $.ajax({
            async: true,
            url: "/BloodBank/VendorAutoCompleteData?DName=" + $('#vendor_name').val(),
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "VN" },
            success: function (data) {
                debugger;
                console.log(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) {
        debugger;
        $('#Hdvendorid').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
})

//Autocomplete Camp
$('#ref_camp').autocomplete({
    source: function (request, response) {
        debugger;
        $.ajax({
            async: true,
            url: "/BloodBank/CampAutoCompleteData?DName=" + $('#ref_camp').val(),
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "CN" },
            success: function (data) {
                debugger;
                console.log(data);
                response($.map(data, function (item) {
                    return { label: item.Camp_name, value: item.Camp_name, id: item.Camp_id };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        debugger;
        $('#HdCampid').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
})
$('#btn_filter').click(function () {
    LoadBloodCollection();
})
$('#btnclear').click(function () {
    $('#a_bag_no').val('');
    $('#a_donor_id').val('');
    $('#a_bag_type').val(0);
    $('#a_test_status').val(0);
    $('#txtdate').val('');
    LoadBloodCollection();
})
function LoadBloodCollection() {
    debugger;

    values = {
        Dml_Indicator: "S",
        hospital_id: $('#HospitalId').val(),
        Serial_no: $('#a_bag_no').val(),
        Vendor_name: $('#a_donor_id').val(),
        Bag_type: $('#a_bag_type').val(),
        Test_status: $('#a_test_status').val(),
        Date: $('#txtdate').val()
    }


    $.ajax({
        async: true,
        type: 'POST',
        url: '/BloodBank/insert_update_deleteBloodCollection',
        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_blood_collection tbody').empty();
                    $('#tbl_blood_collection').dataTable().fnClearTable();
                    $('#tbl_blood_collection').dataTable().fnDraw();
                    $('#tbl_blood_collection').dataTable().fnDestroy();

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

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

                        Update = '<a data-toggle="tooltip" title="Update" class="fa fa-edit btn_r mr-5" data-id="" data-type="" data-nav="" data-name=""  href="javascript:void(0);" onclick=BloodCollectUpdate(this,"' + emp.bloodcollection_id + '")><i class="" aria-hidden="true"></i></a>';
                        edit = '<a data-toggle="tooltip" title="Edit" class="btn btn-edit btn-xs" data-id="" data-type="" data-nav="" data-name=""  href="javascript:void(0);" onclick=BloodCollectedit(this,"' + emp.bloodcollection_id + '")><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                        if (emp.test_status == '0') {
                            active_inactive = '<span class="label label-success">Open</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= stsactive(this,"' + emp.Bloodcollection_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">' + Update + '' + edit + '</div></div>';
                        }
                        else if (emp.test_status == '1') {
                            active_inactive = '<span class="label label-warning">Reactive</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= stsactive(this,"' + emp.Bloodcollection_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">' + Update + '' + edit + ' </div></div>';
                        }
                        else if (emp.test_status == '2') {
                            active_inactive = '<span class="label label-danger">Non-Reactive</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= stsactive(this,"' + emp.Bloodcollection_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">' + Update + '' + edit + ' </div></div>';
                        }

                        var s = emp.status.split(",");
                        var Product_Name = '-'

                        if (s.length > 0) {
                            var pat_type = [];
                            for (var m = 0; m < s.length; m++) {
                                if (s[m] != 0) {
                                    pat_type[m] = $("#status1 option[value='" + s[m] + "']").text();
                                }
                                else {
                                    pat_type[m] = '-'
                                }

                            }
                            Product_Name = pat_type.toString();
                            console.log(Product_Name)
                        }

                        tr = tr + '<tr' + j + '"></td><td>' + j + '</td><td>' + emp.date + '</td><td>' + emp.serial_no + '</td><td >' + emp.donor_id + '</td><td >' + emp.bag_type + '</td><td>' + Product_Name + '</td><td >' + emp.qty + '</td><td >' + emp.qty + '</td><td >' + active_inactive + '</td><td>' + other_info + '</td></tr>';

                    });
                    $('#tbl_blood_collection tbody').html(tr);
                    datatable('tbl_blood_collection', 'blood_collection_view', 'Legal');
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function BloodCollectUpdate(event, id) {
    debugger
    $('#form_back').show();
    $('#divtransaction').hide()
    $('#divcollection').show()
    $('#blood_collection_update').show();
    $('#blood_collection_form').show();
    $('#blood_collection_tbl').hide();
    $('#add_blood_collection').hide();
    $('#back_btn').hide();
    $('#status').prop('disabled', false);
    $('#test_status').prop('disabled', false);

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

    $.ajax({
        async: true,
        type: 'POST',
        url: '/BloodBank/insert_update_deleteBloodCollection',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Edit),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            var emp = data1.data.Table;
            $("#serial_no").val(emp[0].serial_no);
            $("#batch_no").val(emp[0].batch_no);
            $("#no_of_units").val(emp[0].no_of_units);
            $("#quantity").val(emp[0].qty);
            $("#date").val(emp[0].date);
            $("#ref_camp").val(emp[0].camp_name);
            $("#test_status").val(emp[0].test_status);
            // $("#status").val(emp[0].status);
            var s = emp[0].status.split(",");
            $('#status1').val(s).trigger('change');
            $("#remarks").val(emp[0].remarks);
            $("#donor_id").val(emp[0].donor_name);
            $("#vendor_name").val(emp[0].printing_name);
            load_Bag_type(emp[0].bag_type);
            $('#HdBloodid').val(emp[0].bloodcollection_id)
            $('#btn_bc_Submit').hide();
            $("#batch_no").attr('disabled', true);
            $("#serial_no").attr('disabled', true);
            $("#bag_type").attr('disabled', true);
            $('#donor_id').attr('disabled', true);
            $("#vendor_name").attr('disabled', true);
            $("#no_of_units").attr('disabled', true);
            $("#quantity").attr('disabled', true);
            $("#date").attr('disabled', true);
            $("#ref_camp").attr('disabled', true);
            $("#test_status").attr('disabled', true);
            $("#status").attr('disabled', true);
            $("#remarks").attr('disabled', true);
            load_test_service()
            LoadBloodTestService()
        }
    })
}

function BloodCollectedit(event, id) {
    debugger
    $('#form_back').show();
    $('#divtransaction').hide()
    $('#divcollection').show()
    $('#blood_collection_update').hide();
    $('#blood_collection_form').show();
    $('#blood_collection_tbl').hide();
    $('#add_blood_collection').hide();
    $('#back_btn').hide();
    $('#status').prop('disabled', false);
    $('#test_status').prop('disabled', false);

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

    $.ajax({
        async: true,
        type: 'POST',
        url: '/BloodBank/insert_update_deleteBloodCollection',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Edit),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            var emp = data1.data.Table;
            $('#btn_bc_Submit').html('Update');
            $("#HdBagid").val(emp[0].serial_no);
            $("#serial_no").val(emp[0].serial_no);
            $("#batch_no").val(emp[0].batch_no);
            $("#no_of_units").val(emp[0].no_of_units);
            $("#quantity").val(emp[0].qty);
            $("#date").val(emp[0].date);
            $("#ref_camp").val(emp[0].camp_name);
            $('#HdCampid').val(emp[0].ref_camp);
            $("#test_status").val(emp[0].test_status);
            var s = emp[0].status.split(",");
            $('#status1').val(s).trigger('change');
            //$("#status").val(emp[0].status);
            $("#remarks").val(emp[0].remarks);
            $("#donor_id").val(emp[0].donor_name);
            $('#HdDonorid').val(emp[0].donor_id);
            $("#vendor_name").val(emp[0].printing_name);
            $('#Hdvendorid').val(emp[0].vendor_name);
            load_Bag_type(emp[0].bag_type);
            $('#HdBloodid').val(emp[0].bloodcollection_id)
            $("#batch_no").attr('disabled', false);
            $("#serial_no").attr('disabled', false);
            $("#bag_type").attr('disabled', false);
            $('#donor_id').attr('disabled', false);
            $("#vendor_name").attr('disabled', false);
            $("#no_of_units").attr('disabled', false);
            $("#quantity").attr('disabled', false);
            $("#date").attr('disabled', false);
            $("#ref_camp").attr('disabled', false);
            $("#test_status").attr('disabled', false);
            $("#status").attr('disabled', false);
            $("#remarks").attr('disabled', false);
            load_test_service()
            LoadBloodTestService()
        }
    })
}

function load_test_service() {
    debugger

    var state = {
        Dml_Indicator: "LTS"
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/BloodBank/insert_update_deleteBloodCollection',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(state),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var bag;
                    $('#test_name').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        bag = bag + '<option value="' + emp.master_service_id + '">' + emp.service_name + '</option>';
                    });
                    $('#test_name').append(default_opt + bag);
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

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

    if ($.trim($('#test_name').val()) == "") {
        $('#Ptest_name').show();
        $('#Ptest_name').fadeOut(8000);
        $('#Ptest_name').html('Select Test Name');
        $('#test_name').focus();
        return false;
    }
    if ($.trim($('#result').val()) == "") {
        $('#Presult').show();
        $('#Presult').fadeOut(8000);
        $('#Presult').html('Select Result');
        $('#result').focus();
        return false;
    }

    var testserviceArray = new Array();

    //  for (j = 0; j < $('#branch').val().length; j++) {
    var Obj = {};

    Obj.Dml_Indicator = 'BTS';
    Obj.bloodcollection_id = $('#HdBloodid').val();
    Obj.test_name = $('#test_name').val();
    Obj.result = $('#result').val()
    Obj.remark = $('#update_remarks').val()
    Obj.hospital_id = $('#HospitalId').val();
    Obj.created_by = $('#hiddenUser_id').val()

    testserviceArray.push(Obj);
    //  }


    $.ajax({
        async: true,
        type: 'POST',
        url: '/BloodBank/bloodservicexml',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(testserviceArray),
        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);
            }
            clear();
            LoadBloodTestService();
        }
    });
});

function LoadBloodTestService() {
    debugger;

    values = {
        Dml_Indicator: "SBT",
        hospital_id: $('#HospitalId').val(),
        Date: '1/1/2022 12:00:00 AM',
        Bloodcollection_id: $('#HdBloodid').val()
    }


    $.ajax({
        async: true,
        type: 'POST',
        url: '/BloodBank/insert_update_deleteBloodCollection',
        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_blood_collection_update_view tbody').empty();
                    $('#tbl_blood_collection_update').dataTable().fnClearTable();
                    $('#tbl_blood_collection_update').dataTable().fnDestroy();

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

                    b = data1.Table;
                    $.each(b, function (i, emp) {
                        j++
                        var testresult = ''
                        if (emp.result == '1') {
                            testresult = 'Reactive'
                        }
                        else {
                            testresult = 'Non-Reactive'
                        }

                        tr = tr + '<tr' + j + '"></td><td>' + j + '</td><td>' + emp.service_name + '</td><td>' + testresult + '</td><td >' + emp.remark + '</td></tr>';

                    });
                    $('#tbl_blood_collection_update_view').html(tr);
                    datatable('tbl_blood_collection_update', 'BloodTest LIST', 'Legal');
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function clear() {
    $('#test_name').val(0);
    $('#result').val(0);
    $('#update_remarks').val('');
}


