// Load test items and settings

$('#modal-assign-test').on('show.bs.modal', function (event) {
    $.ajax({
        url: get_refs_base_url + '/test-items',
        type:"GET",
        dataType:"json",
        success:function(response){
            $('#test-item-list').html('')
            if(response.success){
                testSamples = []
                response.data.map(item=> {

                    if (item.samples.length > 0) {
                        var container = document.createElement('DIV')
                        container.classList.add("p-0","col-lg-3","col-sm-12","px-2","my-2","bg-white","department-test")
                        container.setAttribute('data-id', item.department_id)

                        var departmentDev = document.createElement('DIV');
                        departmentDev.classList.add("group-test-box","p-0","border","bg-white")

                        item.samples.map(sampleType => {

                            sampleType.testSamples.map(suggestionItem =>{
                                let name = (suggestionItem.code!='' && suggestionItem.code!=null ? (suggestionItem.code + ' - ') : '') + suggestionItem.test_name
                                let suggestionPayload = {id: suggestionItem.id, name: name, code: (suggestionItem.code==null ? '' : suggestionItem.code) }
                                testSamples.push(suggestionPayload)
                            })

                            var sampleTypeGroup = document.createElement('DIV');
                            sampleTypeGroup.classList.add('sample-type-wrapper')
                            sampleTypeGroup.setAttribute('data-sample-type-id', sampleType.id)
                            sampleTypeGroup.setAttribute('id', 'dsample-'+sampleType.id)

                            var sampleTypeHeader = document.createElement('DIV')
                            sampleTypeHeader.classList.add('px-3','font-13','py-2')
                            sampleTypeHeader.style.backgroundColor=sampleType.bg_color
                            sampleTypeHeader.style.color=sampleType.color
                            sampleTypeHeader.innerHTML = '<i class="mdi mdi-hand-pointing-right mr-1"></i><b>'+sampleType.name_en+'</b>'

                            var sampleTypeHeaderDec = document.createElement('DIV')
                            sampleTypeHeaderDec.classList.add('px-3','bg-light','font-13','py-2')

                            var descriptionSelection = document.createElement('SELECT');
                            descriptionSelection.setAttribute('name','sample-desc')
                            descriptionSelection.setAttribute('id','sample-desc-'+sampleType.id)
                            descriptionSelection.style.height='25px';
                            descriptionSelection.classList.add('form-control','form-control-xxs','rounded-0','sample-desc','p-0')
                            if(sampleType.descriptions!=null){
                                var blankOption = document.createElement('OPTION');
                                descriptionSelection.append(blankOption)
                                sampleType.descriptions.map(function (descItem) {
                                    var descriptionsItem = document.createElement('OPTION');
                                    descriptionsItem.setAttribute('value',descItem.toString());
                                    descriptionsItem.text = descItem;
                                    descriptionSelection.append(descriptionsItem)
                                })
                            } else{
                                var descriptionsItem = document.createElement('OPTION');
                                descriptionsItem.setAttribute('value','');
                                descriptionsItem.text = 'Sample Description';
                                descriptionSelection.append(descriptionsItem)
                            }
                            /* //sample-type-color
                            var lb = document.createElement('LABEL')
                            lb.classList.add('p-0','col-sm-12','font-13')
                            lb.innerText = 'Sample Description'
                            sampleTypeHeader.append(lb)
                            */

                            sampleTypeHeaderDec.append(descriptionSelection)

                            sampleTypeGroup.append(sampleTypeHeader)
                            sampleTypeGroup.append(sampleTypeHeaderDec)
                            let listUnstyle1 = document.createElement('ul');
                            listUnstyle1.classList.add('list-unstyled')

                            let sampleTest = list_to_tree(sampleType.testSamples)
                            sampleTest.map(testOption => {
                                let testLevel1 = document.createElement('LI');
                                let textLevel1CheckBox = document.createElement('DIV');
                                textLevel1CheckBox.classList.add('form-check','d-inline')
                                textLevel1CheckBox.innerHTML = '<label '+(testOption.children.length ? 'onclick="checkAll(\'st-'+testOption.id+'\',\'check-item-'+testOption.id+'\')"' : '')+' class="form-check-label d-inline font-13 st-'+testOption.id+'"><input name="sample_tests[]" data-price="'+testOption.price+'" data-group-result="'+testOption.group_result+'" type="checkbox" id="st-'+testOption.id+'" value="' + testOption.id + '" class="form-check-input sample-test check-item-'+testOption.id+'"> ' + testOption.test_name + ' <i class="input-helper"></i></label> '+(testOption.children.length ? '': '<span class="float-right '+(testOption.group_result!='' && parseFloat(testOption.price)>0 ? '':'d-none')+'" style="top: 0; right: 0;">$ ' + toFixedNumber(testOption.price, 2) + '</span>');
                                // Child First Level
                                if(testOption.children.length){
                                    testLevel1.classList.add('heading')
                                    let indicator1 = document.createElement('i')
                                    indicator1.classList.add('indicator','mdi','mdi-plus-circle')
                                    indicator1.addEventListener('click', function () {
                                        $('li .ul-'+testOption.id).slideToggle();
                                        if(indicator1.classList.contains('mdi-plus-circle')){
                                            indicator1.classList.remove('mdi-plus-circle')
                                            indicator1.classList.add('mdi-minus-circle')
                                        }else{
                                            indicator1.classList.remove('mdi-minus-circle')
                                            indicator1.classList.add('mdi-plus-circle')
                                        }
                                    })
                                    testLevel1.append(indicator1)
                                    testLevel1.append(textLevel1CheckBox)
                                    let children = testOption.children
                                    let listUnstyle2 = document.createElement('ul');
                                    listUnstyle2.classList.add('list-unstyled','ul-'+testOption.id)
                                    children.map(function (child){
                                        let testLevel2 = document.createElement('LI');
                                        let textLevel2CheckBox = document.createElement('DIV');
                                        textLevel2CheckBox.classList.add('form-check','d-inline')
                                        textLevel2CheckBox.innerHTML = '<label '+(child.children.length ? 'onclick="checkAll(\'st-'+child.id+'\',\'sub-check-item-'+child.id+'\')"' : '')+' class="form-check-label d-inline font-13 st-'+child.id+'"><input name="sample_tests[]" data-group-result="'+child.group_result+'" type="checkbox" data-price="'+child.price+'" id="st-'+child.id+'" value="' + child.id + '" class="form-check-input sample-test check-item-'+testOption.id+'"> ' + child.test_name + ' <i class="input-helper"> </i><i class="input-helper"> </i></label> '+(child.children.length ? '' : '<span class="float-right '+(child.group_result!='' && parseFloat(child.price)>0 ? '':'d-none')+'" style="top: 0; right: 0;">$ ' + toFixedNumber(child.price, 2) + '</span>');
                                        // Child Second Level
                                        if(child.children.length){
                                            testLevel2.classList.add('heading')
                                            let indicator2 = document.createElement('i')
                                            indicator2.classList.add('indicator','mdi','mdi-plus-circle')
                                            indicator2.addEventListener('click', function () {
                                                $('li .li-ul-'+testOption.id).slideToggle();
                                                if(indicator2.classList.contains('mdi-plus-circle')){
                                                    indicator2.classList.remove('mdi-plus-circle')
                                                    indicator2.classList.add('mdi-minus-circle')
                                                }else{
                                                    indicator2.classList.remove('mdi-minus-circle')
                                                    indicator2.classList.add('mdi-plus-circle')
                                                }
                                            })
                                            testLevel2.append(indicator2)
                                            testLevel2.append(textLevel2CheckBox)
                                            if(child.children.length){
                                                let grandchildren = child.children
                                                let listUnstyle3 = document.createElement('ul');
                                                listUnstyle3.classList.add('list-unstyled','li-ul-'+testOption.id)
                                                grandchildren.map(function (grandchild){
                                                    let testLevel3 = document.createElement('LI');
                                                    testLevel3.classList.add('font-weight-normal')
                                                    let textLevel3CheckBox = document.createElement('DIV');
                                                    textLevel3CheckBox.classList.add('form-check','d-inline')
                                                    textLevel3CheckBox.innerHTML = '<label class="form-check-label d-inline font-13 st-'+grandchild.id+'"><input name="sample_tests[]" data-group-result="'+grandchild.group_result+'" type="checkbox" data-price="'+grandchild.price+'" id="st-'+grandchild.id+'" value="' + grandchild.id + '" class="form-check-input sub-check-item-'+child.id+' sample-test check-item-'+testOption.id+'"> ' + grandchild.test_name + ' <i class="input-helper"></i></label><span class="float-right '+(grandchild.group_result!='' && parseFloat(grandchild.price)>0 ? '':'d-none')+'" style="top: 0; right: 0;">$ ' + toFixedNumber(grandchild.price, 2) + '</span>';
                                                    testLevel3.append(textLevel3CheckBox)
                                                    listUnstyle3.append(testLevel3)
                                                    testLevel2.append(listUnstyle3)
                                                })
                                            }
                                        }
                                        else{
                                            testLevel2.classList.add('font-weight-normal')
                                            testLevel2.append(textLevel2CheckBox)
                                        }
                                        listUnstyle2.append(testLevel2)
                                    })
                                    testLevel1.append(listUnstyle2)
                                }
                                else{
                                    testLevel1.classList.add('font-weight-normal')
                                    testLevel1.append(textLevel1CheckBox)
                                }
                                listUnstyle1.append(testLevel1)

                            })
                            sampleTypeGroup.append(listUnstyle1)
                            departmentDev.append(sampleTypeGroup)
                            container.append(departmentDev)
                        })
                        $('#test-item-list').append(container);
                    }
                })

                if(sample_id!=0){
                    getSampleTestItem()
                }

               // console.log(testSamples)
                autocomplete(document.getElementById("mySearchTest"), testSamples);

            }
        }

    });
});

