
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 colspan="5" style="text-align: center; font-weight: bold; color: #0000ff !important;">'+sample_type+'</td>' +
        '                               </tr>\n' +
        '<tr>\n' +
        '                                    <th class="sourceserifpro-bold" style="width: 52% !important; color: #0000ff;"><div style="width:380px !important; float:left; height:10px; ">&nbsp;</div></th>\n' +
        '                                    <th class="sourceserifpro-bold" style="width: 15%; color: #0000ff;">&nbsp;&nbsp;&nbsp;&nbsp;Result</th>\n' +
        '                                    <th class="sourceserifpro-bold" style="width: 5%; color: #0000ff;"></th>\n' +
        '                                    <th class="sourceserifpro-bold" style="width: 10%; color: #0000ff;">Units</th>\n' +
        '                                    <th class="sourceserifpro-bold" style="width: 18%; color: #0000ff; text-align: center">Reference Range</th>\n' +
        '                                </tr></thead>\n' +
        '                                <tbody id="test-dep-'+sample_tests.sample_type_id+'"></tbody>'+
        '                                </thead>' +
        '                            </table>'
    return tableData;
}

function manipulateSubHeading(setSelectorId) {
    let subTableHeading = '<table width="100%" border="0" class="_test-result">\n' +
        '                                <thead><tr>\n' +
        '                                    <th class="sourceserifpro-bold" style="/*width: 361px !important;*/ color: #0000ff;"></th>\n' +
        '                                    <th class="sourceserifpro-bold" style="width: 2cm; color: #0000ff;">Result</th>\n' +
        '                                    <th class="sourceserifpro-bold" style="width: 0.5cm; color: #0000ff;"></th>\n' +
        '                                    <th class="sourceserifpro-bold" style="width: 1.5cm; color: #0000ff;">Units</th>\n' +
        '                                    <th class="sourceserifpro-bold" style="width: 3.5cm; color: #0000ff; text-align: center">Reference Range</th>\n' +
        '                                </tr>\n' +
        '                                <tbody id='+setSelectorId+'></tbody>'+
        '                                </thead>' +
        '</table>'
    return subTableHeading
}

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);
    //var subtr = document.createElement('TR');
    //subtr.insertCell(0).innerHTML = manipulateSubHeading('test-dep-'+sample_tests.sample_type_id);
    //$('#'+wrapperId).append(subtr);
}

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="font-size:13pt !important;" class="name">' + sample_tests.test_name + '</span></p>') + ''; // + (sample_tests.description!="" ? '<p class="pl-4 pt-2">'+sample_tests.description+'</p>' : '');
        //tr.cells[0].classList.add('tname')
        if(["2","3"].includes(sample_tests.field_type)){
            tr.insertCell(1).innerHTML = (sample_tests.field_type == 0 ? '' : '<span style="margin-right:10px;">:</span>  ') + manipulatePrintOrganismResult(sample_tests) // (sample_tests.field_type!=0 ? (sample_tests.test_result.length<1 ? 'Pending' : sample_tests.test_result) : '');
            tr.cells[1].colSpan=4
        }else{
            tr.insertCell(1).innerHTML = '<span class="name" style="font-family: \'Times New Roman\', Times, serif;">'+ (sample_tests.field_type == 0 ? '' : '<span style="margin-right:10px;">:</span> ') + manipulatePrintOrganismResult(sample_tests) +'</span>'; // (sample_tests.field_type!=0 ? (sample_tests.test_result.length<1 ? 'Pending' : sample_tests.test_result) : '');
            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" style="font-family: \'Times New Roman\', Times, serif;">'+ sample_tests.ref_range +'</span>';
            tr.cells[4].style.textAlign = 'center'
        }

        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 return ''
}


function manipulatePrintOrganismResult(sample_tests) {

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