// Load test items and settings


$('#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){
                $('#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>'
                        renderTestItemDepartmentRowBioLab('st-id'+samples_list[j].sample_type_id, department_name + ' ' + sampleType  ,'',' None', 'test-item-result-bio-lab')
                        var tests = samples_list[j].tests
                        var sampleTest = list_to_tree(tests)
                        sampleTest.map(parent => {
                            renderTestItemRowBioLab(parent.id, parent.field_type,'<sapn class="pl-3 '+((parent.children.length) ? 'font-weight-medium':'')+'">'+parent.test_name+'</sapn>',parent.is_show,'test-item-result-bio-lab','3', parent.order, parent.test_id, samples_list[j].comments, parent.str_comment)
                            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) {
                                    renderTestItemRowBioLab(child.id, child.field_type ,'<span class="pl-4 ml-3">'+child.test_name+'</span>', child.is_show,'test-item-result-bio-lab','4', child.order, child.test_id, samples_list[j].comments, child.str_comment)
                                    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) {
                                            renderTestItemRowBioLab(grandchild.id, grandchild.field_type ,'<span class="pl-5 ml-3">'+grandchild.test_name+'</span>', grandchild.is_show,'test-item-result-bio-lab','5', grandchild.order, grandchild.test_id, samples_list[j].comments, grandchild.str_comment)
                                            //renderTestItemRowBioLab(test_sample_id, fieldType, test_name, isHide, wrapperId, level, order, test_id, comments, selected_comment)
                                            if(grandchild.field_type!=0){
                                                autoSuggest(document.getElementById('comment-'+grandchild.id), samples_list[j].comments);
                                            }

                                        })

                                    }
                                });
                            }
                        })
                    }
                }
                getSampleTestItemBioLab()

            }
        }
    });
});


function renderTestItemDepartmentRowBioLab(dp_id, department, entryBy, modifyBy, wrapperId)
{
    var tr = document.createElement('TR');
    tr.setAttribute('id', 'dp-'+dp_id);
    tr.classList.add('text-center','result-item')
    tr.insertCell(0).innerHTML = department;
    tr.cells[0].colSpan=3
    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 renderTestItemRowBioLab(test_sample_id, fieldType, test_name, isHide, wrapperId, level, order, test_id, comments, selected_comment)
{
    let 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="-1" data-formula="" id="result-'+test_id+'" class="form-control rounded-0 border border-light form-control-xs" type="hidden">';
    let tr = document.createElement('TR');

    let commentControl = resultBoxBioLab(test_sample_id, selected_comment,'')

    tr.setAttribute('id', 'bio_test_'+test_sample_id);
    tr.setAttribute('data-test-sample-id', test_sample_id);
    tr.setAttribute('data-test-id', test_id);

    tr.classList.add('result-item')
    tr.insertCell(0).innerHTML = test_name + resultControl;
    tr.insertCell(1).innerHTML = commentControl;
    tr.insertCell(2).innerHTML = '<input name="test_samples_to_hide[]" '+(isHide==0 ? 'checked':'')+' value="'+test_sample_id+'" class="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');
    tr.cells[2].style.verticalAlign="top"
    $('#'+wrapperId).append(tr);

}

function resultBoxBioLab(controlId, comment ='', orderTest) {
    let searchEle = '<div class="autocomplete col-sm-12 mt-0">'+
        '<textarea name="ref_test_sample_comment[]" maxlength="1000" order="'+orderTest+'" id="comment-'+controlId+'" style="!important; height:80px !important; margin-top: 2px;" placeholder="" class="form-control comment-box rounded-0 form-control-sm">'+comment+'</textarea>'+
        '</div>'
    return searchEle
}

function getSampleTestItemBioLab() {
    $.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-bio-lab').serializeArray()
    let possible_result = []
    let anti_result = []

    let isPreViewResult = ($(this).attr('value')=='save-result-preview') ? true : false
    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){
                    window.location = sample_base_url + '/edit/'+sample_id+'?print-result'
                }
                else alertify.success('Sample result save successfully.')
            } else{
                customErrorAlert(response.error)
            }
        }
    });

})
