// Load test items and settings

let last_org_id = null;
let anti_payload = [];

$('#modal-add-test-result').on('show.bs.modal', function (event) {
    $.ajax({
        url: get_refs_base_url + '/test-items/'+sample_id,
        type:"GET",
        dataType:"json",
        success:function(response){
            if(response.success){

                $('#modal-add-test-result .modal-header .sample-number').html(response.data.sample.sample_number)
                $('#modal-add-test-result .modal-header .patient-code').html(response.data.sample.patient_uuid)
                $('#modal-add-test-result .modal-header .patient-name').html(response.data.sample.patient_name)
                $('#modal-add-test-result .modal-header .sample-source').html(response.data.sample.sample_source)
                $('#modal-add-test-result #sample-id').val(response.data.sample.sample_id)

                $('#test-item-result').empty()
                let res = response.data
                // anti_payload data seeding
                anti_payload = [];
                res.antibiotic_results.map(item=>{
                    var payload_item = {'id' : item.test_organism_id, 'anti_id' : item.antibiotic_id}
                    anti_payload.push(payload_item)
                })

                for (var i in res.sample_tests){
                    var department_name = '<b class="text-info pl-1"> <i class="mdi mdi-hand-pointing-right text-info font-14"></i> ' + res.sample_tests[i].department_name + '</b>';
                    var samples_list = res.sample_tests[i].samples;
                    for(var j in samples_list){
                        var sampleType = '<b class="pl-4 text-info"><i class="mdi mdi-link-variant text-info font-14"></i> '+ samples_list[j].sample_type_name + '</b>' + '<span class="pl-5"> Sample Entry By: <span id="smp-entry">'+res.sample_users.creator+'</span></span> <span class="pl-5">Modified By: <span id="smp-modify">'+res.sample_users.modifier+'</span></span>'
                        renderTestItemDepartmentRow(samples_list[j].sample_type_id, department_name + ' ' + sampleType  ,'',' None', 'test-item-result')
                        var tests = samples_list[j].tests
                        var sampleTest = list_to_tree(tests)
                        sampleTest.map(parent => {
                            renderTestItemRow(parent.id, parent.field_type,'<sapn class="pl-3 '+((parent.children.length) ? 'font-weight-medium':'')+'">'+parent.test_name+'</sapn>', parent.unit_sign ,parent.ref_range, parent.min_ref_val, parent.max_ref_val,parent.test_result,parent.is_show, res.performers, parent.performed_by,'test-item-result','3', parent.org_results, parent.formula, parent.order, parent.test_date, parent.test_id, samples_list[j].comments, parent.str_comment, samples_list[j].sample_type_id, parent.org_suggested_results)

                            if(parent.field_type!=0){
                                autoSuggest(document.getElementById('comment-'+parent.id), samples_list[j].comments);
                            }

                            if(parent.children.length){
                                var children = parent.children
                                children.map(function (child) {
                                    renderTestItemRow(child.id, child.field_type ,'<span class="pl-4 ml-3">'+child.test_name+'</span>', child.unit_sign ,child.ref_range, child.min_ref_val, child.max_ref_val, child.test_result, child.is_show, res.performers, child.performed_by,'test-item-result','4', child.org_results, child.formula, child.order, child.test_date, child.test_id, samples_list[j].comments, child.str_comment, samples_list[j].sample_type_id, child.org_suggested_results)

                                    if(child.field_type!=0){
                                        autoSuggest(document.getElementById('comment-'+child.id), samples_list[j].comments);
                                    }

                                    if(child.children.length){
                                        var grandchildren = child.children
                                        grandchildren.map(function (grandchild) {
                                            renderTestItemRow(grandchild.id, grandchild.field_type ,'<span class="pl-5 ml-3">'+grandchild.test_name+'</span>', grandchild.unit_sign ,grandchild.ref_range, grandchild.min_ref_val,grandchild.max_ref_val, grandchild.test_result, grandchild.is_show, res.performers, grandchild.performed_by,'test-item-result','5', grandchild.org_results, grandchild.formula, grandchild.order, grandchild.test_date, grandchild.test_id, samples_list[j].comments, grandchild.str_comment, samples_list[j].sample_type_id, grandchild.org_suggested_results)

                                            if(grandchild.field_type!=0){
                                                autoSuggest(document.getElementById('comment-'+grandchild.id), samples_list[j].comments);
                                            }

                                        })

                                    }
                                });
                            }
                        })
                    }
                }
                evaluateTestItem()
            }
        }
    });
});

