/** for organism & antibiotic assignment */

var selectedOrgId = [];
let antibiotics = [];

var anti_payload = []


getAntibiotic()

/** organism & antibiotic assignment */

$("#btnSave").on('click',function(e){
    e.preventDefault();
    data_id = $('#data-id').val();
    let url = test_sample_base_url.toString() + (parseInt(data_id) == 0 ? '.save' : '.update').toString();
    anti_payload = []
    $('table #selected-organism').find("tr").each(function () {
        let selected_organism = $(this).find("td input.selected-organism-item").val();
        let is_default = parseInt($(this).find("td input.is_default:checked").val());
        let antis = $(this).find("td select.selected-antibiotics").val();

        var payload_item = {'id' : selected_organism, 'is_default': is_default = (is_default || 0) + 0, 'anti_ids' : antis}
        anti_payload.push(payload_item)

    });
    $.ajax({
        url: url,
        type:"POST",
        data :{
            "_token": csrf_token,
            uid : data_id,
            test_id: $('#test-item').val(),
            sample_type_id: $('#sample-type-id').val(),
            code: $('#code').val(),
            heading_id: $('#heading-id').val(),
            group_result: $('#group-result').val(),
            unit_sign: $('#unit-sign').val(),
            usd_price: $('#usd-price').val(),
            weight: $('#weight').val(),
            filed_type_id: $('#field-type-id').val(),
            patient_type_ids: $('select[name="patient_type_ids"]').serializeArray(),
            min_values: $('input[name="min_values"]').serializeArray(),
            signs: $('input[name="signs"]').serializeArray(),
            max_values: $('input[name="max_values"]').serializeArray(),
            organisms : anti_payload,
            formula: $('#formula').val(),
            format_value: $('#format').val(),
            description: $('#description').val(),
            is_bold: $('#is-bold').is(":checked") ? 1 : 0
        },
        success:function(res){
            handleMessage(res.success, res.message)
            if(res.success) setTimeout(function () {location.reload()}, messageDuration)
        },
        error: function(response) {
            customErrorAlert(response)
        },
    });
});

function delete_data(uid){
    Swal.fire({
        text: confirm_delete_record,
        icon: 'question',
        showCancelButton: true,
        cancelButtonClass:'danger',
        confirmButtonText: confirm_ok_delete,
        cancelButtonText: confirm_cancel
    }).then((result) => {
        if (result.value) {
        $.ajax({
            url: test_sample_base_url.toString() + '.delete',
            type:"POST",
            data:{
                "_token": csrf_token,
                uid : uid,
            },
            success:function(res){
                handleMessage(res.success, res.message)
                if(res.success) setTimeout(function () {location.reload()}, messageDuration)
            },
            error: function(response) {
            },
        });
        }
    });
}

function restore_data(uid){
    Swal.fire({
        text: confirm_restore_record,
        icon: 'question',
        showCancelButton: true,
        cancelButtonClass:'danger',
        confirmButtonText: 'Ok, Restore',
    }).then((result) => {
        $.ajax({
            url: test_sample_base_url.toString() + '.restore',
            type: "POST",
            data: {
                "_token": csrf_token,
                uid: uid,
            },
            success: function (res) {
                handleMessage(res.success, res.message)
                if(res.success) setTimeout(function () {location.reload()}, messageDuration)
            },
            error: function (response) {
            },
        });
    });
}


