$(document).ready(function() {
    var exceptions, ExceptionsTab = {
            ajax: {
                url: "ajax.php",
                type: "POST",
                data: {
                    command: 'updateException',
                    module: 'iub24',
                },
            },
            ExceptionsPanel: {
                self: '#ExceptionsPanel',
                body: '#ExceptionsPanel > div.panel-body',
                table: '#exceptions_grid'
            },
            ExceptionsModal: {
                self: '#ExceptionsModal',
                dialog: '#ExceptionsModal > div.modal-dialog',
                body: '#ExceptionsModal div.modal-body',
            },
            fields: {
                exceptionID: '#exceptionID',
                description: '#addException #description',
                members: '#addException .selectMulti',
            },
            modal: '#addException',
            buttons: {
                modal_addException_ok: '#modal_addException_ok',
            },
            title: '#addException .panel-title',

            init: function () {
            exceptions = this;
                this.bindUIActions();
            },

            /**
             * обработчики кнопок
             */
            bindUIActions: function() {
                $(exceptions.modal).on('show.bs.modal', function (event) {
                    $(exceptions.title).html(' ' + $('#modal_action_exception').attr('value'));
                    if (event.relatedTarget.dataset.id) {
                        $(exceptions.title).prepend($('#modal_action_edit').attr('value'));
                        var promise = exceptions.detail(event.relatedTarget.dataset.id);
                        promise.done(function(res) {
                            $(exceptions.fields.exceptionID).attr('data-id', res.id);
                            exceptions.ajax.data['id'] = $(exceptions.fields.exceptionID).attr('data-id');
                            $(exceptions.fields.description).val(res.description);
                            exceptions.membersSet(JSON.parse(res.numbers));
                        });
                    }else{
                        $(exceptions.title).prepend($('#modal_action_add').attr('value'));
                    }
                });
                $(exceptions.buttons.modal_addException_ok).on('click', function (event) {
                    if (exceptions.__checkInvalid()) {
                        exceptions.update();
                        $(event.currentTarget).parent().parent().parent().parent().modal('hide');
                        toggle_reload_button("show");
                    }
                });
                $(exceptions.modal).on('hidden.bs.modal',function () {
                    exceptions.__clearModal();
                });
            },
            /**
             * Создание/изменение задачи
             */
            update: function() {
                if($(exceptions.fields.exceptionID).attr('data-id'))
                    exceptions.ajax.data['id'] = $(exceptions.fields.exceptionID).attr('data-id');
                exceptions.ajax.data['description'] = ($(exceptions.fields.description).val()) ? $(exceptions.fields.description).val() : '';
                exceptions.ajax.data['members'] = JSON.stringify(exceptions.membersGet());
                $.ajax({
                    url: exceptions.ajax.url,
                    type: exceptions.ajax.type,
                    data: exceptions.ajax.data,
                    success: function (data) {
                        fpbxToast('Complete', 'Members update', 'success');
                        IDTable.exceptions_grid = data;

                    }}).then(function () {
                    if ($(exceptions.ExceptionsModal.self).css('display') === 'block') {
                        $(exceptions.ExceptionsModal.table).bootstrapTable('refresh');
                    }
                    $(exceptions.ExceptionsPanel.table).bootstrapTable('refresh');
                    updateSelects('#add_inbound_modal  select#exceptions');
                    updateSelects('#edit_outbound_modal  select#exceptions');
                });
            },

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

                $.ajax({
                    url: "ajax.php",
                    type: "POST",
                    data: {
                        command: 'getExceptionByID',
                        module: window.modulename,
                        id: id
                    },
                    success: function(data) {
                        exception = data;
                    },
                    complete: function() {
                        deferred.resolve(exception);
                    }
                });

                return deferred.promise();
            },
            membersGet: function(){
                if ($(exceptions.fields.members + ' select') && $(exceptions.fields.members + ' select')[0])
                return $(exceptions.fields.members + ' select')[0].selectize.getValue();
            },
            membersSet: function(value){
                if( $(exceptions.fields.members + ' select').length > 0) {
                    $(exceptions.fields.members + ' select')[0].selectize.setValue(value);
                }else{
                    $(exceptions.fields.members).attr('data-value',value);
                }
            },
            __checkInvalid: function () {
                if (!$(exceptions.fields.description).val()){
                    warnInvalid($(exceptions.fields.description));
                    return false;
                }
                if ((exceptions.membersGet().length == 0)){
                    warnInvalid($(exceptions.fields.members));
                    return false;
                }
                return true;
            },
            __clearModal: function(){

                $(exceptions.fields.exceptionID).attr('data-id','');
                $(exceptions.fields.description).val('');
                exceptions.membersSet('');
            },
        };

    ExceptionsTab.init();
});