function evaluateTestItem() {
    var $test_list = $('#modal-add-test-result').find("table tbody");
    $test_list.find("tr[data-field-type='4']").each(function() {
       // var $tr = $(this);
        var formula = $(this).data("formula");
        //var sample_test_id = $(this).data("test-sample-id");
        var sample_test_id = $(this).data("test-id");
        if (formula) {
            //TODO bind event
            var parser = new exprEval.Parser();
            var expr   = parser.parse(formula);
            var variables = expr.variables();
            for(var i in variables) {
                if (CAMLIS_VARIABLE_FORMAT.TEST.test(variables[i])) {
                    var id = "#" + variables[i].replace('T', 'result-');
                    $test_list.find("input" + id).on("blur", function() {
                        var result = calculateTestValue(formula);
                        if(isFloat(result)) result = Number(result).toFixed(1); // added 23 Jan 2021
                        $test_list.find("input#result-" + sample_test_id).val(result);

                       // $tr.find("input.test_date").data("DateTimePicker").setDate(lastTestDate);
                       // $tr.find("select.performer").val(lastPerformer).trigger("change");
                    });
                }

                CAMLIS_VARIABLE_FORMAT.TEST.lastIndex = 0;
            }
        }
    });
}

function renderTestItemDepartmentRow(dp_id, department, entryBy, modifyBy, wrapperId)
{
    var tr = document.createElement('TR');
    tr.setAttribute('id', 'dp-st-id'+dp_id);
    tr.classList.add('text-center','result-item')
    tr.insertCell(0).innerHTML = department;
    tr.cells[0].colSpan=7
    tr.insertCell(1).innerHTML = '<input onclick="checkAll(\'stdp'+dp_id+'\',\'item-visible-'+dp_id+'\')" id="stdp'+dp_id+'" class="item-visible-'+dp_id+' form-check m-auto border border-light" type="checkbox">';
    tr.cells[0].setAttribute('class','text-left');
    tr.cells[0].classList.add('p-2');
    tr.classList.add('bg-gradient-light','p-2')
    $('#'+wrapperId).append(tr);
}