$('#modal-test').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget) // Button that triggered the modal
    var action = button.data('action') // Extract info from data-* attributes
    var modal = $(this);
    $('.modal-body input[name="checkFilter"]').prop( "checked", false);
    if(action === "new"){
        // Clear inputs
        modal.find('.modal-body input').val("");
        modal.find('.modal-body textarea[name="description"]').val("");
        modal.find('.modal-body select[name="filed_type_id"]').val("").change();
        getDepartment(0)
        modal.find('.modal-body select[name="sample_type_id"]').val("").trigger('change');
        modal.find('.modal-body select[name="test_item"]').val("").trigger('change');
        modal.find('.modal-body input[name="uid"]').val(0);
        $('#reference-range-table tbody').empty();
        $('#is-bold').prop('checked', false)
    }else if(action === "edit"){
        uid = button.data('uid');
        modal.find('.modal-body input[name="uid"]').val(uid);
        $('#reference-range-table tbody').empty();
        $.ajax({
            url: test_sample_base_url.toString() + '.get',
            type:"POST",
            data:{
                "_token": csrf_token,
                uid: uid,
            },
            success:function(res){
                if(res.success){
                    
		            
                    let data = res.data;
                    
                    if(data.is_bold==0) $('#is-bold').prop('checked', false)
		            else $('#is-bold').prop('checked', true)
		            
                    modal.find('.modal-body select[name="test_item"]').val(data.test_id).trigger('change');
                    getDepartment(data.sample_type.department_id)
                    getSampleTypeByDepartmentId(data.sample_type.department_id, 'sample-type-id', data.sample_type.id)
                    getHeadingItems('heading-id', data.sample_type.id, data.heading_id)
                    modal.find('.modal-body select[name="filed_type_id"]').val(data.field_type).change();
                    modal.find('.modal-body input[name="group_result"]').val(data.group_result);
                    modal.find('.modal-body input[name="unit_sign"]').val(data.unit_sign);
                    modal.find('.modal-body input[name="code"]').val(data.code);
                    modal.find('.modal-body input[name="weight"]').val(data.weight);
                    modal.find('.modal-body select[name="format_value"]').val(data.format);
                    modal.find('.modal-body input[name="usd_price"]').val(data.usd_price);
                    if(data.field_type == 2 || data.field_type == 3){
                        getOrganisms()
                        $('#selected-organism').empty()
                        selectedOrgId = []
                        data.selected_organisms.map(item=>{
                            let _name = item.organism.name_en
                            let _id = item.organism.id

                            selectedOrgId.push(_id)

                            let tr = document.createElement('TR');
                            tr.setAttribute('id', 'organ_'+_id);
                            tr.insertCell(0).innerHTML = '<div class="form-check font-13"><label class="form-check-label font-13" style="width: 50%;"><input id="selected-org-'+_id+'" name="selected_organisms" type="checkbox" data-name="'+_name+'" value="'+_id+'" class="form-check-input selected-organism-item"> '+_name+' <i class="input-helper"></i></label></div>';
                            tr.insertCell(1).innerHTML = '<input name="is_defaults" '+(item.is_default==1? 'checked':'')+' class="is_default" value="1" type="radio" />';
                            tr.insertCell(2).setAttribute('id', 'org_'+ _id)
                            tr.cells[0].classList.add('py-1', 'font-13');
                            tr.cells[1].classList.add('py-1', 'text-center','font-13');
                            tr.cells[2].classList.add('py-1', 'text-center','font-13')

                            $('#selected-organism').append(tr);

                            renderAntiSelection('org_'+ _id , item.antibiotics)

                        
                        })
                        
                        $(".select2-multiple").select2({
                                placeholder: " select antibiotics",
                                closeOnSelect : false,
                            });
                            
                    }
                    if((data.field_type == 1 || data.field_type == 4) && data.test_values.length){
                        // load test normal values
                        data.test_values.map(tnvItem =>{
                            addRefRangeRow(tnvItem.patient_type_id,tnvItem.minimum, tnvItem.maximum, tnvItem.sign)
                        })
                    }
                    modal.find('.modal-body input[name="formula"]').val(data.formula);
                    modal.find('.modal-body input[name="format_value"]').val(data.format);
                    modal.find('.modal-body textarea[name="description"]').val(data.description);
                }
                else handleMessage(res.success, res.message)

            },
            error: function(response) {
            },
        });
    }
})


function addNewTest(patientElementId){
    Swal.fire({
        html:"<p style='float: left;'>Test Name</p>",
        input: "text",
        showCancelButton: !0,
        confirmButtonText: "<i class='fa fa-save mr-2'></i>Save",
        cancelButtonText: "Cancel",
        showLoaderOnConfirm: !1,
        confirmButtonColor: "#844fc1",
        cancelButtonColor: "#cbcbcb",
        preConfirm: function (n) {
            return new Promise(function (t) {
                $.ajax({
                    url: test_base_url + '.save',
                    method:'post',
                    dataType:'json',
                    data:{
                        "_token": csrf_token,
                        name_en: n
                    },
                    success:function(r)
                    {
                        if(r.success !== true){
                            Swal.showValidationMessage('Failed while saving test name. ' + r.errors)
                            Swal.enableButtons()
                        }
                        else t(r.data)
                    }
                })
            })
        },
        allowOutsideClick:!1,
    }).then(function (t) {
        if(!t.dismiss){
            t.value.map(item =>{
                var patientOption = document.createElement('OPTION');
                patientOption.setAttribute('value',item.id);
                patientOption.setAttribute('selected','selected');
                patientOption.text = item.name_en;
                $('#'+patientElementId).append(patientOption);
            })
        }
    })
}

