$(document).ready(function () {

    $("#fio").select2({
        tags: true
    });
    $("#fio").on("change", function() {
        id = this.value;
        text = $( "#fio option:selected" ).text();
        if (id == text)
        {
            console.log('New Patient');
        }
        else{
            $.ajax({
                type: "GET",
                url: '/get_patient_clinic/' + id,
                processData: false,  // tell jQuery not to process the data
                contentType: false,  // tell jQuery not to set contentType
                success: (data) => {
                    $("#med_card").val(data['card_number']);
                    $("#telephone").val(data['telephone']);
                    $("#dob").val(data['dob']);
                    $("#sex").val(data['sex']);
                    updateInfo();
                }
            })
        }
    })

    load__endo_history(true);

    function getUrlParameter(sParam) {
        var sPageURL = window.location.search.substring(1),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return typeof sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
            }
        }
        return false;
    };

    $('.close-modal').on('click', function(){
        $('#standart_modal').modal('toggle');
    });

    $('#short_std').on('click', function(){
        standart_load($('#cur_modal_std').val(), false, $('#cur_modal_tag_id').val());
        $('#short_std').hide();
        $('#long_std').show();
    });

    $('#long_std').on('click', function(){
        standart_load($('#cur_modal_std').val(), true, $('#cur_modal_tag_id').val());
        $('#short_std').show();
        $('#long_std').hide();
    });

    $('#med_card').on('change', function(){updateInfo()});
    $('#telephone').on('change', function(){updateInfo()});