function renderTestItemRow(test_sample_id, fieldType, test_name, unit_sign, ref, minVal, maxVal, resultVal, isHide, performers,selected_performer, wrapperId, level, org_results, formula, order, test_date, test_id, comments, selected_comment, sample_type_id, org_suggested_results)
{
    let org_result			= [];
    let org_resultTxt		= [];
    let orderTest = $('#'+wrapperId+' TR.hasInput').length +1

    let resultControl = '';
    let unitSignLabel = '';
    let refRangeLabel = '';
    let performedControl = '';
    let commentControl = '';
    if(fieldType==1){
        resultControl='<input type="hidden" name="ref_test_sample_id[]" value="'+test_sample_id+'"> <input style="width: 300px !important;" name="ref_test_sample_id_value[]" value="'+resultVal+'" data-formula="'+formula+'" id="result-'+test_id+'" order="'+orderTest+'" onblur="computeRefRangeResult(\'result-'+test_id+'\', $(this).val(),'+ minVal+','+ maxVal+')" class="form-control result rounded-0 border border-light form-control-xs T'+test_id+'" type="text">';
        refRangeLabel = ref
    }
    else if(fieldType==2 || fieldType==3){
        org_results.map(item=>{
            org_result.push({
                test_sample_id      : test_sample_id,
                test_organism_id	: item.test_organism_id,
                organism_id         : item.organism_id,
                quantity_id			: item.quantity_id,
                contaminant         : item.contaminant
            });
            org_resultTxt.push(item.organism_name.trim());
        })
        if(org_results.length<1 && org_suggested_results.length>0){
            var i = 0;// (fieldType==2) ? org_suggested_results.length-2 : 0;
            for (; i < org_suggested_results.length; i++) {
                if (org_suggested_results[i].is_default == 1) {
                    org_result.push({
                        test_sample_id: test_sample_id,
                        test_organism_id: org_suggested_results[i].test_organism_id,
                        organism_id: org_suggested_results[i].organism_id,
                        quantity_id: 0,
                        contaminant: 0
                    });
                    org_resultTxt.push(org_suggested_results[i].organism_name.trim());
                }
            }
        }
        resultControl='<input type="hidden" name="ref_test_sample_id___[]" value="'+test_sample_id+'"> <input type="text" order="'+orderTest+'" class="result" style="width: 0px; border: none; position: absolute; z-index: -10 !important;" onfocus="$(\'#test-sample-id-'+test_sample_id+'\').click()"> <button type="button" style="background:white; cursor:pointer;" id="test-sample-id-'+test_sample_id+'" onclick="showOrganismResult('+test_sample_id+', '+fieldType+')" data-toggle="modal" data-formula="'+formula+'" data-target="#modal-organism-result" data-test-sample-id="'+test_sample_id+'" data-test-id="'+test_id+'" data-backdrop="static" class="form-control ref-sample-organism rounded-0 form-control-xs border border-light text-left"></button>'
    }
    // field type calculation
    else if(fieldType == 4){
        resultControl='<input type="hidden" name="ref_test_sample_id[]" value="'+test_sample_id+'"> <input style="width: 300px !important;" name="ref_test_sample_id_value[]" order="'+orderTest+'" value="'+resultVal+'" data-formula="'+formula+'" id="result-'+test_id+'" onchange="computeRefRangeResult(\'result-'+test_id+'\', $(this).val(),'+ minVal+','+ maxVal+')" class="form-control result rounded-0 border border-light form-control-xs T'+test_id+'" type="text">';
        refRangeLabel = ref
    }

    let tr = document.createElement('TR');
    if(fieldType != 0) {
        tr.setAttribute('class', 'hasInput');
        unitSignLabel = unit_sign
        performedControl = '<select id="performer-'+orderTest+'" name="ref_test_sample_performer[]" class="form-control performed_by rounded-0 form-control-xs border border-light"><option></option></select>'
        if(fieldType==2 || fieldType==3){
            commentControl = commentBox('ref_test_sample_comment___',test_sample_id, selected_comment, orderTest)
        }
        else{
            commentControl = commentBox('ref_test_sample_comment', test_sample_id, selected_comment, orderTest)
        }
    }
    tr.setAttribute('id', 'test_'+test_sample_id);
    tr.setAttribute('data-test-sample-id', test_sample_id);
    tr.setAttribute('data-test-id', test_id);
    if(fieldType == 4){
        tr.setAttribute('data-field-type', '4');
        tr.setAttribute('data-formula', formula);
    }

    tr.classList.add('result-item')
    tr.insertCell(0).innerHTML = test_name;
    tr.insertCell(1).innerHTML = resultControl;
    tr.insertCell(2).innerHTML = unitSignLabel;
    tr.insertCell(3).innerHTML = refRangeLabel;
    tr.insertCell(4).innerHTML = (fieldType != 0) ? '<input type="date" name="ref_test_sample_test_date[]" id="test-date-'+orderTest+'" value="'+test_date+'" class="form-control test-date form-control-sm" />':'';
    tr.insertCell(5).innerHTML = performedControl;
    tr.insertCell(6).innerHTML = commentControl;
    tr.insertCell(7).innerHTML = '<input name="test_samples_to_hide[]" '+(isHide==0 ? 'checked':'')+' value="'+test_sample_id+'" class="item-visible-'+sample_type_id+' form-check m-auto border border-light" type="checkbox">';
    tr.cells[0].classList.add('pl-'+level, 'p-2')
    tr.cells[1].classList.add('p-1','px-2');
    tr.cells[0].style.width='300px !important';
    tr.cells[2].classList.add('p-1','text-left','pl-3');
    tr.cells[3].classList.add('p-1','text-left','pl-3');
    tr.cells[4].classList.add('p-1','px-2');
    tr.cells[5].classList.add('p-1','px-2');
    tr.cells[6].classList.add('p-1','text-left');
    tr.cells[6].style.verticalAlign="top"
    $('#'+wrapperId).append(tr);

    performerBox('performer-'+orderTest, performers, selected_performer)

    if((fieldType==2 || fieldType==3) && org_result.length>0){
        $("#modal-add-test-result #test-sample-id-"+test_sample_id).text(org_resultTxt.join(', '))
        $("#modal-add-test-result #test-sample-id-"+test_sample_id).data("possible_result", org_result);
    }
    evaluateTestItem()

    computeRefRangeResult('result-'+test_id, resultVal,minVal,maxVal);

    $(".select2-tags").select2({
        placeholder: choose_option,
        tags: true,
        tokenSeparators: [',']
    });

}