function editTestName(testId,oldName, patientElementId){
    Swal.fire({
        html:"<p style='float: left;'>Test Name</p>",
        input: "text",
        inputValue: oldName,
        showCancelButton: !0,
        confirmButtonText: "<i class='fa fa-save mr-2'></i>Save",
        cancelButtonText: "Cancel",
        showLoaderOnConfirm: !1,
        confirmButtonColor: "#844fc1",
        cancelButtonColor: "#cbcbcb",
        preConfirm: function (n) {
            return new Promise(function (t) {
                $.ajax({
                    url: test_base_url + '.update',
                    method:'post',
                    dataType:'json',
                    data:{
                        "_token": csrf_token,
                        uid: testId,
                        name_en: n
                    },
                    success:function(r)
                    {
                        if(r.success !== true){
                            Swal.showValidationMessage('Failed while saving test name. ' + r.errors)
                            Swal.enableButtons()
                        }
                        else t(r.data)
                    }
                })
            })
        },
        allowOutsideClick:!1,
    }).then(function (t) {
        if(!t.dismiss){
            t.value.map(item =>{
                var patientOption = document.createElement('OPTION');
                patientOption.setAttribute('value',item.id);
                patientOption.setAttribute('selected','selected');
                patientOption.text = item.name_en;
                $('#'+patientElementId).append(patientOption);
            })
        }
    })
}

$('#department-id-search-form').change(function () {
    var departmentId = $(this).val()
    getSampleTypeByDepartmentId(departmentId, 'sample-type-id-search-form');
})

$('#department-id').change(function () {
    var departmentId = $(this).val()
    getSampleTypeByDepartmentId(departmentId, 'sample-type-id');
})


$('#modal-test-sample-formula').on('show.bs.modal', function (event) {
    let modal = $(this);
    modal.find('.modal-body select[name="department_id"]').val("0").trigger('change');
    modal.find('.modal-body select[name="sample_type_id"]').val("").trigger('change');
    modal.find('.modal-body select[name="test_sample_id"]').val("").trigger('change');
})

$('#test-sample-formula-department-id').change(function () {
    var departmentId = $(this).val()
    getSampleTypeByDepartmentId(departmentId, 'test-sample-formula-sample-type-id');
})

$('#test-sample-formula-sample-type-id').change(function () {
    var sample_type_id = $(this).val()
    getHeadingItems('test-sample-formula-heading-id', sample_type_id, 0, "")
})

$('#modal-test-sample-formula #btnAdd2Formula').click(function () {
    // change for formula base on test id on 22-Jun-2023
    //let testSampleId = $('#test-sample-formula-heading-id').val()
    let testSampleId = $('#test-sample-formula-heading-id option:selected').attr('test_id')
    insertEquation('T'+testSampleId, 'formula')
    $('#close-modal-test-sample-formula').click()
})

function getDepartment(selected_department_id = 0) {
    $.ajax({
        url: get_refs_base_url+'/department',
        type:"GET",
        dataType:"JSON",
        success:function(response){
            $('#department-id').html('');
            $('#department-id').append('<option></option>');
            response.data.map(item =>{
                var patientOption = document.createElement('OPTION');
                patientOption.setAttribute('value',item.id);
                if(selected_department_id == item.id){
                    patientOption.setAttribute('selected','selected');
                }
                patientOption.text = item.name_en;
                $('#department-id').append(patientOption);
            })
        },
        error: function(response) {
        },
    });
}