$('#modal-assign-test').find(".btnAssignTest").on("click", function (evt) {
    evt.preventDefault();
    let isAddResult = ($(this).attr('value')=='save_test_and_add_result') ? true : false
    var sample_tests	= [];
    var sample_details	= [];
    var test_payments   = {};
    var sample_id = $('#modal-assign-test').find("input[name=sample_id]").val();
    var data_source = $('#modal-assign-test').find("input[name=sample_id]").attr('data-source')
    $('#modal-assign-test').find(".modal-body .department-test").each(function () {
        var $department_samples = $(this).find("div.sample-type-wrapper");
        if ($department_samples.length > 0) {
            $department_samples.each(function () {
                var sample_type_id		= Number($(this).data('sample-type-id'));
                var $selected_tests	= $(this).find(":checkbox.sample-test:checked");
                var $sample_desc	= $(this).find("select.sample-desc");
                //var first_weight	= $(this).find("input[name=first_weight]").val();
                //var second_weight	= $(this).find("input[name=second_weight]").val();
                $(this).find(":checkbox.sample-test").each(function () {
                    var checkbox = $(this).get(0);
                    var id = $(this).val();
                    if (checkbox && checkbox.indeterminate && id > 0) {
                        sample_tests.push(id);
                    }
                });

                if ($selected_tests.length > 0) {
                    if (!isNaN(sample_type_id) && sample_type_id > 0 && $sample_desc.length > 0) {
                        sample_details.push({
                            'sample_id' : sample_id,
                            'sample_type_id'	: sample_type_id,
                            'sample_description'	: $sample_desc.val(),
                            //'first_weight'			: first_weight === undefined ? null : first_weight,
                            //'second_weight'			: second_weight === undefined ? null : second_weight,
                        });
                    }

                    //Selected test
                    $selected_tests.each(function () {
                        var val = Number($(this).val());
                        if (!isNaN(val) && val > 0) sample_tests.push(val);

                        var group_result = $(this).data("group-result");
                        var price        = $(this).data("test-price") || 0;
                        if (group_result && price > 0) {
                            /**Added: 13-11-2022 remove all characters exept number and alphabet */
                            var group_result_ind = group_result.replace(/[^A-Za-z0-9]/g,"");
                            group_result_ind = group_result_ind.replace(" ", "");
                            //End
                            test_payments[group_result_ind] = {
                                group_result: group_result,
                                price: parseFloat(price)
                            };
                        }
                    });
                }
            });
        }
    });

    if (sample_tests.length === 0 || sample_id=='') {
        var res = {success: false, message: "Couldn't save assign tests!​ Please contact system administrator."}
        customErrorAlert(res)
        return false;
    }

    $.ajax({
        url: sample_base_url.toString()+'/assign-test',
        type:"POST",
        dataType:"JSON",
        data :{
            "_token": csrf_token,
            sample_id: sample_id,
            sample_tests : sample_tests,
            sample_details	: sample_details,
        },
        success:function(res){
            if(res.success){
                if(isAddResult){
                    if(data_source == 'new_sample'){
                        window.location = sample_base_url + '/edit/'+sample_id+'?add-result'
                    }
                    $('#modal-assign-test .close').click();
                    $('#sample-forms #btnAddTestResult').click()
                }
                else alertify.success("Test already assigned.")

            }else{
                customErrorAlert(res)
            }
        },
        error:function(error){
            customErrorAlert(error)
        }
    });

});