//    $('#fio').on('change', function(){updateInfo()});
    $('#dob').on('change', function(){updateInfo()});
    $('#sex').on('change', function(){updateInfo()});
    $('#complaints_input').on('change', function(){updateInfo()});
    $('#anamnesis_input').on('change', function(){updateInfo()});

    function complete_med_exam(visit_id){
        var message = {
            visit_id : visit_id
        }
        $.ajax({
            type:'POST',
            url: '/complete_med_exam',
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            data: JSON.stringify(message),
            success: (data) => {
                if(data['success'] == true)
                {
                    show_success('Профосмотр сохранён', false);
                }
                else
                {
                    show_error('Не удалось завершить профосмотр' ,0);
                }
            },
            error:function (jqXHR, exception) {
                show_error('Не удалось завершить профосмотр' ,0);
            }
        });
    }

    $('#clear_med_exam').click(function(){

        $('#med_card').val('');
        $('#telephone').val('');
        $('#fio').val('');
        $('#dob').val('');
        $('#sex').val('');
        $('#complaints_input').val('');
        $('#anamnesis_input').val('');
        $('#short_endo_history').empty();
        let visit_id = $('#visit_id').val();
        complete_med_exam(visit_id);
        updateStatus();
        $.ajax({
            type:'GET',
            url: '/get_new_visit_id',
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: (data) => {
                $('#visit_id').val(data['visit_id']);
                console.log('New visit ID');
                console.log($('#visit_id').val());
            },
            error:function (jqXHR, exception) {
                after_error();
            }
        });

    })

    function updateInfo(){
        updateStatus();
        if ($('#visit_id').val())
            startLoad(null)
        else
            console.log('no visit')
    }

    function previewIMG(input, preview) {
        var reader = new FileReader();
        reader.onload = function(e) {
          $(preview).attr('src', e.target.result);
        }
        reader.readAsDataURL(input);
    }

    $("#file_input").change(function(){
        $('#imgs_preview').empty();
        $('#file-input-greenspan').html('');
        if ($(this)[0].files[0]) {
            $('#pre_load').hide();
            $('#file-input-greenspan').html('Загружено снимков: ' + $(this)[0].files.length);
            for(i=0;i<$(this)[0].files.length;i++)
            {
                if (($(this)[0].files[i].type.includes('image')))
                {
                    div = document.createElement('div');
                    div.setAttribute('class', 'col-3 p-1 m-0');
                    img = document.createElement('img');
                    img.setAttribute('class', 'preview_img');
                    previewIMG($(this)[0].files[i], $(img));
                    div.appendChild(img);
                    document.getElementById("imgs_preview").appendChild(div);
                    startLoad(null);
                }
            }
        }
    });

    function reload_visit_info(){
        lang = getUrlParameter('lang');
        $.ajax({
            type:'GET',
            url: '/reload_visit_info/' + $('#visit_id').val() + '?task=off'+'&lang='+lang,
            processData: false,
            contentType: false,
            success: (data) => {
                //load__endo_history(false);
            }
        });
    }


    function load__endo_history(rvn){
        $('#short_endo_history').empty();
        if(rvn)
            reload_visit_info();
        $.ajax({
            type:'GET',
            url: '/get_visit_info/' + $('#visit_id').val() + '?task=off',
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentTypestatus
            success: (data) => {
                var label_id = 0
                for (untask_num in data['untask_pics'])
                {
                    pic = data['untask_pics'][untask_num]
                    organ = ''
                    if (pic['organ'])
                    {
                        organ = pic['organ']
                    }
                    if($('#language').val() == 'ru')
                        $('#short_endo_history').append('<tr><td scope="col"><img src=/img/'+pic['file']+'?va'+getRandomInt(100)+' class="preview_img"></td><td scope="col"><select data-img='+pic['file']+' id="ds'+label_id+'" type="select" class="form-control diagnoses_select w-100"><option value="" disabled="" selected="">Диагноз</option></select><span class="standart_modal btn btn-secondary btn-sm" data-code="">Стандарт</span></td></tr>');
                    else
                        $('#short_endo_history').append('<tr><td scope="col"><img src=/img/'+pic['file']+'?va'+getRandomInt(100)+' class="preview_img"></td><td scope="col"><select data-img='+pic['file']+' id="ds'+label_id+'" type="select" class="form-control diagnoses_select w-100"><option value="" disabled="" selected="">Diagnosis</option></select><span class="standart_modal btn btn-secondary btn-sm" data-code="">Standart</span></td></tr>');
                    label_id = label_id + 1
                }
                for (task_num in data['tasks'])
                {
                    task = data['tasks'][task_num]

                    if ('task' in task)
                    if (task['task'])
                    if ('result' in task['task'])
                    for (result_num in task['task']['result'])
                    {
                        result = task['task']['result'][result_num]
                        var code = ''
                        var name = ''
                        var probability = 0
                        if ('diseases' in result)
                        for (d_num in result['diseases'])
                        {
                            disease = result['diseases'][d_num]
                            if(disease['probability'] > probability)
                            {
                                probability = disease['probability']
                                code = disease['code']
                                name = disease['name']
                            }
                        }
                        var organ = result['organ']
                        if (organ == undefined)
                            organ = 'Ошибка - '+task['task']['status']
                        if (probability > 0)
                            if($('#language').val() == 'ru')
                                $('#short_endo_history').append('<tr><td scope="col"><img src=/img/'+result['file']+'?va'+getRandomInt(100)+' class="preview_img"></td><td scope="col"><select data-img='+result['file']+' id="ds'+label_id+'" type="select" class="form-control diagnoses_select w-100"><option value="" disabled="" selected="">Диагноз</option></select><span class="standart_modal btn btn-secondary btn-sm" data-code="">Стандарт<span></td></tr>');
                            else
                                $('#short_endo_history').append('<tr><td scope="col"><img src=/img/'+result['file']+'?va'+getRandomInt(100)+' class="preview_img"></td><td scope="col"><select data-img='+result['file']+' id="ds'+label_id+'" type="select" class="form-control diagnoses_select w-100"><option value="" disabled="" selected="">Диагноз</option></select><span class="standart_modal btn btn-secondary btn-sm" data-code="">Standart<span></td></tr>');
                        else
                            if($('#language').val() == 'ru')
                                $('#short_endo_history').append('<tr><td scope="col"><img src=/img/'+result['file']+'?va'+getRandomInt(100)+' class="preview_img"></td><td scope="col"><select data-img='+result['file']+' id="ds'+label_id+'" type="select" class="form-control diagnoses_select w-100"><option value="" disabled="" selected="">Диагноз</option></select><span class="standart_modal btn btn-secondary btn-sm" data-code="">Стандарт<span></td></tr>');
                            else
                                $('#short_endo_history').append('<tr><td scope="col"><img src=/img/'+result['file']+'?va'+getRandomInt(100)+' class="preview_img"></td><td scope="col"><select data-img='+result['file']+' id="ds'+label_id+'" type="select" class="form-control diagnoses_select w-100" ><option value="" disabled="" selected="">Диагноз</option></select><span class="standart_modal btn btn-secondary btn-sm" data-code="">Standart<span></td></tr>');
                        label_id = label_id + 1
                    }
                }
                select_fill();
                for (pic_num in data['pics'])
                {
                    pic = data['pics'][pic_num]
                    if (pic.length > 0){
                        if(pic.length > 1)
                        {
                            console.log('Обнаружены снимки с дублирующимся описанием')
                        }

                        $.each($('.diagnoses_select'), function(e) {
                            if($(this).data('img') == pic[0]['hash_name'])
                            {
                                $(this).val(pic[0]['tag_id']);
                                $(this).parent().children('.standart_modal').data('code', pic[0]['icd']);
                                $(this).parent().children('.standart_modal').removeClass('btn-secondary');
                                $(this).parent().children('.standart_modal').addClass('btn-primary');
                            }
                        })
                    }
                }

                for (pic_num in data['expert_pics'])
                {
                    pic = data['expert_pics'][pic_num]
                    if (pic.length > 0){
                        if(pic.length > 1)
                        {
                            console.log('Обнаружены снимки с дублирующимся экспертым описанием')
                        }

                        $.each($('.expert_diagnos'), function(e) {
                            if($(this).data('img') == pic[0]['hash_name'])
                            {
                                $(this).html(pic[0]['icd']+' '+pic[0]['tag'])
                                $(this).parent().children('.standart_modal').data('tag_id', pic[0]['tag_id']);
                                $(this).parent().children('.standart_modal').data('code', pic[0]['icd']);
                                $(this).parent().children('.standart_modal').removeClass('btn-secondary');
                                $(this).parent().children('.standart_modal').addClass('btn-primary');
                            }
                        })
                    }
                }
                $('.standart_modal').on('click', function(){
                    $('#standart_modal').modal('toggle');
                    standart_load($(this).data('code'), false, $(this).data('tag_id'));
                })
                $('.preview_img').click(function(){
                    $(this).attr('src', $(this).attr('src')+getRandomInt(99));
                })
                $('.diagnoses_select').on('change', function() {
                    save_select(this);
                    $(this).parent().children('.standart_modal').removeClass('btn-secondary');
                    $(this).parent().children('.standart_modal').addClass('btn-primary');
                });
                $('.diagnoses_select').select2();
            },
            error:function (jqXHR, exception) {

            }
        });

    }

    //saving on select change
    function save_select(element){
        var message = {
            diagnos_id: element.value,
            pic_name: $(element).data('img'),
            visit_id: $('#visit_id').val(),
        }
        $.ajax({
            type:'POST',
            url: '/save_pic_diagnos',
            async: false    ,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            data: JSON.stringify(message),
            success: (data) => {
                if(data['success'] == true)
                {
                    $(element).parent().children('.standart_modal').data('code', data['icd']);
                    $(element).parent().children('.standart_modal').data('tag_id', data['tag_id']);
                    $('#success').html('Диагноз сохранен');
                    $('#success').slideDown(500);
                    $('#success').delay(2000).slideUp();
                }
                else
                {
                    after_error();
                }
            },
            error:function (jqXHR, exception) {
                after_error();
            }
        });

    }

    function getId(str)
    {
        return(str.replaceAll(' ','').replaceAll(',','').replaceAll('.','').replaceAll(';','').replaceAll(':','').replaceAll('(','').replaceAll(')','').replaceAll('-','').replaceAll('/','').replaceAll('\\',''))
    }

    function standart_load(code, full, tag_id){
        $('#cur_modal_std').val(code);
        $('#cur_modal_tag_id').val(tag_id);
        lang = getUrlParameter('lang');
        console.log('lang - '+lang);
        $.ajax({
            type:'GET',
            url: '/get_diagnos_standart?icd='+code+'&tag_id='+tag_id+'&lang='+lang,
            async: true,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: (data) => {
                $('#standart_body').empty();
                $('#standart_name').html(data['standart_name']);
                if(lang == 'en'){
                    $('#standart_diagnos').html('Diagnosis: <b>' + data['name']+'</b>');
                    $('#standart_type').html('Type of standard: <b>'+data['standart_type']+'</b>');
                    $('#standart_icd_code').html('ICD-10 code: <b>'+data['icd']+'</b>');
                    $('#standart_time').html('Treatment time (days): <b>'+data['days_min']+' - '+data['days_max']+'</b>');
                }
                else
                {
                    $('#standart_diagnos').html('Диагноз: <b>' + data['name']+'</b>');
                    $('#standart_type').html('Вид стандарта: <b>'+data['standart_type']+'</b>');
                    $('#standart_icd_code').html('Код по МКБ-10: <b>'+data['icd']+'</b>');
                    $('#standart_time').html('Сроки лечения (дней): <b>'+data['days_min']+' - '+data['days_max']+'</b>');
                }
                var groups = [];
                for (std_num in data['standart'])
                {
                    var std = data['standart'][std_num]
                    if (!(groups.includes(std['service_type'])))
                    {
                        groups.push(std['service_type'])
                        $('#standart_body').append('<h5>'+std['service_type']+'</h5><div id="group'+getId(std['service_type'])+'"></div>');
                    }
                }
                var sub_groups = [];
                for (std_num in data['standart'])
                {
                    var std = data['standart'][std_num]
                    for (group in groups){
                        if(!($('#group'+getId(std['service_type'])).data('dt'+getId(std['service_subtype'])) == true))
                        {
                            $('#group'+getId(std['service_type'])).data('dt'+getId(std['service_subtype']), true);
                            $('#group'+getId(std['service_type'])).append('<p>'+std['service_subtype']+'</p>');
                            if(lang == 'en')
                                $('#group'+getId(std['service_type'])).append('<table style="width: 100%;" class="table table-striped table-bordered custom-font"><thead><tr><th scope="col">Medical Service Code</th><th scope="col">Name</th><th scope="col">Approximate frequency of presentation</th></tr></thead><tbody id="table'+ getId(std['service_subtype']) + getId(std['service_type'])+'"></tbody></table>');
                            else
                                $('#group'+getId(std['service_type'])).append('<table style="width: 100%;" class="table table-striped table-bordered custom-font"><thead><tr><th scope="col">Код медицинской услуги</th><th scope="col">Наименование</th><th scope="col">Примерная частота представления</th></tr></thead><tbody id="table'+ getId(std['service_subtype']) + getId(std['service_type'])+'"></tbody></table>');
                        }
                    }
                }
                for (std_num in data['standart'])
                {
                    if(full == true){
                        var std = data['standart'][std_num]
                        service_code = ''
                        if (!(std['service_code'] == 'NULL'))
                            service_code = std['service_code']
                        $('#table'+ getId(std['service_subtype']) + getId(std['service_type'])).append(
                            '<tr><td>'+service_code+'</td><td>'+std['standart_name']+'</td><td>'+std['periodicity']+'</td></td>'
                        );
                    }
                    else
                    {
                        var std = data['standart'][std_num]
                        if(std['periodicity'] == '1'){
                            service_code = ''
                            if (!(std['service_code'] == 'NULL'))
                                service_code = std['service_code']
                            $('#table'+ getId(std['service_subtype']) + getId(std['service_type'])).append(
                                '<tr><td>'+service_code+'</td><td>'+std['standart_name']+'</td><td>'+std['periodicity']+'</td></td>'
                            );
                        }
                    }

                }
                $('#copy_text').data('text', data['for_copy'])

            },
            error:function (jqXHR, exception) {
                $('#standart_body').empty();
                $('#standart_name').html('');
                $('#standart_diagnos').html('');
                $('#standart_type').html('');
                $('#standart_icd_code').html('');
                $('#standart_time').html('');
            }
        });
    }


    $('#copy_text').on("click", function(){
        $('#text_to_copy').html($('#copy_text').data('text'));
        function listener(e) {
            str = document.getElementById('text_to_copy').innerHTML
            e.clipboardData.setData("text/html", str);
            e.clipboardData.setData("text/plain", str);
            e.preventDefault();
        }
        document.addEventListener("copy", listener);
        document.execCommand("copy");
        document.removeEventListener("copy", listener);

        $('#copy_text').addClass('check-icn');
        setTimeout(function() {
           $('#copy_text').removeClass('check-icn');
        }, 2000);
    });

    function updateStatus(){
        var piece = 100/7;
        var width = 0;
        if ($('#med_card').val())
            width = width + piece;
        if ($('#telephone').val())
            width = width + piece;
        if ($('#fio').val())
            width = width + piece;
        if ($('#dob').val())
            width = width + piece;
        if ($('#sex').val())
            width = width + piece;
//        if ($('#visit_id').val())
//            width = width + piece;
        if ($('#complaints_input').val())
            width = width + piece;
        if ($('#anamnesis_input').val())
            width = width + piece;
        $('#exam_progress').css('width', width+'%');
    }

    function startLoad(nic_src){
        $('#start_rec').attr("disabled", true);
        $('#save_picture').attr("disabled", true);
        $('#request_waiting').show();
        $('#progress_text').html('Сохранение');
        var lang = getUrlParameter('lang');
        var fileList = document.getElementById('file_input').files;
        var formData = new FormData();
        var poll = null;
        var i = 0
        for(i=0;i<fileList.length;i++)
        {
            if (fileList[i].type.includes('image'))
            {
                formData.append("files", fileList[i]);
                i += 1;
            }
        }
        var params = {
            profarea:$('#visit_profarea').val(),
            med_card:$('#med_card').val(),
            telephone:$('#telephone').val(),
            fio:$('#fio').val(),
            dob:$('#dob').val(),
            sex:$('#sex').val(),
            visit_id:$('#visit_id').val(),
            complaints:$('#complaints_input').val(),
            anamnesis:$('#anamnesis_input').val(),
            lang:lang
        };
        if (nic_src){
            params['src'] = nic_src;
        }
        var str_params = jQuery.param( params );


        $.ajax({
            type:'POST',
            data: formData,
            url: '/save_med_exam?' + str_params,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            async: true,
            success: (data) => {
                $('#visit_id').val(data['visit_id']);
                $('#imgs_preview').empty();
                $('#file_input').val(null);
                $('#pre_load').show();
                $('#file-input-greenspan').html('');
                $('#start_rec').attr("disabled", false);
                $('#save_picture').attr("disabled", false);
                $('#request_waiting').hide();
                updateStatus();
                if(i > 0)
                    load__endo_history(true);
                if(nic_src)
                    load__endo_history(true);
            },
            error:function (jqXHR, exception) {
                $('#imgs_preview').empty();
                $('#file_input').val(null);
                $('#pre_load').show();
                $('#file-input-greenspan').html('');
                $('#start_rec').attr("disabled", false);
                $('#save_picture').attr("disabled", false);
                $('#request_waiting').hide();
                after_error();
            }
        });
    }

    function select_fill(){
        lang = getUrlParameter('lang');
        $.ajax({
            type:'GET',
            url: '/get_diagnos_tags/'+$('#visit_profarea').val()+'?lang='+lang,
            async: false,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: (data) => {

                 $.each($('.diagnoses_select'), function(e) {
                    for(tag_num in data)
                    {
                        
                        var tag = data[tag_num]
                        if(tag['category_id'] == null && tag['diagnos'] == true)
                        {
                            var icd = ''
                            if (tag['icd'])
                            {
                                icd = tag['icd'] + ' '
                            }
                            $(this).append('<option value="'+tag['id']+'">'+icd+tag['standart_name']+'</option>');
                        }

                    }
                });

            },
            error:function (jqXHR, exception) {

            }
        });
    }


    function getRandomInt(max) {
        return Math.floor(Math.random() * Math.floor(max));
    }

    function makeid(length) {
       var result           = '';
       var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
       var charactersLength = characters.length;
       for ( var i = 0; i < length; i++ ) {
          result += characters.charAt(Math.floor(Math.random() * charactersLength));
       }
       return result;
    }
});