$('#field-type-id').change(function () {
    var fieldTypeId = $(this).val()

    switch (parseInt(fieldTypeId)) {
        case 1:
            $('#reference-range').css('display','block')
            //$('#hide-beside-2-4').css('display','block')
            $('#formula-input-area').css('display','none')
            $('#format-input-area').css('display','block')
            $('#options').css('display','none')
            $('#description-input-area').removeClass('col-sm-4')
            $('#description-input-area').removeClass('col-sm-12')
            $('#description-input-area').addClass('col-sm-8')
            break
        case 2:
        case 3:
            $('#reference-range').css('display','none')
            //$('#hide-beside-2-4').css('display','none')
            $('#options').css('display','block')
            if($('#data-id').val()==0){
                getOrganisms();
                getAntibiotic();
            }
            $('#description-input-area').removeClass('col-sm-8')
            $('#description-input-area').removeClass('col-sm-4')
            $('#description-input-area').addClass('col-sm-12')

            $('#formula-input-area').css('display','none')
            $('#format-input-area').css('display','none')

            break
        case 4:
            $('#description-input-area').removeClass('col-sm-12')
            $('#description-input-area').removeClass('col-sm-8')
            $('#description-input-area').addClass('col-sm-4')
            //$('#hide-beside-2-4').css('display','block')
            $('#reference-range').css('display','block')
            $('#options').css('display','none')

            $('#formula-input-area').css('display','block')
            $('#format-input-area').css('display','block')
            //$('#format-input-area').css('display','none')

            break;
        default:
            $('#reference-range').css('display','none')
            //$('#hide-beside-2-4').css('display','none')
            $('#formula-input-area').css('display','none')
            $('#format-input-area').css('display','none')
            $('#options').css('display','none')
            $('#description-input-area').removeClass('col-sm-8')
            $('#description-input-area').addClass('col-sm-12')
            break
    }
})

function addRefRangeRow(patient_type_id = 0, min=0, max = 0, sign='' ){
    var id = 'ref-val-' + (Math.floor(Math.random() * (1000 - 100)) + 100) + (Math.floor(Math.random() * (99)) + 1)
    if($('#reference-range-table tbody tr').length){
        var $lastRow = $("[id$=reference-range-table] tr:not('.ui-widget-header'):last"); //grab row before the last row
        var $newRow = $lastRow.clone().prop({id: id}); //clone it
        $newRow.find('td:last').addClass('py-0 text-center').html('<button type="button" class="btn btn-sm btn-inverse-danger " onclick="removeRefRangeRow(\'' + id + '\')"><i class="mdi mdi-close-circle"></i></button>');
        $newRow.find('select[name="patient_type_ids"]').val(patient_type_id); //clear out textbox values
        $newRow.find('input[name="min_values"]').val(min); //clear out textbox values
        $newRow.find('input[name="signs"]').val(sign); //clear out textbox values
        $newRow.find('input[name="max_values"]').val(max); //clear out textbox values
        $lastRow.after($newRow); //add in the new row at the end
    }
    else {
        var tr = document.createElement('TR');
        let patientTypeSelect = document.createElement('SELECT')
        patientTypeSelect.setAttribute('name', 'patient_type_ids')
        patientTypeSelect.classList.add("form-control", "rounded-0", "form-control-xs")
        patientTypes.map(item=>{
            let patientTypeOption = document.createElement('OPTION')
            patientTypeOption.setAttribute('value', item.id)
            patientTypeOption.text = item.name_en
            if(patient_type_id==item.id)  patientTypeOption.setAttribute('selected', 'selected')
            patientTypeSelect.append(patientTypeOption)
        })

        var patientTypeControl = patientTypeSelect
        tr.setAttribute('id', id);
        tr.insertCell(0).append(patientTypeControl)
        tr.insertCell(1).innerHTML = '<input type="number" value="'+min+'" class="form-control rounded-0 form-control-xs" name="min_values">';
        tr.insertCell(2).innerHTML = '<input type="text" value="'+sign+'" class="form-control rounded-0 form-control-xs" name="signs">';
        tr.insertCell(3).innerHTML = '<input type="number" value="'+max+'" class="form-control rounded-0 form-control-xs" name="max_values">';
        tr.insertCell(4).innerHTML = '<button type="button" class="btn btn-sm btn-inverse-danger " onclick="removeRefRangeRow(\'' + id + '\')"><i class="mdi mdi-close-circle"></i></button>';
        tr.cells[0].classList.add('p-2','col-sm-4');
        tr.cells[1].classList.add('p-2','col-sm-3');
        tr.cells[2].classList.add('p-2','col-sm-2');
        tr.cells[3].classList.add('p-2','col-sm-3');
        tr.cells[4].classList.add('p-2','col-sm-1','text-center');

        $('#reference-range-table tbody').append(tr);
    }
}

function removeRefRangeRow(id){
    $('#reference-range-table tr#'+id).remove();
}

$('#reference-range-add').click(function () {
    addRefRangeRow();
})


$('#search-organism').keyup(function () {
    getOrganisms($(this).val())
})

$('#search-antibiotic').keyup(function () {
    getAntibiotic($(this).val())
})

