$(document).ready(function () {

     $('#new_only').on('change', function() {
        view_new();
    });

    function view_new(){
        if($('#new_only').prop('checked') == true)
        {
            $.each($('.accordion-item'), function(e) {
                if($(this).attr('data-answer') == 1)
                    $(this).hide();
            });
        }
        else{
            $('.accordion-item').show();
        }
    }

    function reload(){
        $('.diagnoses_select').on('change', function() {
            save_select(this);
        });

        function save_select(element){
            var visit_id = $(element).data('visit_id');
            var message = {
                diagnos_id: element.value,
                pic_id: $(element).data('pic_id'),
            }
            $.ajax({
                type:'POST',
                url: '/save_pic_control_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)
                    {
                        console.log($('#uncf'+visit_id).text())
                        $('#uncf'+visit_id).text($('#uncf'+visit_id).text()-1);
                        if ($('#uncf'+visit_id).text() == 0)
                            $('#uncf'+visit_id).hide()
                    }
                    else
                    {
                        after_error();
                    }
                },
                error:function (jqXHR, exception) {
                    after_error();
                }
            });

        }

        $('.diagnoses_select').select2();

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

        $('.zoom-img').on('click', function(){
            $('#img_modal').modal('toggle');
            $('#zoomed_img').attr('src', $(this).attr('src'));
        })
    }

    $('#accordion_visits').on('hide.bs.collapse', function () {
//        console.log('hide');
    });

    $('#accordion_visits').on('show.bs.collapse', function () {
//        console.log('show');
    });

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

    $('.accordion-collapse').on('show.bs.collapse', function () {
        var visit_id = $(this).data("visit_id");
        var tab_id = '#collapse_body_'+visit_id;
        var lang = getUrlParameter('lang');

        $.ajax({
            type: "GET",
            url: "/get_clinic_select/"+visit_id,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: (data) => {
                var select = $("#select_diagnos")
                console.log(select.attr('id', "#select_diagnos"+visit_id))
                for (cln in data['clinic']) {
                    select.append('<option value='+data['clinic'][cln]['id']+'>'+data['clinic'][cln]['clinic_name']+'</option>')
                }
            }

        })

        $(tab_id).empty();
        $.ajax({
                type:'GET',
                url: '/get_control_visit_info/'+visit_id+'?lang=' + lang,
                async: !1,
                processData: false,  // tell jQuery not to process the data
                contentType: false,  // tell jQuery not to set contentType
                success: (data) => {
                    var row = $('<div class="row"></div>').appendTo($(tab_id));
                    var col2 =  $('<div class="col-2"></div>').appendTo(row);
                    var col10 =  $('<div class="col-10"></div>').appendTo(row);
                    col2.append('<h5>'+data['dict']['complaints']+'</h5>');
                    col10.append('<p>'+data['complaints']+'</p>')
                    var col2 =  $('<div class="col-2"></div>').appendTo(row);
                    var col10 =  $('<div class="col-10"></div>').appendTo(row);
                    col2.append('<h5>'+data['dict']['anamnesis']+'</h5>')
                    col10.append('<p>'+data['anamnesis']+'</p>')
                    var col2 =  $('<div class="col-2"></div>').appendTo(row);
                    var col10 =  $('<div class="col-10"></div>').appendTo(row);
                    col2.append('<h5>'+data['dict']['telephone']+'</h5>')
                    col10.append('<p>'+data['telephone']+'</p>')
                    var col2 =  $('<div class="col-2"></div>').appendTo(row);
                    var col10 =  $('<div class="col-10"></div>').appendTo(row);
                    col2.append('<h5>Email</h5>')
                    col10.append('<p>'+data['email']+'</p>')
                    var col2 =  $('<div class="col-2"></div>').appendTo(row);
                    var col10 =  $('<div class="col-10"></div>').appendTo(row);
                    col2.append('<h5>'+data['dict']['dob']+'</h5>')
                    col10.append('<p>'+data['dob']+'</p>')

                    if (data['pics'].length > 0){
                        var col4_1 =  $('<div class="col-4"></div>').appendTo(row);
                        var col4_2 =  $('<div class="col-4"></div>').appendTo(row);
                        var col4_3 =  $('<div class="col-4"></div>').appendTo(row);
                        col4_1.append('<p>'+data['dict']['snapshot']+'</p>')
                        col4_2.append('<p>'+data['dict']['doctors_diagnosis']+'</p>')
                        col4_3.append('<p>'+data['dict']['expert_diagnosis']+'</p>')
                    }
                    for(pic in data['pics'])
                    {
                        var col4_1 =  $('<div class="col-4"></div>').appendTo(row);
                        var col4_2 =  $('<div class="col-4"></div>').appendTo(row);
                        var col4_3 =  $('<div class="col-4"></div>').appendTo(row);
                        let path = data['pics'][pic]['src']
                        let type = 'image'
                        parts = path.split('.')
                        if (['avi', 'mp4', 'webm', 'mkv', 'flv', 'wmv', 'mpeg'].includes(parts[parts.length - 1])) {
                            type = 'video'
                        }
                        col4_1.append('<img src=/img/' + path + ' class="preview_img" style="padding: 10px;" data-type_file=' + type + ' data-path_file=' + path + '></img>')
                        col4_2.append('<p>'+data['pics'][pic]['doctors_diagnosis']+'</p>')
                        select = $('<select class="diagnoses_select form-control", id='+data['pics'][pic]['id']+' data-pic_id='+data['pics'][pic]['id']+' data-visit_id='+visit_id+'></select>').appendTo(col4_3);
                        select.css('width','100%')
                        select.append('<option value=0, selected, disabled>'+data['dict']['diagnosis']+'</option>')
                        for(tag in data['tags'])
                        {
                            if(data['tags'][tag]['id'] == data['pics'][pic]['expert_diagnosis_id'])
                            {
                                select.append('<option selected, value='+data['tags'][tag]['id']+'>'+data['tags'][tag]['icd']+" "+data['tags'][tag]['name']+'</option>');
                            }
                            else
                            {
                                select.append('<option value='+data['tags'][tag]['id']+'>'+data['tags'][tag]['icd']+" "+data['tags'][tag]['name']+'</option>');
                            }
                        }
                        select.val(data['pics'][pic]['expert_diagnosis_id']).trigger('change');
                    }
                    if(data['pirogov_answer'] == false)
                    {

                        var col12 =  $('<div class="row"></div>').appendTo(row);
                        var button_route = $('<button class="btn btn-primary mt-5 col-3 offset-5" id="verify_routing_btn" data-visit_id="'+visit_id+'"data-patient_id='+ data.patient_id +'">'+data['dict']['verify_routing']+'</button>').appendTo(col12);
                        
                        button_route.on('click', function() {
                         
                            $('#direct_modal').modal('toggle');
                            $('#dm_patinet').html(data['patient']);
                            $('#send_direction').data('visit_id', visit_id);
                        });
                        var button = $('<button class="btn btn-success mt-5 col-3 offset-1" id="verify_control_btn" data-visit_id="'+visit_id+'">'+data['dict']['verify_control']+'</button>').appendTo(col12);
                        button.on('click', function(){
                            $('#conclusion_modal_visit_id').val($(this).data('visit_id'));
                            $('#conclusion_modal').modal('show');
                        });
                        var row_s =  $('<div class="row row_s"></div>').appendTo(row);

                    }

                    reload();
                },
                error:function (jqXHR, exception) {
                }
            });

    });

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

    var visit_id = $('#conclusion_modal_visit_id').val();
    message = {
        confirm_control: true,
        next_visit: $('#next_visit').val(),
        conclusion: $('#conclusion').val()
    }

    $.ajax({
        type:'POST',
        url: '/2_0/visit_conclusion/'+visit_id,
        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) => {
            $("#verify_routing_btn").hide();
            $("#verify_control_btn").hide();
            $('#badge'+visit_id).hide();
            $('#item_'+visit_id).attr('data-answer', 1);
            $('#conclusion_modal').modal('hide');
            view_new();
        },
        error:function (jqXHR, exception) {
        }
    });
})

    $('#send_direction').on('click', function() {
        var params = {
            visit_id: $(this).data('visit_id'),
            clinic_id: $('.direct_patient').val()
        };
        console.log(params);
        if (params['clinic_id'] == null) {
            $('#exception').slideDown(500);
            $('#exception').delay(2000).slideUp();
            
        } else {
            $.ajax({
                type: "POST",
                url: '/verify_route',
                processData: false,  // tell jQuery not to process the data
                contentType: false,  // tell jQuery not to set contentType
                data: JSON.stringify(params),
                success: (data) => {
                    if (data['success'] == true) {
                        $("#direct_modal").modal('hide');
                        var smaul = $('<p class=" col-3 offset-5 text-success" id="dir_patient">Пациент перенаправлен в клинику "'+ $('.direct_patient option:selected').text() +'"<p>').appendTo($('.row_s'));
                        
                        smaul.slideDown(500);
                        smaul.delay(2000).slideUp();
                        $("#verify_routing_btn").delay(5000).hide()
                        $("#verify_control_btn").delay(5000).hide()
                    }
                },
                error: function (jqXHR, exception) {
                    after_error();
                }
            }) 
        }
    });



});