/** LOAD test and set default check state or value */

var $modal_test				= $("#modal-assign-test");
var $sample_forms			= $("#sample-forms");

//$sample_forms.on("click", ".btnShowTestModal", function (evt) {
   // evt.preventDefault();

    //$modal_test.find("input[type=text]").val('');
    //$modal_test.find(".total-test-payment").val(0);
    //$modal_test.find("select").val(-1);
    //$modal_test.find(".tree-filter").trigger("keyup");
    //$modal_test.find('.tree-list input[type=checkbox].sample-test').iCheck('uncheck');

  /*
    var form		= $(this).parents("form.frm-sample-entry");
    var sampleForm 	= new SampleForm(form);
    var data		= sampleForm.get_data();
  */


//});

function getSampleTestItem() {
    $.ajax({
        url		 : sample_base_url +'/' + sample_id + '/tests',
        type	 : 'get',
        data	 : {},
        dataType : 'json',
        success	 : function (resource) {
            if(resource.success) {
                let totalPrice = 0
                let totalTest = 0
                res = resource.data
                $('#modal-assign-test .modal-header .sample-number').html(res.sample_number)
                $('#modal-assign-test .modal-header .patient-code').html(res.patient.uuid)
                $('#modal-assign-test .modal-header .patient-name').html(res.patient.name)
                $('#modal-assign-test .modal-header .sample-source').html(res.sample_source.name)
                $('#modal-assign-test #sample-id').val(res.id)
                if (res.sample_tests && Array.isArray(res.sample_tests) && res.sample_tests.length > 0) {
                    for (var i in res.sample_tests) {
                        $modal_test.find("input#st-" + res.sample_tests[i].test_sample_id).iCheck('check');
                        //totalPrice+= parseFloat(res.sample_tests[i].usd_price)
                        //totalTest+=1
                    }
                }

                //$('#total-test-payment').text('$ '+parseFloat(totalPrice).toFixed(2))
                //$('#total-test').text(parseInt(totalTest))

                if (res.sample_details && Array.isArray(res.sample_details) && res.sample_details.length > 0) {
                    for (var i in res.sample_details) {
                        var $department_sample  = $modal_test.find("#dsample-" + res.sample_details[i].sample_type_id);
                        if ($department_sample != undefined) {
                           // var $sample_desc    = $department_sample.find("select[name=sample_desc]");
                            var $sample_desc    = $department_sample.find("#sample-desc-"+res.sample_details[i].sample_type_id);
                            //var $first_weight   = $department_sample.find("input[name=first_weight]");
                            //var $second_weight  = $department_sample.find("input[name=second_weight]");
                            if ($sample_desc   != undefined) {
                                $sample_desc.val(res.sample_details[i].sample_descr.toString());
                            }
                           // if ($first_weight  != undefined) $first_weight.val(res.sample_details[i].sample_volume1);
                           // if ($second_weight != undefined) $second_weight.val(res.sample_details[i].sample_volume2);
                        }
                    }
                }
                calculateTestPrice()
            }

        },
        error	 : function () {

        }
    });
}