function getOrganisms(name = '', selectedOrganisms=[]) {
    $.ajax({
        url: get_refs_base_url+ '/organism/json'+(name.trim() !='' ? '?search&name='+name : ''),
        type:"GET",
        dataType:"json",
        success:function(response){
            $('#organism-box').html('');
            var checkBoxItems="";
            response.map(item =>{
                var checkBoxContainer = document.createElement('DIV');
                checkBoxContainer.classList.add('form-check');
                checkBoxContainer.setAttribute('id','form-checkbox-'+item.id);
                var isChecked = false
                if((selectedOrganisms.map(i=>Number(i))).includes(item.id)){isChecked = true}
                checkBoxItems = '<label class="form-check-label font-13" style="width: 50%;"><input '+(isChecked == true ? 'checked':'')+' name="organism" data-name="'+item.name_en+'" type="checkbox" value="'+item.id+'" class="form-check-input organism-item"> '+item.name_en+' <i class="input-helper"></i></label>';
                checkBoxContainer.innerHTML = checkBoxItems;
                $('#organism-box').append(checkBoxContainer);
            })
        },
        error: function(response) {
        },
    });
}

function getAntibiotic(name = '', selectedAntibiotics=[]) {
    antibiotics = []
    $.ajax({
        url: get_refs_base_url+ '/antibiotic/json'+(name.trim() !='' ? '?search&name='+name : ''),
        type:"GET",
        dataType:"json",
        success:function(response){
            response.map(item =>{
                antibiotics.push({id: item.id, name: item.name_en})
            })
        },
        error: function(response) {
        },
    });
}

$('#sample-type-id').change(function () {
    var sample_type_id = $(this).val()
    getHeadingItems('heading-id',sample_type_id)
})

function getHeadingItems(inputElementId, sample_type_id=0, selected_group_id = 0, field_type=0) {
    $.ajax({
        url: get_refs_base_url+'/test-items/get'+(sample_type_id==0 ? '/0' : '/'+sample_type_id).toString()+'/'+field_type,
        type:"GET",
        dataType:"JSON",
        success:function(response){
            $('#'+inputElementId).html('');
            $('#'+inputElementId).append('<option></option>');
            response.data.map(item =>{
                var patientOption = document.createElement('OPTION');
                patientOption.setAttribute('value',item.sample_id);
                patientOption.setAttribute('test_id',item.id);
                if(selected_group_id == item.sample_id){
                    patientOption.setAttribute('selected','selected');
                }
                patientOption.text = item.name_en;
                $('#'+inputElementId).append(patientOption);
            })
        },
        error: function(response) {
        },
    });
}

$('.btnCommission').click(function () {
    let test_sample_id = $(this).attr('data-uid')
    $('#physician-test-sample-id').val(test_sample_id)
})

$('#modal-physician-commission').on('show.bs.modal', function (event) {
    let test_sample_id = $('#physician-test-sample-id').val()
    $.ajax({
        url: get_refs_base_url+'/test-sample-commission/'+test_sample_id,
        type:"GET",
        dataType:"JSON",
        success:function(response){
            if(response.success){
                let res = response.data
                $('#modal-physician-commission #physician-test-sample-name').text(res.test_name)
                $('#modal-physician-commission table tbody').empty()
                res.physicians.map(physician =>{
                    renderPhysicianRow(physician)
                })
            }
        },
        error: function(response) {
        },
    });
})


function renderPhysicianRow(physician)
{
    var physician_option = document.createElement('OPTION');
    physician_option.setAttribute('value',physician.id);
    physician_option.setAttribute('selected','selected');
    physician_option.text = physician.name_en;
    let tr = document.createElement('TR');
    tr.insertCell(0).innerHTML = '<select class="form-control form-control-sm rounded-0" name="physician[]" id="tb-physician-physician-id-'+physician.id+'" style=" width: 100% !important;"> </select>'
    tr.insertCell(1).innerHTML = '<input id="commission-rate-'+physician.id+'" type="number" min="0.00" step="any" class="form-control form-control-sm rounded-0" value="'+physician.commission_rate+'" name="commission_rate[]" >\n' +
        '<input type="hidden" value="'+physician.commission_type+'" name="commission_type[]">'
    tr.insertCell(2).innerHTML = '<button type="button" onclick="applyCommissionAllTest('+physician.id+', $(\'#commission-rate-'+physician.id+'\').val() , '+physician.commission_type+')" class="btn btn-md btn-inverse-info px-2" style="width: auto !important;"><i class="mdi mdi-check"></i>'+ btn_apply_to_all_tests +'</button>'
    tr.cells[0].classList.add('p-2')
    tr.cells[1].classList.add('p-2')
    tr.cells[2].classList.add('p-2','text-center')
    $('#modal-physician-commission #tb-physician').append(tr);
    $("#tb-physician-physician-id-"+physician.id).append(physician_option);
}

