$(document).ready(function () {

    $('.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();
    });

    $('.custom-input').on('focus focusout', function(){
        if($(this).val() == null || $(this).val() == '')
        {
            $($(this).parent()).removeClass('hastext');
        }
        else
        {
            $($(this).parent()).addClass('hastext');
        }
    });


    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);
                }
            }
        }
    });

    $('#endo_tab_link').on('click', function()
    {
        load__endo_history(true);
    });

    $('#nn_tab_link').on('click', function()
    {
        load__endo_history(true);
    });

    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){
        $('#endo_history').empty();
        if(rvn)
        {
            reload_visit_info();
            return;
        }
        $.ajax({
            type:'GET',
            url: '/get_visit_info_alt/'+$('#visit_id').val(),
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentTypestatus
            success: (data) => {
                $('#endo_history').empty();
                var label_id = 0
                console.log(data['pics'])
                for (pic_num in data['pics'])
                {
                    pic = data['pics'][pic_num]
                    organ = ''
                    if (pic['organ'])
                    {
                        organ = pic['organ']
                    }
                    type = 'image'
                    parts = pic['hash_name'].split('.')
                    if (['avi', 'mp4', 'webm', 'mkv', 'flv', 'wmv', 'mpeg'].includes(parts[parts.length - 1])) {
                        type = 'video'
                    }
                    if(pic.hasOwnProperty('nn_tag'))
                    {
                        //Нейросеть
                        if($('#language').val() == 'ru')
                            $('#endo_history').append('<tr><td scope="col" id="click"><img src=/img/'+pic['hash_name']+' class="preview_img" data-path_file=' + pic['hash_name'] + ' data-type_file=' + type + '></td><td scope="col"><span class="expert_diagnos" data-img='+pic['hash_name']+'>'+pic['nn_icd']+' '+pic['nn_tag']+'</span><span class="standart_modal btn btn-primary btn-sm" data-code="'+pic['nn_icd']+'">Стандарт</span></td><td scope="col"><select data-img='+pic['hash_name']+' id="ds'+label_id+'" type="select" class="form-control diagnoses_select"><option value="" disabled="" selected="">Диагноз</option></select><span class="standart_modal btn btn-secondary btn-sm" data-code="">Стандарт<span></td></tr>');
                        else
                            $('#endo_history').append('<tr><td scope="col" id="click"><img src=/img/'+pic['hash_name']+' class="preview_img" data-path_file=' + pic['hash_name'] + ' data-type_file=' + type + '></td><td scope="col"><span class="expert_diagnos" data-img='+pic['hash_name']+'>'+pic['nn_icd']+' '+pic['nn_tag']+'</span><span class="standart_modal btn btn-primary btn-sm" data-code="'+pic['nn_icd']+'">Standart</span></td><td scope="col"><select data-img='+pic['hash_name']+' id="ds'+label_id+'" type="select" class="form-control diagnoses_select"><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')
                            $('#endo_history').append('<tr><td scope="col"><img src=/img/'+pic['hash_name']+' class="preview_img" data-path_file=' + pic['hash_name'] + ' data-type_file=' + type + '></td><td scope="col"><span class="expert_diagnos" data-img='+pic['hash_name']+'></span><span class="standart_modal btn btn-secondary btn-sm" data-code="">Стандарт</span></td><td scope="col"><select data-img='+pic['hash_name']+' id="ds'+label_id+'" type="select" class="form-control diagnoses_select"><option value="" disabled="" selected="">Диагноз</option></select><span class="standart_modal btn btn-secondary btn-sm" data-code="">Стандарт</span></td></tr>');
                        else
                            $('#endo_history').append('<tr><td scope="col"><img src=/img/'+pic['hash_name']+' class="preview_img" data-path_file=' + pic['hash_name'] + ' data-type_file=' + type + '></td><td scope="col"><span class="expert_diagnos" data-img='+pic['hash_name']+'></span><span class="standart_modal btn btn-secondary btn-sm" data-code="">Standart</span></td><td scope="col"><select data-img='+pic['hash_name']+' id="ds'+label_id+'" type="select" class="form-control diagnoses_select"><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.hasOwnProperty('confirmed')){
                        if(pic['confirmed'] == true)
                        {
                            $.each($('.expert_diagnos'), function(e) {
                                if($(this).data('img') == pic[0]['hash_name'])
                                {
                                    console.log(pic[0]['icd']);
                                    $(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');
                                }
                            })
                        }
                        else{
                            $.each($('.diagnoses_select'), function(e) {
                                if($(this).data('img') == pic['hash_name'])
                                {
                                    $(this).val(pic['tag_id']);
                                    $(this).parent().children('.standart_modal').data('code', pic['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'));
                })
                $('.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 OK FOR MULTIPROFILE
    function save_select(element){
//        console.log(element.value);
//        console.log($(element).data('img'));
        var message = {
            diagnos_id: element.value,
            pic_name: $(element).data('img'),
            visit_id: $('#visit_id').val(),
        }
        $.ajax({
            type:'POST',
            url: '/save_pic_diagnos',
            async: !1,
            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('\\',''))
    }

    var getUrlParameter = 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;
    };

    function standart_load(code, full, tag_id){
        $('#cur_modal_std').val(code);
        $('#cur_modal_tag_id').val(tag_id);
        lang = getUrlParameter('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>');
                    try{
                        if(data['standart_text_en'] != undefined){
                            $('#standart_body').append('<hr>');
                            $('#standart_body').append('<p class="mt-3">'+data['standart_text_en']+'</p>');
                        }
                    }
                    catch(e)
                    {
                        console.log('error_standart_text_en')
                    }
                }
                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>');
                    try{
                        if(data['standart_text'] != undefined)
                        {
                            $('#standart_body').append('<hr>');
                            $('#standart_body').append('<p class="mt-3">'+data['standart_text']+'</p>');
                        }
                    }
                    catch(e)
                    {
                        console.log('error_standart_text')
                    }
                }
                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);
    });

    $('#start_rec').on("click", function()
    {
        if($('#btnradio_ear').is(":checked"))
            startRec('source');
        else
            loadWOrec('source');
    });

    $('#save_picture').on("click", function()
    {
        if($('#btnradio_ear').is(":checked"))
            startRec('webcam');
        else
            loadWOrec('webcam');
    });

    function makeblob(dataURL) {
        var BASE64_MARKER = ';base64,';
        if (dataURL.indexOf(BASE64_MARKER) == -1) {
            var parts = dataURL.split(',');
            var contentType = parts[0].split(':')[1];
            var raw = decodeURIComponent(parts[1]);
            return new Blob([raw], { type: contentType });
        }
        var parts = dataURL.split(BASE64_MARKER);
        var contentType = parts[0].split(':')[1];
        var raw = window.atob(parts[1]);
        var rawLength = raw.length;

        var uInt8Array = new Uint8Array(rawLength);

        for (var i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
        }

        return new Blob([uInt8Array], { type: contentType });
    }

    function loadWOrec(from){
        $('#start_rec').attr("disabled", true);
        $('#save_picture').attr("disabled", true);
        $('#request_waiting').show();
        $('#progress_text').html('Загрузка снимков');
        var organ = 0

        var fileList = document.getElementById('file_input').files;
        var formData = new FormData();
        var poll = null;
        var i = 0
        if (from == 'source')
            for(i=0;i<fileList.length;i++)
            {
                if (fileList[i].type.includes('image'))
                {
                    formData.append("files", fileList[i]);
                    i += 1;
                }
            }
        if (from == 'webcam')
            $.each($('.endo_image'), function(e) {
                formData.append("files", makeblob($(this).attr('src')));
                i += 1;
            });
        if (i > 0)
        {
            $.ajax({
                type:'POST',
                data: formData,
                url: '/save_images?patient_id='+$('#patient_id').val()+'&organ='+organ+'&visit_id='+$('#visit_id').val()+'&profarea_id='+'2',
                processData: false,  // tell jQuery not to process the data
                contentType: false,  // tell jQuery not to set contentType
                success: (data) => {
                    $('#photos').empty();
                    $('#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();
                },
                error:function (jqXHR, exception) {
                    $('#start_rec').attr("disabled", false);
                    $('#save_picture').attr("disabled", false);
                    $('#request_waiting').hide();
                    after_error();
                }
            });
        }
        else
        {
            $('#start_rec').attr("disabled", false);
            $('#save_picture').attr("disabled", false);
            $('#request_waiting').hide();
            after_error();
        }
    }


    function startRec(from){
        $('#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
        var img_in_params = ''
        if (from == 'source')
            for(i=0;i<fileList.length;i++)
            {
                if (fileList[i].type.includes('image'))
                {
                    formData.append("files", fileList[i]);
                    i += 1;
                }
            }
        if (from == 'webcam')
            $.each($('.endo_image'), function(e) {
                if($(this).data('type') == "blob")
                    formData.append("files", makeblob($(this).attr('src')));
                else
                {
                    formData.append("files", $(this).attr('src'));
                    img_in_params = img_in_params + $(this).data('name') + ','
                }
                i += 1;
            });
        let searchParams = new URLSearchParams(window.location.search)
        force_ear = searchParams.has('force_ear');

        if (i > 0)
        {
            $.ajax({
                type:'POST',
                data: formData,
                url: '/start_flebo_image_diagnostics?patient_id='+$('#patient_id').val()+'&visit_id='+$('#visit_id').val() + '&imgs='+img_in_params + '&force_ear='+force_ear+'&lang=' + lang,
                processData: false,  // tell jQuery not to process the data
                contentType: false,  // tell jQuery not to set contentType
                success: (data) => {
                    $('#photos').empty();
                    $('#imgs_preview').empty();
                    $('#file_input').val(null);
                    $('#pre_load').show();
                    $('#file-input-greenspan').html('');
                    $('#progress_text').html('Распознание диагноза');
                    if(data['status_id'] == 0)
                        poll = setTimeout(function() { check_image_output(data['id']); }, 2500);
                    if(data['status_id'] == 1)
                        poll = setTimeout(function() { check_image_output(data['id']); }, 2500);
                    if(data['status_id'] == 2)
                    {
                        $('#start_rec').attr("disabled", false);
                        $('#save_picture').attr("disabled", false);
                        $('#request_waiting').hide();
                        $('#success').html('Загрузка завершена, снимок доступен в истории')
                        $('#success').slideDown(500);
                        $('#success').delay(2000).slideUp();
                        load__endo_history(true);
                    }
                    if(data['status_id'] == 3)
                        after_error();
                },
                error:function (jqXHR, exception) {
                    $('#photos').empty();
                    $('#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();
                }
            });
        }
        else
        {
            $('#start_rec').attr("disabled", false);
            $('#save_picture').attr("disabled", false);
            $('#request_waiting').hide();
            after_error();
        }
    }

    function check_image_output(task_id)
    {
        $.ajax({
            type:'GET',
            url: '/flebo_status/'+task_id,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: (data) => {
//                console.log(data);
                if('status_id' in data){
                    if(data['status_id'] == 0)
                        poll = setTimeout(function() { check_image_output(data['id']); }, 2500);
                    if(data['status_id'] == 1)
                        poll = setTimeout(function() { check_image_output(data['id']); }, 2500);
                    if(data['status_id'] == 2)
                    {
                        $('#start_rec').attr("disabled", false);
                        $('#save_picture').attr("disabled", false);
                        $('#request_waiting').hide();
                        $('#success').html('Загрузка завершена, снимок доступен в истории')
                        $('#success').slideDown(500);
                        $('#success').delay(2000).slideUp();
                        load__endo_history(true);
                    }
                    if(data['status_id'] == 3)
                    {
                        after_error();
                    }
                }
                else
                {
                    after_error();
                }
            },
            error:function (jqXHR, exception) {
                after_error();
            }
        });
    }

    function select_fill(){
        lang = getUrlParameter('lang');
        $.ajax({
            type:'GET',
            url: '/get_diagnos_tags/2'+'?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) {
//                    console.log(data);
                    for(tag_num in data)
                    {
                        var tag = data[tag_num]
//                        console.log(tag);
                        if(tag['category_id'] == null && tag['diagnos'] == true)
                        {
                            var icd = ''
                            if (tag['icd'])
                            {
                                icd = tag['icd'] + ' '
                            }
//                            console.log(icd);
                            $(this).append('<option value="'+tag['id']+'">'+icd+tag['standart_name']+'</option>');
//                            $('#diagnoses_tags').append('<div class="custom-control custom-checkbox my-1 mr-sm-2 checktag"><input type="checkbox" id="tag'+tag['id']
//                            +'" data-name="'+tag['name']+'" class="custom-control-input checkitem"><label for="tag'+tag['id']+'" class="custom-control-label">'+icd+tag['name']+'</label></div>');
                        }

                    }
                });

            },
            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;
    }

});
