$(document).ready(function() {
    var inbound,
        InboundDestinationTab = {
            ajax: {
                url: "ajax.php",
                type: "POST",
                data: {
                    module: 'iub24',
                    command: 'updateDid',
                },
            },
            InboundDestinationsPanel: {
                self: '#InboundDestinationsPanel',
                body: '#InboundDestinationsPanel > div.panel-body',
                table: '#inbound_destinations_table'
            },
            InboundDestinationsModal: {
                self: '#InboundDestinations',
                dialog: '#InboundDestinations > div.modal-dialog',
                table: '#inbound_destinations_table_modal',
                body: '#InboundDestinations div.modal-body',
            },
            fields: {
                inboundID: '#inboundID',
                description: '#add_inbound_modal input[name=description]',
                regPriority: '#add_inbound_modal select[name="regPriority"]',
                show_caller_name: '#add_inbound_modal input[name=show_caller_name]',
                show_card: '#add_inbound_modal input[name=show_card]',
                add_to_chat: '#add_inbound_modal input[name=add_to_chat]',
                assign: '#add_inbound_modal input[name=assign]',
                assigned_manager_ring_timer: '#add_inbound_modal input[name=assigned_manager_ring_timer]',
                create_lead: '#add_inbound_modal input[name=create_lead]',
                source: '#add_inbound_modal div[data-placement="source-options"]',
                task: '#add_inbound_modal select[name=did_tasks]',
                exceptions: '#add_inbound_modal select#exceptions',
                assessment: '#add_inbound_modal input[name="assessment"]',
                greatings: '#add_inbound_modal  select#greatings',
                bye: '#add_inbound_modal  select#bye',
                user_id: '#add_inbound_modal .selectSingle',
            },
            help: {
                regPriorityHelp: '#add_inbound_modal span[id="regPriority-help"]',
                usersFromPortalHelp: '#add_inbound_modal span[id="users-from-portal-help"]',
                exceptionsOptionsHelp: '#add_inbound_modal span[id="exceptions-options-help"]',
                showCallerNameHelp: '#add_inbound_modal span[id="show_caller_name-help"]',
                addToChatHelp: '#add_inbound_modal span[id="add_to_chat-help"]',
                assignHelp: '#add_inbound_modal span[id="assign-help"]',
                tasksHelp: '#add_inbound_modal span[id="did_tasks-help"]',
                showCardHelp: '#add_inbound_modal span[id="show_card-help"]',
                createLeadHelp: '#add_inbound_modal span[id="create_lead-help"]',
                sourceHelp: '#add_inbound_modal span[id="source-options-help"]',
                AssignedManagerHelp: '#add_inbound_modal span[id="manager_in_charge-help"]',
                assessmentHelp: '#add_inbound_modal span[id="assessment-help"]',
                greatingsHelp: '#add_inbound_modal span[id="greatings-help"]',
                byeHelp: '#add_inbound_modal span[id="bye-help"]',
                destinationHelp: '#add_inbound_modal span[id="dest_ajax-help"]'
            },
            dest_ajax : $('.dest_ajax').html(),
            manager_in_charge_ajax: $('.manager_in_charge_ajax').html(),
            modal: $('#add_inbound_modal'),
            buttons: {
                modal_addInbound_ok: $('#modal_addInbound_ok'),
            },
            title: $('#add_inbound_modal .panel-title'),

            init: function () {
                inbound = this;
                translate(this.help);
                this.bindUIActions();
            },
            /**
             * обработчики кнопок
             */
            bindUIActions: function () {
                $(inbound.modal).on('change', '.iub24_destdropdown' ,function () {
                        let tableID = $(this).parent().attr('class');
                        $('[class="' + tableID + '"] option[selected]').attr('selected',false);
                        $('[class="' + tableID + '"] option[value="' + $(this).val() + '"]').attr('selected',true);
                        let id = $(this).attr('data-id');
                        $('[class="' + tableID + '"] .iub24_destdropdown2[data-id="' + id + '"]').addClass('hidden');
                        let iub24_destdropdown2 = $('[class="' + tableID + '"] [id="' + $(this).val() + id +'"]');
                        iub24_destdropdown2.removeClass('hidden');
                });

                inbound.modal.on('show.bs.modal', function (event) {
                    inbound.title.html(' ' + $('#modal_action_did').attr('value'));
                    if (event.relatedTarget.dataset.id) {
                        inbound.title.prepend($('#modal_action_edit').attr('value'));
                        inbound.title.prepend("#" + event.relatedTarget.dataset.id + " ");

                        var promise = inbound.detail(event.relatedTarget.dataset.id);
                         promise.done(function(res) {
                            (res.id) ? $(inbound.fields.inboundID).attr('data-id', res.id) : '';
                            (res.description) ? $(inbound.fields.description).val(res.description) : '';
                            if (res.user_id && $(inbound.fields.user_id + ' select').length > 0){
                                $(inbound.fields.user_id+ ' select')[0].selectize.setValue(res.user_id);
                            } else {
                                $(inbound.fields.user_id).attr('data-value',res.user_id);
                            }
                            (res.regPriority) ? $(inbound.fields.regPriority)[0].selectize.setValue(JSON.parse(res.regPriority),true) : '';
                            (res.exceptions) ? $(inbound.fields.exceptions).val(res.exceptions) : '';
                            (res.show_caller_name) ? $(inbound.fields.show_caller_name + '[value=' + res.show_caller_name + ']').prop('checked', true) : '';
                            (res.add_to_chat) ? $(inbound.fields.add_to_chat + '[value=' + res.add_to_chat + ']').prop('checked', true) : '';
                            (res.assign) ? $(inbound.fields.assign +'[value=' + res.assign + ']').prop('checked', true) : '';
                            (res.task) ? $(inbound.fields.task).val(res.task) : '';
                            (res.show_card) ? $(inbound.fields.show_card + '[value=' + res.show_card + ']').prop('checked', true) : '';
                            (res.create_lead) ? $(inbound.fields.create_lead + '[value=' + res.create_lead + ']').prop('checked', true) : '';
                            if (res.source && $(inbound.fields.source + ' select').length > 0){
                                $(inbound.fields.source + ' select')[0].selectize.setValue(res.source);
                            } else {
                                $(inbound.fields.source).attr('data-value', res.source);
                            }
                            (res.assigned_manager_ring_timer) ? $(inbound.fields.assigned_manager_ring_timer).val(res.assigned_manager_ring_timer) : '';
                            (res.assessment) ? $(inbound.fields.assessment + '[value=' + res.assessment + ']').prop('checked', true).trigger('change') : '';
                            (res.greatings) ? $(inbound.fields.greatings).val(res.greatings) : '';
                            (res.bye) ? $(inbound.fields.bye).val(res.bye) : '';
                            $('.manager_in_charge_ajax').trigger('change');

                        });
                    }else{
                        inbound.title.prepend($('#modal_action_add').attr('value'));
                        $('.manager_in_charge_ajax').trigger('change');
                    }
                });
                inbound.buttons.modal_addInbound_ok.on('click', function (event) {
                    if (inbound.__checkInvalid()) {
                        inbound.update();
                        $(event.currentTarget).parent().parent().parent().parent().parent().parent().modal('hide');
                        toggle_reload_button("show");
                    }
                });
                $(inbound.modal).on('hidden.bs.modal', function () {
                    inbound.clearFormInbound();
                });
                $('.manager_in_charge_ajax').on('change',function (e) {
                    if($('#add_inbound_modal select[name=goto1]').val() === 'Assigned_Manager'){
                        switch ($('#add_inbound_modal select[name=Assigned_Manager1]').val()) {
                            case 'manager_in_charge,exten,1':
                            case 'manager_in_charge,mobile,1':
                                $('.show_div_ringtimer').show();
                                break;
                            default:
                                $('.show_div_ringtimer').hide();
                                break;
                        }
                    }else{
                            $('.show_div_ringtimer').hide();
                    }
                });
                 $('#add_inbound_modal input[name=assessment], ' +
                    '#add_inbound_modal input[name=assessment]').on('change', function () {

                    switch ($(this).val()) {
                        case 'yes':

                            $('.show_div_greet').show();
                            $('.show_div_bye').show();
                            break;
                        case 'no':


                            $('.show_div_greet').hide();
                            $('.show_div_bye').hide();
                            break;
                    }
                });

            },
            /**
             * обновление дида
             */
            update: function () {
                inbound.ajax.data['id'] = $(inbound.fields.inboundID).attr('data-id');
                inbound.ajax.data['description'] = $(inbound.fields.description).val();
                inbound.ajax.data['user_id'] = $(inbound.fields.user_id + ' select').val();
                inbound.ajax.data['regPriority'] = JSON.stringify($(inbound.fields.regPriority).val());
                inbound.ajax.data['exceptions'] = $(inbound.fields.exceptions).val();
                inbound.ajax.data['show_caller_name'] = $(inbound.fields.show_caller_name + ':checked').val();
                inbound.ajax.data['add_to_chat'] = $(inbound.fields.add_to_chat + ':checked').val();
                inbound.ajax.data['assign'] = $(inbound.fields.assign + ':checked').val();
                inbound.ajax.data['task'] = $(inbound.fields.task).val();
                inbound.ajax.data['show_card'] = $(inbound.fields.show_card + ':checked').val();
                inbound.ajax.data['create_lead'] = $(inbound.fields.create_lead+ ':checked').val();
                inbound.ajax.data['source'] = ($(inbound.fields.source +' select').val()) ? $(inbound.fields.source + ' select').val() : '';
                inbound.ajax.data['manager_in_charge'] = inbound.getDestinationForm(inbound.modal, '.manager_in_charge');
                inbound.ajax.data['assessment'] = $(inbound.fields.assessment + ':checked').val();
                inbound.ajax.data['assigned_manager_ring_timer'] = $(inbound.fields.assigned_manager_ring_timer).val();
                inbound.ajax.data['greatings'] = $(inbound.fields.greatings).val();
                inbound.ajax.data['bye'] = $(inbound.fields.bye).val();
                inbound.ajax.data['destination'] = inbound.getDestinationForm(inbound.modal);

                $.ajax({
                    url: inbound.ajax.url,
                    type: inbound.ajax.type,
                    data: inbound.ajax.data,
                    success: function (data) {
                        fpbxToast('Complete', 'InboundDestination update', 'success');
                        IDTable.inbound_destinations_table = data;
                    }}).then(function () {
                    if ($(inbound.InboundDestinationsModal.self).css('display') === 'block'){
                        $(inbound.InboundDestinationsModal.table).bootstrapTable('refresh');
                    }
                    $(inbound.InboundDestinationsPanel.table).bootstrapTable('refresh');
                });
            },

            /**
             * получение детальной информации о диде по его id
             * @param id
             * @returns {*}
             */
            detail: function(id) {
                var self = this;
                var deferred = $.Deferred();
                var did = null;

                $.ajax({
                    url: "ajax.php",
                    type: "POST",
                    data: {
                        command: 'getDidByID',
                        module: window.modulename,
                        id: id
                    },
                    success: function(data) {
                        did = data;
                        if (data['destination_custom'])
                            self.getDestination('.dest_ajax', data['destination_custom']);

                        if (data['manager_in_charge'])
                            self.getDestination('.manager_in_charge_ajax', data['manager_in_charge_custom']);

                        // bind_dests_double_selects();
                    },
                    complete: function() {
                        deferred.resolve(did);
                    }
                });

                return deferred.promise();
            },
            getDestination: function(className, html) {
                inbound.modal.find(className).html(html);
            },

            clearFormInbound: function() {
                // console.log('clear modal');
                $(inbound.title).html();
                $(inbound.fields.inboundID).attr('data-id', '');
                $(inbound.fields.description).val('');
                if($(inbound.fields.user_id)[0] && $(inbound.fields.user_id)[0].selectize)
                    $(inbound.fields.user_id + ' select')[0].selectize.setValue('');
                $(inbound.fields.regPriority)[0].selectize.setValue('DEFAULT',true);
                $(inbound.fields.exceptions).prop('selected',true);
                $(inbound.fields.show_caller_name + '[value=no]').prop('checked',true).trigger('change');
                $(inbound.fields.add_to_chat +'[value=no]').prop('checked',true).trigger('change');
                $(inbound.fields.assign + '[value=default]').prop('checked',true).trigger('change');
                $(inbound.fields.task).val('');
                $(inbound.fields.show_card +':checked').prop('checked',false);
                $(inbound.fields.create_lead +':checked').prop('checked',false);
                if($(inbound.fields.source)[0] && $(inbound.fields.source)[0].selectize)
                    $(inbound.fields.source + ' select')[0].selectize.setValue(0);
                $(inbound.fields.assigned_manager_ring_timer).val(15);
                $(inbound.fields.assessment +'[value=no]').prop('checked',true).trigger('change');
                $(inbound.fields.greatings).val('');
                $(inbound.fields.bye).val('');

                inbound.getDestination('.dest_ajax', inbound.dest_ajax);
                inbound.getDestination('.manager_in_charge_ajax', inbound.manager_in_charge_ajax);

            },
            /**
             * Получаем destination route из селектов
             * в настройках
             * @returns {*}
             */
            getDestinationForm: function($form, className) {
                var className = typeof className == 'undefined' ? '.dest_settings_b24' : className;
                var destination = null;
                $.each($form.find(className + ':visible'), function() {
                    var attr = $(this).attr('data-class');
                        destination = $(this).val();
                });
                return destination;
            },
            __checkInvalid: function() {
                let div_ring_timer = inbound.modal.find('.show_div_ringtimer');

                if (!$(inbound.fields.description).val()){
                    warnInvalid($(inbound.fields.description));
                    return false;
                }

                if (!$(inbound.fields.user_id + ' select').val()){
                    warnInvalid($(inbound.fields.user_id + ' select'));
                    return false;
                }

                if (!$(inbound.fields.regPriority).val().length || ($(inbound.fields.regPriority).val().length < 3  && !$(inbound.fields.regPriority).val().includes("DEFAULT")) ){
                    warnInvalid($(inbound.fields.regPriority));
                    return false;
                }

                if (!$(inbound.fields.show_card).is(':checked')){
                    warnInvalid($(inbound.fields.show_card));
                    return false;
                }

                if (!$(inbound.fields.create_lead).is(':checked')){
                    warnInvalid($(inbound.fields.create_lead));
                    return false;
                }
                if((div_ring_timer.is(':visible')  && !div_ring_timer.find('input[name="assigned_manager_ring_timer"]').val()) || (div_ring_timer.is(':visible')  && div_ring_timer.find('input[name="assigned_manager_ring_timer"]').val() < 1)){
                    warnInvalid(div_ring_timer);
                    return false;
                }

                if (!inbound.getDestinationForm(inbound.modal)){
                    warnInvalid($('.dest_ajax'));
                    return false;
                }
                return true;
            },
        };

    InboundDestinationTab.init();

});