function computeRefRangeResult(controlId, val, min, max) {
    if(min=='null' || max=='null' || val=='') $('#'+controlId).removeClass('out-of-range')
    else if(parseFloat(val)>=parseFloat(min) && parseFloat(val)<=parseFloat(max)) $('#'+controlId).removeClass('out-of-range')
    else $('#'+controlId).addClass('out-of-range','text-white')
}

function performerBox(controlId,data, selected) {
    $('#'+controlId).html('<option></option>');
    data.map(function (item) {
        var performerOption = document.createElement('OPTION');
        performerOption.setAttribute('value',item.id);
        if(selected==item.id) performerOption.setAttribute('selected','selected');
        performerOption.text = item.name;
        $('#'+controlId).append(performerOption);
    })
}

function commentBox(controlName, controlId, comment ='', orderTest) {
    let searchEle = '<div class="autocomplete position-absolute d-block mt-1">'+
        //'<input multiple type="text" name="ref_test_sample_comment[]" order="'+orderTest+'" value="'+comment+'" id="comment-'+controlId+'" style="width: 250px !important;" placeholder="search test" class="form-control comment-box rounded-0 form-control-sm">'+
        '<textarea name="'+controlName+'[]" order="'+orderTest+'" id="comment-'+controlId+'" style="width: 250px !important; height: 34px !important; margin-top: 2px;" placeholder="search test" class="form-control comment-box rounded-0 form-control-sm">'+comment+'</textarea>'+
        '</div>'
    return searchEle
}

function getSampleTestItem_() {
    $.ajax({
        url		 : sample_base_url +'/' + sample_id + '/tests',
        type	 : 'get',
        data	 : {},
        dataType : 'json',
        success	 : function (resource) {
            if(resource.success) {
                res = resource.data
                $('#modal-add-test-result .modal-header .sample-number').html(res.sample_number)
                $('#modal-add-test-result .modal-header .patient-code').html(res.patient.uuid)
                $('#modal-add-test-result .modal-header .patient-name').html(res.patient.name)
                $('#modal-add-test-result .modal-header .sample-source').html(res.sample_source.name)
                $('#modal-add-test-result #sample-id').val(res.id)
            }

        },
        error	 : function () {

        }
    });
}

$('#modal-add-test-result').find(".btnAddTestResult").on("click", function (evt) {
    $('.btnAddTestResult').prop('disabled', true)
    var formData = $('#form-add-test-result').serializeArray()
    //formData.push({name: "organism_antibiotics", value: JSON.stringify(anti_payload)});
    let possible_result = []
    let anti_result = []

    let isPreViewResult = ($(this).attr('value')=='save-result-preview') ? true : false
    let previousId = $('#previous_sample').val();

    $('#form-add-test-result #test-item-result').find("tr").each(function () {
        if($(this).find("td button.ref-sample-organism").length){
            let organism_data = $(this).find("td button.ref-sample-organism").data("possible_result");
            if(organism_data) possible_result.push(organism_data)

            let antibiotic_data = $(this).find("td button.ref-sample-organism").data("anti_result");
            if(antibiotic_data) anti_result.push(antibiotic_data)
        }
    });

    formData.push({name: "possible_result", value: JSON.stringify(possible_result)});
    formData.push({name: "anti_result", value: JSON.stringify(anti_result)});
    $.ajax({
        url: sample_base_url + '/add-test-result',
        type: "POST",
        data: formData,
        dataType: "json",
        success: function (response) {
            if(response.success){
                if(isPreViewResult){
                    let previousSampleUrl = (previousId>0) ? '&previous_sample='+ previousId: '';
                    window.location = sample_base_url + '/edit/'+sample_id+'?print-result' + previousSampleUrl

                    //$('#modal-assign-test .close').click();
                    //$('#sample-forms #btnAddTestResult').click()
                }
                else alertify.success('Sample result save successfully.')
            } else{
                customErrorAlert(response.error)
            }
        }
    });

})

function showOrganismResult(test_sample_id, field_type){
    $("#modal-organism-result").attr('data-test-sample-id', test_sample_id)
    $("#modal-organism-result").attr('data-field-type', field_type);
    $.ajax({
        url: get_refs_base_url + '/test-sample-organism/get/' + test_sample_id+'/'+sample_id,
        type: "GET",
        dataType: "json",
        success: function (response) {
            if (response.success) {
                $('#modal-organism-result-organism #orgn-result-area').empty();
                $('.possible-result-test-name').text(response.test.test.name_en)
                response.data.map(item =>{
                    renderOrganismResultItemRow(item.test_sample_id, field_type, item, response.qualities);
                })
            }
        }
    });
}


