
let antibiotic_results = []

$('#print_preview_modal').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){
                $('#sample-result-print').empty()
                let res = response.data
                antibiotic_results = res.antibiotic_results
                for (var i in res.sample_tests){
                    let heading = {"sample": res.sample, "department": res.sample_tests[i].department_name}
                    let samples_list = res.sample_tests[i].samples;
                    for(var j in samples_list){
                        renderPrintTestItemDepartmentRow(samples_list[j], heading,'sample-result-print')
                        var tests = samples_list[j].tests
                        var sampleTest = list_to_tree(tests)
                        sampleTest.map(parent => {
                            renderPrintTestItemRow(parent, '0' ,'test-dep-'+samples_list[j].sample_type_id,' sample-result-print')
                            if(parent.children.length){
                                var children = parent.children
                                children.map(function (child) {
                                    renderPrintTestItemRow(child, '1' ,'test-dep-'+samples_list[j].sample_type_id,' sample-result-print')
                                    if(child.children.length){
                                        var grandchildren = child.children
                                        grandchildren.map(function (grandchild) {
                                            renderPrintTestItemRow(grandchild, '1' ,'test-dep-'+samples_list[j].sample_type_id,' sample-result-print')
                                        })
                                    }
                                });
                            }
                        })
                    }
                }

            } else{
                antibiotic_results = []
            }
        }
    });
})

function manipulateTableHeading(department, sample_type, sample_number, requester, collected_date, received_date, sample_tests) {
    let tableData = '<table width="100%" border="0" class="_department-sample-info"><thead>\n' +
        '                                <tr style="background: #eee;">' +
        '                                   <td class="sourceserifpro-bold result-page-color" colspan="5" style="text-align: center;">'+sample_type+'</td>' +
        '                               </tr>\n' +
        '<tr>\n' +
        '                                    <th class="sourceserifpro-bold result-font-size result-page-color" style="width: 50% !important;"><div style="width:370px !important; float:left; height:10px; ">&nbsp;</div></th>\n' +
        '                                    <th class="sourceserifpro-bold result-font-size result-page-color" style="width: 15%;">Result</th>\n' +
        '                                    <th class="sourceserifpro-bold result-font-size result-page-color" style="width: 5%;"></th>\n' +
        '                                    <th class="sourceserifpro-bold result-font-size result-page-color" style="width: 10%;">Units</th>\n' +
        '                                    <th class="sourceserifpro-bold result-font-size result-page-color" style="width: 20%; text-align: center">Normal Range</th>\n' +
        '                                </tr></thead>\n' +
        '                                <tbody id="test-dep-'+sample_tests.sample_type_id+'"></tbody>'+
        '                                </thead>' +
        '                            </table>'
    return tableData;
}


function renderPrintTestItemDepartmentRow(sample_tests, department_heading, wrapperId)
{
    let tableData = manipulateTableHeading(department_heading.department, sample_tests.sample_type_name, department_heading.sample.sample_number, department_heading.sample.requested_by.name_en, department_heading.sample.collected_date, department_heading.sample.received_date, sample_tests)
    var tr = document.createElement('TR');
    tr.setAttribute('class', 'sample-type');
    tr.insertCell(0).innerHTML = tableData;
    $('#'+wrapperId).append(tr);
}

function renderPrintTestItemRow(sample_tests, level, closet_parent_id)
{
    if(sample_tests.is_show == 1) {

        let IsAbnormal = computeRefRange(sample_tests);
        let tr = document.createElement('TR');
        tr.setAttribute('valign', 'top')
        tr.insertCell(0).innerHTML = '' + (sample_tests.field_type == 0 ? '<b class="sourceserifpro-bold">' + sample_tests.test_name + '</b>' : '<p class="value-pair"><span style="'+(sample_tests.is_bold==1 ? ' font-weight:bold;' :'' )+'" class="name result-font-size">' + sample_tests.test_name + '</span> </p>') + '';
        if(["2","3"].includes(sample_tests.field_type)){
            tr.insertCell(1).innerHTML = (sample_tests.field_type == 0 ? '' : '') + manipulatePrintOrganismResult(sample_tests)
            tr.cells[1].colSpan=4
        }else{
            if(sample_tests.unit_sign.trim()!='' || (["0.0","0.00","0"].includes(sample_tests.sign))){
                tr.insertCell(1).innerHTML = ''+ (sample_tests.field_type == 0 ? '' : '') + manipulatePrintOrganismResult(sample_tests) +'</span>';
                tr.insertCell(2).innerHTML = (IsAbnormal !="" ? '<span class="abnormal" style="margin-right: 20px">'+IsAbnormal+'</span>' : '');
                tr.insertCell(3).innerHTML = sample_tests.unit_sign;
                tr.insertCell(4).innerHTML = '<span class="name result-font">'+ sample_tests.ref_range +'</span>';
                tr.cells[4].style.textAlign = 'center'
            }
            else{
                tr.insertCell(1).innerHTML = ''+ (sample_tests.field_type == 0 ? '' : '') + manipulatePrintOrganismResult(sample_tests) +'</span>';
                tr.cells[1].colSpan=4
            }
        }

        tr.cells[0].style.paddingLeft = (5 * level * 2.5) + 'px'
        tr.cells[0].style.width="380px";

        if(IsAbnormal!=''){
            tr.cells[1].classList.add('abnormal')
        }
        if (sample_tests.field_type == 0) {
            tr.cells[0].classList.add('pl-' + (level * 2))
        }
        $('#' + closet_parent_id).append(tr);
        if(sample_tests.description!=""){
            renderPrintTestItemDescriptionRow(sample_tests, level, closet_parent_id);
        }
        if(sample_tests.comment!=""){
            renderPrintTestItemCommentRow(sample_tests, level, closet_parent_id);
        }

    }
}

