$(document).ready(function () {
    var codition = {}
    
    open_filter();
    remove_script_btn();

    function remove_script_btn(){
        $('.remove-script').click(function(){
            console.log($(this).data('id'));
            if($(this).data('id') == 'main_filter')
            {
                $('#' + $(this).data('id')).data('filters', '');
                $('#' + $(this).data('id')).data('filter_type', '');
                $('#' + $(this).data('id')).parent().children("small").remove();
                $('#' + $(this).data('id')).val('0').prop('selected', true);
                $('#' + $(this).data('id')).parent().children(".small").remove();
                $('#' + $(this).data('id')).select2({
                            tags: true
                        });
            }
            else
            {
                $('#' + $(this).data('id')).parent().remove();
                $(this).parent().remove();
            }
        })
    }
    
    function open_filter() {
            $('.filter').change(function() {
            if($(this).val() == 'by_nn_diagnos'){
                $('#routing_modal_by_diagnos').modal('toggle');
                $("#routing_modal_dignosis_submit").attr('filter_type', $(this).val());
                $("#routing_modal_dignosis_submit").attr('filter_num', $(this).attr('id'));
                $(this).data('filter_type', $(this).val());
                //$('#area1').attr('class', 'tab-pane active')
                //$('#arealink1').attr('class', 'nav-link active')

                //Открывается модалка с 4 вкладками, в них чекбоксы с перечисленными диагнозами,
                //при закрытии модалки в data- от селекта записывается набор tag.id добавленых в фильтр
                //Под SELECT пишется набор tag.name в small
            }
            if($(this).val() == 'by_expert_diagnos'){
                $('#routing_modal_by_diagnos').modal('toggle');
                $("#routing_modal_dignosis_submit").attr('filter_type', $(this).val());
                $("#routing_modal_dignosis_submit").attr('filter_num', $(this).attr('id'));
                $(this).data('filter_type', $(this).val());
                //$('#area1').attr('class', 'tab-pane active')
                //$('#arealink1').attr('class', 'nav-link active')
                //Открывается модалка с 4 вкладками, в них чекбоксы с перечисленными диагнозами,
                //при закрытии модалки в data- от селекта записывается набор tag.id добавленых в фильтр
                //Под SELECT пишется набор tag.name в small
            }
            if($(this).val() == 'by_doctor_diagnos'){
                $('#routing_modal_by_diagnos').modal('toggle');
                $("#routing_modal_dignosis_submit").attr('filter_type', $(this).val());
                $("#routing_modal_dignosis_submit").attr('filter_num', $(this).attr('id'));
                $(this).data('filter_type', $(this).val());
                //$('#area1').attr('class', 'tab-pane active')
                //$('#arealink1').attr('class', 'nav-link active')
                //Открывается модалка с 4 вкладками, в них чекбоксы с перечисленными диагнозами,
                //при закрытии модалки в data- от селекта записывается набор tag.id добавленых в фильтр
                //Под SELECT пишется набор tag.name в small
            }
            if($(this).val() == 'by_script'){
                $('#routing_modal_by_script').modal('toggle');
                $("#routing_modal_scripts_submit").attr('filter_type', 'by_script');
                $(this).data('filter_type', 'by_script');
                $("#routing_modal_scripts_submit").attr('filter_num', $(this).attr('id'));
                //Открывается модалка с чекбоксами возможных первичных сценариев,
                //[Визит, Профосмотр, Направление, Внешние источники, Виджет на сайте]
                //при закрытии модалки в data- от селекта записывается набор имен сценариев добавленых в фильтр
                //Под SELECT пишется набор сценариев в small
            }
            if($(this).val() == 'by_user'){
                
                var ind = $('#source_clinic').val()
                if (!ind) {
                    $('#exception').innerHTML = "Выберите клинику";
                    $('#exception').slideDown(500);
                    $('#exception').delay(2000).slideUp();
                } else {
                    $('#routing_modal_by_user').modal('toggle');
                    $.ajax({
                        type:'GET',
                        url: '/routing/get_user_by_clinic/' + ind,
                        processData: false,
                        contentType: false,
                        success: (data) => {
                            var users_list = document.getElementById('users');
                            $(users_list).empty();
                            for (var i = 0; i < data.length; i++) {
                                var div = document.createElement('div');
                                div.setAttribute('class', 'form-check.mb-2')
                                var checkbox = document.createElement('input');
                                checkbox.setAttribute('class', 'form-check-input user');
                                checkbox.setAttribute('id', 'user_id'+data[i]['id']);
                                checkbox.setAttribute('value', data[i]['id']);
                                checkbox.setAttribute('type', 'checkbox');
                                var label = document.createElement('label');
                                label.setAttribute('class', 'form-check-label');
                                label.setAttribute('for', 'user_id'+data[i]['id']);
                                label.innerHTML = data[i]['name']
                                div.appendChild(checkbox);
                                div.appendChild(label);
                                users_list.appendChild(div);
                            }
                            $("#routing_modal_users_submit").attr('filter_type', 'by_user');
                            $(this).data('filter_type', $(this).val());
                            $("#routing_modal_users_submit").attr('filter_num', $(this).attr('id'));
                        }
                    })
                }
                //Открывается модалка с чекбоксами возможных пользователей клиники-инициатора
                //при закрытии модалки в data- от селекта записывается набор user.id добавленых в фильтр
                //Под SELECT пишется набор user.name в small
            }
            if($(this).val() == 'by_profarea'){
                var id = $('#source_clinic').val();
                if (!id) {
                    $('#exception').innerHTML = "Выберите клинику";
                    $('#exception').slideDown(500);
                    $('#exception').delay(2000).slideUp();
                } else {
                    $('#routing_modal_by_profarea').modal('toggle');
                    $.ajax({
                        url: '/routing/get_profarea_by_clinic/' + id,
                        processData: false,
                        contentType: false,
                        success: (data) => {
                            var profarea_list = document.getElementById('profarea_list');
                            $(profarea_list).empty();
                            for (var i = 0; i < data.length; i++) {
                                var div = document.createElement('div');
                                div.setAttribute('class', 'form-check.mb-2')
                                var checkbox = document.createElement('input');
                                checkbox.setAttribute('class', 'form-check-input area');
                                checkbox.setAttribute('id', 'area_id'+data[i]['id'])
                                checkbox.setAttribute('value', data[i]['id'])
                                checkbox.setAttribute('type', 'checkbox');
                                var label = document.createElement('label');
                                label.setAttribute('class', 'form-check-label');
                                label.setAttribute('for', 'area_id'+data[i]['id']);
                                label.innerHTML = data[i]['name']
                                div.appendChild(checkbox);
                                div.appendChild(label);
                                profarea_list.appendChild(div);
                            }
                            $("#routing_modal_profarea_submit").attr('filter_type', 'by_profarea');
                            $(this).data('filter_type', $(this).val());
                            $("#routing_modal_profarea_submit").attr('filter_num', $(this).attr('id'));
                        }
                    })
                }
            
                //Открывается модалка с чекбоксами возможных профобластей клиники-инициатора
                //при закрытии модалки в data- от селекта записывается набор profarea.id добавленых в фильтр
                //Под SELECT пишется набор profarea.area_name в small
            }
            if($(this).val() == 'by_city'){
                $('#routing_modal_by_city').modal('toggle');
                $.ajax({
                    url: '/routing/get_city',
                    processData: false,
                    contentType: false,
                    success: (data) => {
                        for (var i = 0; i < data.length; i++) {
                            var option = document.createElement('option');
                            option.setAttribute('value', data[i]['id']);
                            option.innerHTML = data[i]['name'];
                            $('#city_patient').append(option);
                        }
                        $("#routing_modal_city_submit").attr('filter_type', 'by_city');
                        $(this).data('filter_type', $(this).val());
                        $("#routing_modal_city_submit").attr('filter_num', $(this).attr('id'));
                        $(".routing_select2").select2({
                            tags: true
                        });
                    }
                })


                //Открывается модалка с SELECT2 с кастомным вводом, на модалке кнопка добавить выбранный
                //При нажатии кнопки город добавляется в список под селектом, рядом с каждым должен быть крестик для удаления
                //при закрытии модалки в data- от селекта записывается набор городов добавленых в фильтр
                //Под SELECT пишется набор городов в small
            }
        });
        //TODO: если фильтр поменяли на другой, то удалять значнения из filters() сделать кнопку удаления фильтра справа от селекта
    }
    $("#city_patient").change(function() {
        $('#city').show();
        var city = this.options[this.selectedIndex].text
        var id = $(this).val()
        var div = document.createElement('div');
        div.setAttribute('class', 'form-check.mb-2')
        var checkbox = document.createElement('input');
        checkbox.setAttribute('class', 'form-check-input city');
        checkbox.setAttribute('id', 'city_id'+id);
        checkbox.setAttribute('value', city);
        checkbox.setAttribute('type', 'checkbox');
        checkbox.setAttribute('checked', '')
        var label = document.createElement('label');
        label.setAttribute('class', 'form-check-label');
        label.setAttribute('for', 'user_id'+id);
        label.innerHTML = city
        div.appendChild(checkbox);
        div.appendChild(label);
        $('#city_list').append(div);

    });
    $('.nav-link').on('click', function() {
        this.setAttribute('class', 'nav-link active');
    });
    $('.choise_all').on('click', function() {
        var checkboxes = document.querySelectorAll('input[area_id="' + this.getAttribute('id_area') + '"]')
        for (var checkbox of checkboxes) {
            checkbox.checked = true;
        }
    });
    $('.cancel_all_choise').on('click', function() {
        var checkboxes = document.querySelectorAll('input[area_id="' + this.getAttribute('id_area') + '"]')
        for (var checkbox of checkboxes) {
            checkbox.checked = false;
        }
    });

    $('.choise_all_scripts').on('click', function() {
        var checkboxes = document.querySelectorAll('input[class="form-check-input script"]')
        for (var checkbox of checkboxes) {
            checkbox.checked = true;
        }
    });
    $('.cancel_all_choise_scipts').on('click', function() {
        var checkboxes = document.querySelectorAll('input[class="form-check-input script"]')
        for (var checkbox of checkboxes) {
            checkbox.checked = false;
        }
    });

    $('.choise_all_users').on('click', function() {
        var checkboxes = document.querySelectorAll('input[class="form-check-input user"]')
        for (var checkbox of checkboxes) {
            checkbox.checked = true;
        }
    });
    $('.cancel_all_choise_users').on('click', function() {
        var checkboxes = document.querySelectorAll('input[class="form-check-input user"]')
        for (var checkbox of checkboxes) {
            checkbox.checked = false;
        }
    });

    $('.choise_all_area').on('click', function() {
        var checkboxes = document.querySelectorAll('input[class="form-check-input area"]')
        for (var checkbox of checkboxes) {
            checkbox.checked = true;
        }
    });
    $('.cancel_all_choise_area').on('click', function() {
        var checkboxes = document.querySelectorAll('input[class="form-check-input area"]')
        for (var checkbox of checkboxes) {
            checkbox.checked = false;
        }
    });

    $('#routing_modal_users_submit').on('click', function() {
        var users = []
        var users_text = []
        var checkboxes = document.querySelectorAll('input[class="form-check-input user"]');
        for (var checkbox of checkboxes) {
            if (checkbox.checked == true) {
                users.push(checkbox.getAttribute('value'))
                users_text.push($(checkbox).parent().children("label").html())
            }
        }
        $('#' + $(this).attr('filter_num')).parent().children(".small").remove();
        $('#' + $(this).attr('filter_num')).data('filters', users);
        $('#' + $(this).attr('filter_num')).data('filter_type', 'by_user');
        $('#' + $(this).attr('filter_num')).parent().append('<div class="col-12 small"><small class="text-success">'+users_text.join(", ")+'</small></div>');
        $("#routing_modal_by_user").modal('hide')
    })
    $('#routing_modal_profarea_submit').on('click', function() {
        var profarea = []
        var profarea_text = []
        var checkboxes = document.querySelectorAll('input[class="form-check-input area"]');
        for (var checkbox of checkboxes) {
            if (checkbox.checked == true) {
                profarea.push(checkbox.getAttribute('value'));
                profarea_text.push($(checkbox).parent().children("label").html());
            }
        }
        $('#' + $(this).attr('filter_num')).parent().children(".small").remove();
        $('#' + $(this).attr('filter_num')).data('filters', profarea);
        $('#' + $(this).attr('filter_num')).data('filter_type', 'by_profarea');
        $('#' + $(this).attr('filter_num')).parent().append('<div class="col-12 small"><small class="text-success">'+profarea_text.join(", ")+'</small></div>');
        $("#routing_modal_by_profarea").modal('hide')

    })
    $('#routing_modal_scripts_submit').on('click', function() {
        var scripts = []
        var scripts_text = []
        var checkboxes = document.querySelectorAll('input[class="form-check-input script"]');
        for (var checkbox of checkboxes) {
            if (checkbox.checked == true) {
                scripts.push(checkbox.getAttribute('value'));
                scripts_text.push($(checkbox).parent().children("label").html())
            }
        }
        $('#' + $(this).attr('filter_num')).parent().children(".small").remove();
        $('#' + $(this).attr('filter_num')).data('filter_type', 'by_script');
        $('#' + $(this).attr('filter_num')).data('filters', scripts);
        $('#' + $(this).attr('filter_num')).parent().append('<div class="col-12 small"><small class="text-success">'+scripts_text.join(", ")+'</small></div>');
        $("#routing_modal_by_script").modal('hide')
    });
    $('#routing_modal_city_submit').on('click', function() {
        var cities = []
        var cities_text = []
        var checkboxes = document.querySelectorAll('input[class="form-check-input city"]');
        for (var checkbox of checkboxes) {
            if (checkbox.checked == true) {
                cities.push(checkbox.getAttribute('value'))
                cities_text.push($(checkbox).parent().children("label").html())
            }
        }
        $('#' + $(this).attr('filter_num')).parent().children(".small").remove();
        $('#' + $(this).attr('filter_num')).data('filter_type', 'by_city');
        $('#' + $(this).attr('filter_num')).data('filters', cities);
        $('#' + $(this).attr('filter_num')).parent().append('<div class="col-12 small"><small class="text-success">'+cities_text.join(", ")+'</small></div>');
        $("#routing_modal_by_city").modal('hide');
    })
    $('#routing_modal_dignosis_submit').on('click', function() {
        var diagonosis = {}
        var checkboxes = document.querySelectorAll('input[class="form-check-input tag_name"]')

        var all_tags = []
        var tags_text = []

        for (var tn of checkboxes) {
            if (tn.checked == true) {
                all_tags.push(tn.getAttribute('value'));
                tags_text.push($(tn).parent().children("label").html())
            }
        }
        $('#' + $(this).attr('filter_num')).parent().children(".small").remove();
        $('#' + $(this).attr('filter_num')).data('filter_type', $(this).attr('filter_type'));
        $('#' + $(this).attr('filter_num')).data('filters', all_tags);
        $('#' + $(this).attr('filter_num')).parent().append('<div class="col-12 small"><small class="text-success">'+tags_text.join(", ")+'</small></div>');
        for (tn of checkboxes) {
            tn.checked = false
        }
        
        $("#routing_modal_by_diagnos").modal('hide')
    })
    function checked_condition() {
        $('.or_check').on('click', function() {
            codition[this.getAttribute('name')] = this.getAttribute('value')
        })
        $('.and_check').on('click', function() {
            codition[this.getAttribute('name')] = this.getAttribute('value')
        })
        
    }
    

    $("#btn_add_filter").on('click', function() {
        var ind = this.getAttribute('ind-filter');
        this.setAttribute('ind-filter', parseInt(ind)+1);
        var script = document.createElement('div');
        script.setAttribute('class', 'mt-2 col-md-11')

        var remove_script = document.createElement('div');
        remove_script.setAttribute('class', 'col-md-1')

        var btn = document.createElement('button')
        btn.setAttribute('class', 'remove-script btn btn-danger btn-sm mt-2')
        btn.setAttribute('data-id', 'main_filter'+ind)
        btn.innerHTML = 'Удалить'

        remove_script.appendChild(btn)

        var select = document.createElement('select')
        select.setAttribute('class', 'form-select form-control custom-input routing_select2 filter me-0')
        select.setAttribute('style', 'width: 100%;')
        select.setAttribute('id', 'main_filter'+ind)
        
        var option = document.createElement('option');
        option.setAttribute('value', 0)
        option.setAttribute('selected', '')
        option.setAttribute('disabled', '')
        option.innerHTML = 'Правила'
        select.appendChild(option)

        var option = document.createElement('option');
        option.setAttribute("value", 'by_nn_diagnos')
        option.innerHTML = 'По диагнозу от нейросети'
        select.appendChild(option)

        var option = document.createElement('option');
        option.setAttribute("value", 'by_expert_diagnos')
        option.innerHTML = 'По диагнозу эксперта'
        select.appendChild(option)
        
        var option = document.createElement('option');
        option.setAttribute("value", 'by_doctor_diagnos')
        option.innerHTML = 'По диагнозу первичного врача'
        select.appendChild(option)

        var option = document.createElement('option');
        option.setAttribute("value", 'by_script')
        option.innerHTML = 'По сценарию'
        select.appendChild(option)

        var option = document.createElement('option');
        option.setAttribute("value", 'by_user')
        option.innerHTML = 'По пользователю клиники'
        select.appendChild(option)

        var option = document.createElement('option');
        option.setAttribute("value", 'by_profarea')
        option.innerHTML = 'По профобласти'
        select.appendChild(option)

        var option = document.createElement('option');
        option.setAttribute("value", 'by_city')
        option.innerHTML = 'По городу пациента'
        select.appendChild(option)
        script.appendChild(select)
        $('#all_scripts').append(script)
        $('#all_scripts').append(remove_script)
        $('.routing_select2').select2({tags: true});
        open_filter();
        checked_condition();
        remove_script_btn();
    });
    function clear_form() {
        //console.log($('#source_clinic').val())
        $('#source_action').val(0)
        $('#source_clinic').val('')
        $('#price_source').val('')
        $('#emails').val('')
        $('#all_scripts').val(0)
        $('#dest_action').val(0)
        $('#dest_clinic').val(0)
        $('#price_terget').val('')
        $('#emails2').val('')
    }

    $('#add_routing_rule').click(function(){
        filters = {}
        $.each($('.filter'), function(e) {
            if($(this).data('filter_type') == undefined || $(this).data('filters') == undefined)
            {
                console.log('und');
            }
            else{
                if (filters.hasOwnProperty($(this).data('filter_type')))
                {
                    filters[$(this).data('filter_type')] = $.merge(filters[$(this).data('filter_type')], $(this).data('filters'));
                }
                else
                {
                    filters[$(this).data('filter_type')] = $(this).data('filters');
                }
            }
        })
        //TODO: Маршрутизация
        //Собираем получившиеся данные и записываем в message
        var message = {'rules' : {}}

        message['rule_name'] =  $('#rule_name').val()
        message['source_action'] =  $('#source_action').val()
        message['source_clinic_id'] =  $('#source_clinic').val()
        message['source_price'] =  $('#price_source').val()
        message['source_emails'] =  $('#emails').val()
        message['rules'] = filters;
        message['dest_action'] =  $('#dest_action').val()
        message['dest_clinic_id'] =  $('#dest_clinic').val()
        message['dest_price'] =  $('#price_target').val()
        message['dest_emails'] =  $('#emails2').val()
        
        console.log(message)
        
        $.ajax({
            type:'POST',
            url: '/routing/add_rule',
            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('Правило успешно добавлено', 0);
                    clear_form()
                }
                else
                {
                    show_error(data['message'] ,0);
                }
            },
            error:function (jqXHR, exception) {
                show_error('System error' ,0);
            }
        });
    })

    $('.disable_rule').click(function(){
        let rule_id = $(this).data('rule_id');
        $.ajax({
            type:'POST',
            url: '/routing/' + rule_id + '/disable',
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: (data) => {
                if(data['success'] == true){
                    $('#enable_rule_'+rule_id).show();
                    $('#disable_rule_'+rule_id).hide();
                }
                else
                {
                    show_error('Disable error' ,0);
                }
            },
            error:function (jqXHR, exception) {
                show_error('System error' ,0);
            }
        });
    });

    $('.enable_rule').click(function(){
        let rule_id = $(this).data('rule_id');
        $.ajax({
            type:'POST',
            url: '/routing/' + rule_id + '/enable',
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: (data) => {
                if(data['success'] == true){
                    $('#enable_rule_'+rule_id).hide();
                    $('#disable_rule_'+rule_id).show();
                }
                else
                {
                    show_error('Enable error' ,0);
                }
            },
            error:function (jqXHR, exception) {
                show_error('System error' ,0);
            }
        });
    });

});