function renderOrganismResultItemRow(test_sample_id, fieldType, data, qualities, selectedOrgByClicked = [])
{
    let possible_results = [];
    possible_results = $("#modal-add-test-result #test-sample-id-"+test_sample_id).data("possible_result") ?? []
    let checked = false
    if((possible_results.some(possible_result => possible_result.test_organism_id == data.id)) || data.is_default==1){ checked = true }

    let quantity_id = 0;
    let contaminant = false;

    possible_results.map(item=>{
        if(item.test_organism_id == data.id){
            quantity_id = item.quantity_id
            contaminant = (item.contaminant==1) ? true : false
            return true
        }
    })

    selectedOrgByClicked.map(items=>{
        if(items.test_organism_id == data.id){
            quantity_id = items.quantity_id
            return true
        }
    })

    if(data.selected==1){
        checked = true
    }

    //let resultControl = '<div class="form-check"><label onclick="getOrganismAntibiotics(\'org-'+data.id+'\','+data.id+','+data.organism.id+','+test_sample_id+')" class="form-check-label d-inline font-13"><input name="org-anti" '+(checked ? 'checked':'')+' data-name="'+data.organism.name_en+'" data-id="'+data.organism.id+'" data-test-sample-id="'+test_sample_id+'" type="'+(fieldType==2?'radio':'checkbox')+'" id="org-'+data.id+'" value="' + data.id + '" class="form-check-input test_organism"><i class="input-helper"></i></label></div>';
    let tr = document.createElement('TR');
    tr.setAttribute('id', 'organ_'+data.id);
    tr.setAttribute('data-name', data.organism.name_en);
    tr.setAttribute('class', 'organ_parent organ_anti_'+data.id);
    tr.insertCell(0).innerHTML = '<i onclick="$(\'#child_organ_'+data.id+'\').toggle()" role="button" class="text-info pointer-event font-weight-bold mdi mdi-plus-circle"></i>';
    tr.insertCell(1).innerHTML = '<input name="org-anti" '+(checked ? 'checked':'')+' data-name="'+data.organism.name_en+'" data-id="'+data.organism.id+'" data-test-sample-id="'+test_sample_id+'" type="'+(fieldType==2?'radio':'checkbox')+'" id="org-'+data.id+'" value="' + data.id + '" class="test_organism">';
    tr.insertCell(2).innerHTML = data.organism.name_en;
    tr.insertCell(3).innerHTML = '<select id="org-quanity-'+data.id+'" class="form-control form-control-xxs organism_qty rounded-0 test_organism_qty" data-id="'+data.organism.id+'" data-test-sample-id="'+test_sample_id+'"></select>';
    tr.insertCell(4).innerHTML = '<input type="checkbox" '+(contaminant ? 'checked':'')+' class="org-contaminant" />';
    tr.cells[0].classList.add('py-1', 'text-center')
    tr.cells[1].classList.add('py-1', 'text-center');
    tr.cells[2].classList.add('py-1');
    tr.cells[3].classList.add('py-1');
    tr.cells[4].classList.add('py-1','text-center');
    $('#modal-organism-result-organism #orgn-result-area').append(tr);

    if(data.antibiotics.length){
        let chTr = document.createElement('TR');
        chTr.setAttribute('data-name', data.organism.name_en);
        chTr.setAttribute('id', 'child_organ_'+data.id);
        chTr.setAttribute('class', 'organ_child organ_anti_'+data.id);
        chTr.style.display="none";
        chTr.insertCell(0).innerHTML="<div class=\"table-responsive\">\n" +
            "                                    <table class=\"table table-bordered\"><tr class='bg-light'>\n" +
            "                                            <td class=\"py-1\">Antibiotic</td>\n" +
            "                                            <td width='110px' class=\"py-1\">Disk diffusion</td>\n" +
            "                                            <td width='110px' class=\"py-1\">MIC</td>\n" +
            "                                            <td width='160px' class=\"py-1\">Sensitive</td>\n" +
            "                                            <td width='60px' class=\"py-1\">Invisible</td></tr>\n" +
            "                                        <tbody id=\"anti-result-area"+data.id+"\">\n" +
            "\n" +
            "                                        </tbody>\n" +
            "                                    </table>\n" +
            "                                </div>"
        chTr.cells[0].setAttribute('id', 'antibiotics_org_'+data.id)
        chTr.cells[0].colSpan=5
        chTr.cells[0].classList.add('p-2', 'pl-5')
        $('#modal-organism-result-organism #orgn-result-area').append(chTr);

        data.antibiotics.map(item=>{
            let antiTr = document.createElement('TR');
            let sensitive = (item.antibiotic_result!=null ? item.antibiotic_result.sensitive : '')
            antiTr.setAttribute('id', 'organ_'+data.id);
            antiTr.insertCell(0).innerHTML = item.antibiotic_item.name_en;
            antiTr.insertCell(1).innerHTML = '<input type="hidden" class="antibiotic_id" value="'+item.id+'"> <input type="text" class="form-control disk_diffusion form-control-xxs" value="'+(item.antibiotic_result!=null ? item.antibiotic_result.disk_diffusion : '')+'">';
            antiTr.insertCell(2).innerHTML = '<input type="text" class="form-control mic form-control-xxs" value="'+(item.antibiotic_result!=null ? item.antibiotic_result.mic : '')+'">';
            antiTr.insertCell(3).innerHTML = '<select class="form-control form-control-xxs sensitive rounded-0"><option '+(sensitive=='' ? 'selected':'')+' value=""></option><option '+(sensitive=='S' ? 'selected':'')+' value="S">Sensitive</option><option '+(sensitive=='R' ? 'selected':'')+' value="R">Resistant</option> <option '+(sensitive=='I' ? 'selected':'')+' value="I"> Intermediate</option></select>';
            antiTr.insertCell(4).innerHTML = '<input class="is_hide" type="checkbox" '+(item.antibiotic_result!=null && item.antibiotic_result.is_hide==1  ? 'checked' : '')+' >';
            antiTr.cells[0].classList.add('py-1')
            antiTr.cells[1].classList.add('py-1');
            antiTr.cells[2].classList.add('py-1');
            antiTr.cells[3].classList.add('py-1');
            antiTr.cells[4].classList.add('py-1','text-center');
            $('#modal-organism-result-organism #orgn-result-area #anti-result-area'+data.id).append(antiTr);
        })

    }
    performerBox('org-quanity-'+data.id,qualities, quantity_id)
}