function renderPrintTestItemDescriptionRow(sample_tests, level, closet_parent_id)
{
    if(sample_tests.is_show == 1) {

        let tr = document.createElement('TR');
        tr.setAttribute('valign', 'top');
        tr.insertCell(0).innerHTML = (sample_tests.description!=="" ? '<p class="pl-4 pt-2">'+sample_tests.description+'</p>' : '');
        tr.cells[0].style.paddingLeft = (5 * level * 5) + 'px'
        tr.cells[0].colSpan=5
        if (sample_tests.field_type == 0) {
            tr.cells[0].classList.add('pl-' + (level * 2))
        }
        $('#' + closet_parent_id).append(tr);
    }
}

function renderPrintTestItemCommentRow(sample_tests, level, closet_parent_id)
{
    if(sample_tests.is_show == 1) {

        let tr = document.createElement('TR');
        tr.setAttribute('valign', 'top');
        tr.insertCell(0).innerHTML = (sample_tests.comment!=="" ? '<div style="padding-left: 15px; float:left; font-weight:bold;">Comment: </div><div style="padding-left:85px;  margin-top: 0px;  margin-left:10px;">'+sample_tests.comment+'</div>' : '');
        tr.cells[0].style.paddingLeft = (5 * 0) + 'px'
        tr.cells[0].colSpan=5
        if (sample_tests.field_type == 0) {
            tr.cells[0].classList.add('pl-' + (0 * 2))
        }
        $('#' + closet_parent_id).append(tr);
    }
}

function computeRefRange(sample_tests) {
    if(sample_tests.min_ref_val=='' || sample_tests.max_ref_val=='' || sample_tests.test_result=='' || sample_tests.ref_range == '') return ''
    /*else if([">",">=","<","<=","-","Neg <", "Neg<","≤","≥"].includes(sample_tests.sign)){
        if(parseFloat(sample_tests.test_result) > parseFloat(sample_tests.max_ref_val)) return 'H';
        if(parseFloat(sample_tests.test_result) < parseFloat(sample_tests.min_ref_val)) return 'L';
        else return ''*/
    else if([/*">",">=","<","<=",*/"-"].includes(sample_tests.sign)){
        if(parseFloat(sample_tests.test_result) > parseFloat(sample_tests.max_ref_val)) return 'H';
        if(parseFloat(sample_tests.test_result) < parseFloat(sample_tests.min_ref_val)) return 'L';
        else return ''
    }else if(["<=","Neg <", "Neg<","≤","<"].includes(sample_tests.sign)){
        if(parseFloat(sample_tests.test_result) > parseFloat(sample_tests.max_ref_val)) return 'H';
        else return ''
    }else if([">",">=","≥"].includes(sample_tests.sign)){
        //console.log(parseFloat(sample_tests.test_result), "  : "+ parseFloat(sample_tests.max_ref_val))
        if(parseFloat(sample_tests.test_result) < parseFloat(sample_tests.max_ref_val)){ return 'L'; }
        else { console.log('h',sample_tests); return ''; }
    }
    else if(["0.0"].includes(sample_tests.sign)){
        if(parseFloat(sample_tests.test_result) > parseFloat(sample_tests.max_ref_val)) return 'H';
        if(parseFloat(sample_tests.test_result) < parseFloat(sample_tests.min_ref_val)) return 'L';
        else return ''
    }
    else return ''
}


function manipulatePrintOrganismResult(sample_tests) {

    if(sample_tests.field_type == 0){
        return ''
    } else if(["2","3"].includes(sample_tests.field_type)){
        let orgCount = 0;
        return (sample_tests.org_results.length<1 ? ': Pending' : sample_tests.org_results.map(function (value) {
            let anti_text =''
            orgCount+=1;
            antibiotic_results.map(function (anti) {
                if(anti.organism_id == value.organism_id && anti.test_organism_id == value.test_organism_id && anti.sensitive!=''){
                    anti_text+= '<p class="value-pair" style="width: 90% !important; position: relative;"><span class="name" style="padding-left: 10px; '+(anti.sensitive=='R' ? 'font-weight:bold':'')+'"> - '+anti.name_en+'</span> <span class="name" style="float: right; '+(anti.sensitive=='R' ? 'font-weight:bold':'')+'">'+anti.sensitive+'</span></p>';
                }
            });
            if(anti_text!=''){
                return '<p class="value-pair" style="width: 90% !important; position: relative; margin-top:2px !important;"> <span class="name result-font">'+(orgCount==1?': ':'&nbsp;&nbsp;') +'</span>'+ ((value.is_bold==1) ? '<span class="abnormal name">' + value.organism_name +'</span>' : '<span class="name">' + value.organism_name + '</span>') +' <span class="name" style="float: right;"> '+ (value.quantity_name !=null ? value.quantity_name : '')+'</span> </p>' + anti_text;
            }
            else{
                return ': ' +((value.is_bold==1) ? '<span class="abnormal">'+ value.organism_name+'</span>' : value.organism_name) +' '+ (value.quantity_name !=null ? value.quantity_name : '') +'</br>'
            }

        }).join(' '))
    } else if(sample_tests.field_type == 1){
        return '<span class="name result-font">: ' + (sample_tests.test_result.length<1 ? 'Pending' : sample_tests.test_result) + '</span>'
    }
    else{
        return '<span class="name result-font">: ' + (sample_tests.test_result.length<1 ? 'Pending' : sample_tests.test_result) + '</span>'
    }
}