function checkAll(parentId, targetClass) {
    var checkedState = $('#'+parentId).is(':checked');
    var checkboxes = document.getElementsByClassName(targetClass);
    for (var i = 0; i < checkboxes.length; i++) {
        checkboxes[i].checked = checkedState;
    }
}

function saveTestGroup() {
    var checkboxes = document.getElementsByClassName('sample-test');
    var test_sample_ids = []
    for (var i = 0; i < checkboxes.length; i++) {
        if(checkboxes[i].checked){
            test_sample_ids.push(checkboxes[i].getAttribute('value'))
        }
    }
    if(test_sample_ids.length){
        Swal.fire({
            html:"<p style='float: left;'>Name</p>",
            input: "text",
            showCancelButton: !0,
            position: "center",
            confirmButtonText: "<i class='fa fa-save mr-2'></i>Save",
            cancelButtonText: "Cancel",
            showLoaderOnConfirm: !1,
            confirmButtonColor: "#4fb51a",
            preConfirm: function (n) {
                return new Promise(function (t) {
                    $.ajax({
                        url: get_refs_base_url + '/test-group/save',
                        method:'post',
                        dataType:'json',
                        data:{
                            "_token": csrf_token,
                            name_en: n,
                            test_sample_ids: test_sample_ids
                        },
                        success:function(r)
                        {
                            if(!r.success){
                                Swal.showValidationMessage('Failed while saving test group. ' + r.errors)
                                Swal.enableButtons()
                            }
                            else {
                                t(r.data)
                            }
                        }
                    })
                })
            },
            allowOutsideClick:!1,
        }).then(function (t) {
            if(!t.dismiss){
                t.value.map(item =>{
                    $('#test-group-slot').append('<div class="btn-group mr-2" id="tsg-'+item.id+'" role="group">' +
                        '<button onclick="useTemplate('+item.id+')" class="btn btn-md btn-info rounded-0" type="button"><i class="mdi mdi-checkbox-marked-outline"></i>&nbsp;'+item.group_name+'</button>' +
                        '<button onclick="deleteGroupTemplate('+item.id+')" type="button" class="btn btn-sm btn-inverse-danger"><i class="mdi mdi-close-circle"></i></button>' +
                        '</div>')
                    alertify.success("Reject comment successfully added.")
                })
            }
        })

    }
}