$('#btnAddOrganism').click(function () {
    let $organism_list	= $('#modal-organism-result').find("#orgn-result-area");
    let org_results			= [];
    let anti_results = [];
    let org_resultTxt		= [];
    $organism_list.find("tr").each(function () {
        if ($(this).find("td input.test_organism").is(":checked")) {
            var val			= $(this).find("td input.test_organism:checked").val();
            var id			= $(this).find("td input.test_organism:checked").attr('data-id');
            var test_sample_id = $(this).find("td input.test_organism:checked").attr('data-test-sample-id');
            var txt			= $(this).find("td input.test_organism:checked").attr('data-name');
            var resQty		= $(this).find("td select.organism_qty").val();
            var contaminant = $(this).find("td .org-contaminant").is(":checked") ? 1 : 0 ;
            org_results.push({
                test_sample_id      : test_sample_id,
                test_organism_id	: val,
                organism_id         : id,
                quantity_id			: resQty,
                contaminant         : contaminant
            });
            org_resultTxt.push(txt.trim());
            $('#'+'child_'+$(this).attr('id')+' .table').find("tr").each(function (item, obj) {
                if($(obj).find("td input.antibiotic_id").val()!==undefined){
                    let disk_diffusion = $(obj).find("td input.disk_diffusion").val()
                    let antibiotic_id = $(obj).find("td input.antibiotic_id").val()
                    let mic = $(obj).find("td input.mic").val()
                    let sensitive = $(obj).find("td select.sensitive").val()
                    let is_hide = $(obj).find("td input.is_hide").is(":checked") ? 1 : 0
                    anti_results.push({
                        test_organism_id : val,
                        antibiotic_id : antibiotic_id,
                        disk_diffusion : disk_diffusion,
                        mic : mic,
                        sensitive : sensitive,
                        is_hide : is_hide,
                    });
                }
            });
        }
    });

    let test_sample_id = $("#modal-organism-result").attr('data-test-sample-id');
    $("#modal-add-test-result #test-sample-id-"+test_sample_id).text(org_resultTxt.join(', '))
    $("#modal-add-test-result #test-sample-id-"+test_sample_id).data("possible_result", org_results);
    $("#modal-add-test-result #test-sample-id-"+test_sample_id).data("anti_result", anti_results);
    $('#close-modal-organism-result').click()
})