function applyCommissionAllTest(physician_id, commission_rate, commission_type) {
    $.ajax({
        url: test_sample_base_url + '/all/physician-commission',
        type:"POST",
        data:{
            "_token": csrf_token,
            physician_id: physician_id,
            commission_rate: commission_rate,
            commission_type: commission_type
        },
        success:function(res){
            handleMessage(res.success, res.message)
            if(res.success) setTimeout(function () {location.reload()}, messageDuration)
        },
        error: function(response) {
        },
    });
}

/**
 * Modify on organism
 * */

function renderAntiSelection(id, selectionAntiIds = []) {
    let antiSelection = document.createElement('select')
    antiSelection.name = 'selected_antibiotics'
    antiSelection.classList.add('select2-multiple', 'form-control','selected-antibiotics')
    antiSelection.multiple = true
    antiSelection.style.width='150px !important'
    antibiotics.map(ant=>{
        var antiItem = document.createElement('OPTION');
        if((selectionAntiIds.map(i=>Number(i))).includes(ant.id)){antiItem.setAttribute('selected', 'selected')}
        antiItem.setAttribute('value',ant.id);
        antiItem.text = ant.name;
        antiSelection.append(antiItem)
    })
    $('#'+id).append(antiSelection)

    /*$(".select2-multiple").select2({
        placeholder: 'select antibiotics',
        closeOnSelect : false,
    });*/
}

function selectedOrganismRow()
{
    console.log(selectedOrgId)
    var checkboxes = document.getElementsByClassName('organism-item');
    for (var i = 0; i < checkboxes.length; i++) {
        if(checkboxes[i].checked){
            let _id = parseInt(checkboxes[i].value)
            let _name = checkboxes[i].getAttribute('data-name')
            if(!_.contains(selectedOrgId, _id)){
                selectedOrgId.push(_id)
                let tr = document.createElement('TR');
                tr.setAttribute('id', 'organ_'+_id);
                tr.insertCell(0).innerHTML = '<div class="form-check font-13"><label class="form-check-label font-13" style="width: 50%;"><input id="selected-org-'+_id+'" name="selected_organisms" type="checkbox" data-name="'+_name+'" value="'+_id+'" class="form-check-input selected-organism-item"> '+_name+' <i class="input-helper"></i></label></div>';
                tr.insertCell(1).innerHTML = '<input name="is_defaults" class="is_default" value="1" type="radio" />';
                tr.insertCell(2).setAttribute('id', 'org_'+ _id)
                tr.cells[0].classList.add('py-1', 'font-13');
                tr.cells[1].classList.add('py-1', 'text-center','font-13');
                tr.cells[2].classList.add('py-1', 'text-center','font-13')
                $('#selected-organism').append(tr);
                renderAntiSelection('org_'+ _id)

                $(".select2-multiple").select2({
                    placeholder: " select antibiotics",
                    closeOnSelect : false,
                });
            }
        }
    }

    _.each(selectedOrgId, function(i){
        $('#organism-box div').remove('#form-checkbox-'+i)
    })
}

function removeSelectedOrganism()
{
    let removeIds = []
    var checkboxes = document.getElementsByClassName('selected-organism-item');
    for (var i = 0; i < checkboxes.length; i++) {
        if(checkboxes[i].checked){
            let _id = parseInt(checkboxes[i].value)
            removeIds.push(_id)
            let _name = checkboxes[i].getAttribute('data-name')
            if(_.contains(selectedOrgId, _id)){
                selectedOrgId = _.without(selectedOrgId, _id);
                var checkBoxContainer = document.createElement('DIV');
                checkBoxContainer.classList.add('form-check');
                checkBoxContainer.setAttribute('id','form-checkbox-'+_id);
                checkBoxItems = '<label class="form-check-label font-13" style="width: 50%;"><input name="organism" data-name="'+_name+'" type="checkbox" value="'+_id+'" class="form-check-input organism-item"> '+_name+' <i class="input-helper"></i></label>';
                checkBoxContainer.innerHTML = checkBoxItems;
                $('#organism-box').append(checkBoxContainer);
            }
        }
    }
    _.each(removeIds, function(i){
        $('#selected-organism tr').remove('#organ_'+i)
    })
}