function useTemplate(group_id){
    $.ajax({
        url: get_refs_base_url + '/test-group/get/'+group_id,
        method:'get',
        dataType:'json',
        success:function(r)
        {
            if(r.success){
                $(".sample-type-wrapper input:checkbox").prop('checked', false);
                const templateItems = r.data
                var checkboxes = document.getElementsByClassName('sample-test');
                for (var i = 0; i < checkboxes.length; i++) {
                    //if(templateItems.includes(parseInt(checkboxes[i].getAttribute('value')))){
                    if(templateItems.includes(checkboxes[i].getAttribute('value'))){
                        let sugg_id = checkboxes[i].getAttribute('value');
                        $('.st-'+sugg_id).click();
                    }
                }
            }
        }
    })
}

function deleteGroupTemplate(group_id){
    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: get_refs_base_url + '/test-group/delete/'+group_id,
                method:'POST',
                dataType:"JSON",
                data:{
                    "_token": csrf_token,
                    'id' : group_id
                },
                success:function(response){
                    $('#tsg-'+group_id).hide();
                    handleMessage(response.success, response.message)
                }
            })

        }
    });
}

function calculateTestPrice() {
    let totalPrice = 0, totalTest=0;
    var checkboxes = document.getElementsByClassName('sample-test');
    for (var i = 0; i < checkboxes.length; i++) {
        if(checkboxes[i].checked == true && (checkboxes[i].getAttribute('data-group-result') !="" && checkboxes[i].getAttribute('data-group-result')!="null") && parseFloat(checkboxes[i].getAttribute('data-price')) >0){
            //totalPrice+= parseFloat(checkboxes[i].attr('data-price'))
            totalPrice+= parseFloat(checkboxes[i].getAttribute('data-price'))
            totalTest+=1
        }
        //checkboxes[i].checked = checkedState;
    }
    $('#total-test-payment').text('$ '+parseFloat(totalPrice).toFixed(2))
    $('#total-test').text(parseInt(totalTest))
}

$('#form-assign-test').on('change', ':checkbox', function () {
    calculateTestPrice()
})