function renderOrganismAntibioticsResultItemRow(test_sample_organism_id, data)
{
    let resultControl = '<div class="form-check"><label onclick="checkOrgAntibiotics(\'anti-check-'+data.id+'\','+data.id+')" class="form-check-label d-inline font-13"><input name="organism_result[]" type="checkbox" id="anti-check-'+data.id+'" value="' + data.id + '" class="form-check-input sample-test"> ' + data.antibiotic_item.name_en + ' <i class="input-helper"></i></label></div>';
    let tr = document.createElement('TR');
    tr.setAttribute('id', 'ainti_'+test_sample_organism_id);
    tr.insertCell(0).innerHTML = resultControl;
    tr.insertCell(1).innerHTML = '';
    tr.insertCell(2).innerHTML = '';
    tr.insertCell(3).innerHTML = '';
    tr.insertCell(4).innerHTML = '';
    tr.cells[0].classList.add('py-0')
    tr.cells[1].classList.add('py-0');
    tr.cells[2].classList.add('py-0');
    tr.cells[4].classList.add('py-0');
    tr.cells[4].classList.add('py-0');
    $('#modal-organism-result-antibiotic #anti-result-area').append(tr);
}

function checkOrgAntibiotics(controlId, antibiotic_id) {
    var checkedState = $('#'+controlId).is(':checked');
    var id = antibiotic_id
    if(last_org_id == null){return false;}
    if(checkedState){
        var payload_item = {'id' : last_org_id, 'anti_id' : id}
        anti_payload.push(payload_item)
    }
    else{
        anti_payload = $.grep(anti_payload, function(value) {
            return value.anti_id != id;
        });
    }
}

$('#edit-test').click(function () {
    window.location = sample_base_url + '/edit/'+sample_id+'?edit-test'
})

$('#modal-add-test-result').on("keyup", "input.result", function (evt) {
    if (evt.which === 13 || evt.which === 38 || evt.which === 40) {
        var order = parseInt($(this).attr("order"));
        order = evt.which === 13 || evt.which === 40 ? order + 1 : order - 1;
        if (order > 0) {
            $('#modal-add-test-result').find("input.result[order="+ order +"]").focus();

            $('#modal-add-test-result .performed_by').each(function(index, item){
                if(item.value){
                    $('#modal-add-test-result #performer-'+order).val(item.value)
                    return true;
                }
            });

            $('#modal-add-test-result .test-date').each(function(index, item){
                if(item.value){
                    $('#modal-add-test-result #test-date-'+order).val(item.value)
                    return true;
                }
            });

        }
    }
});


$('#modal-add-test-result').on("keyup", "input.comment-box", function (evt) {
    if (evt.which === 13 || evt.which === 38 || evt.which === 40) {
        var order = parseInt($(this).attr("order"));
        order = evt.which === 13 || evt.which === 40 ? order + 1 : order - 1;
        if (order > 0) {
            $('#modal-add-test-result').find("input.comment-box[order="+ order +"]").focus();
        }
    }
});

$('#modal-organism-result').on("click", ".test_organism", function () {

    if($(this).is(':checked')){
        var test_sample_id = parseInt($(this).attr("data-test-sample-id"));
        var organism_id = parseInt($(this).attr("data-id"));

        $.ajax({
            url: sample_base_url + '/add-org-result/' + sample_id +'/'+test_sample_id+'/'+organism_id,
            type: "GET",
            dataType: "json",
            success: function (response) {
                if (response.success) {
                   console.log(response)

                }
            }
        });


    }

});

$('#modal-organism-result').on("change", ".test_organism_qty", function () {


        var test_sample_id = parseInt($(this).attr("data-test-sample-id"));
        var organism_id = parseInt($(this).attr("data-id"));

        $.ajax({
            url: sample_base_url + '/save-org-result-qty/' + sample_id +'/'+test_sample_id+'/'+organism_id+'/'+$(this).val(),
            type: "GET",
            dataType: "json",
            success: function (response) {
                if (response.success) {
                   console.log(response)

                }
            }
        });




});


