$(document).ready(function() {

    var tasks, TasksTab = {
        ajax: {
            url: "ajax.php",
            type: "POST",
            data: {
                command: 'updateTask',
                module: window.modulename,
            },
        },
        TasksPanel: {
            self: '#TasksPanel',
            body: '#TasksPanel > div.panel-body',
            table: '#tasks_table'
        },
        TasksModal: {
            self: '#TasksModal',
            dialog: '#TasksModal > div.modal-dialog',
            table: '#tasks_modal_table',
        },
        fields: {
            taskID: '#taskID',
            task_name: '#task_name',
            deadline: '#deadline',
            deadlineMeasure: '#deadlineMeasure',
            observers: '#addTask .selectMulti',
        },
        modal: $('#addTask'),
        buttons: {
            modal_addTask_ok: $('#modal_addTask_ok'),
        },
        title: '#addTask .panel-title',
        init: function () {
            tasks = this;
            this.bindUIActions();
        },
        /**
         * обработчики кнопок
         */
        bindUIActions: function () {
            tasks.modal.on('show.bs.modal', function (event) {
                $(tasks.title).html(' ' + $('#modal_action_task').attr('value'));
                if (event.relatedTarget.dataset.id) {
                    $(tasks.title).prepend($('#modal_action_edit').attr('value'));
                    var promise = tasks.detail(event.relatedTarget.dataset.id);
                    promise.done(function(res) {
                        $(tasks.fields.taskID).attr('data-id', res.id);
                        tasks.ajax.data['id'] = $(tasks.fields.taskID).attr('data-id');
                        $(tasks.fields.task_name).val(res.name);
                        $(tasks.fields.deadline).val(res.deadline);
                        $(tasks.fields.deadlineMeasure).val(res.deadline_day);

                        tasks.observersSet(JSON.parse(res.observers));

                    });
                }else{
                    $(tasks.title).prepend($('#modal_action_add').attr('value'));
                }
            });
            tasks.buttons.modal_addTask_ok.on('click', function (event) {
                if (tasks.__checkInvalid()) {
                    tasks.update();
                    $(event.currentTarget).parent().parent().parent().parent().modal('hide');
                    toggle_reload_button("show");
                }
            });
            tasks.modal.on('hidden.bs.modal',function () {
                tasks.__clearModal();
            });
        },
        /**
         * изменение задачи
         */
        update: function () {
            if($(tasks.fields.taskID).attr('data-id'))
                tasks.ajax.data['id'] = $(tasks.fields.taskID).attr('data-id');
                tasks.ajax.data['name'] = ($(tasks.fields.task_name).val()) ? $(tasks.fields.task_name).val() : '';
                tasks.ajax.data['deadline'] = ($(tasks.fields.deadline).val()) ? $(tasks.fields.deadline).val() : '';
                tasks.ajax.data['deadline_day'] = ($(tasks.fields.deadlineMeasure).val()) ? $(tasks.fields.deadlineMeasure).val() : '';
                tasks.ajax.data['observers'] = JSON.stringify(tasks.observersGet());
            $.ajax({
                url: tasks.ajax.url,
                type: tasks.ajax.type,
                data: tasks.ajax.data,
                success: function (data) {
                    fpbxToast('Complete', 'Task update', 'success');
                    IDTable.tasks_table = data;
                    updateTaskSelects('#add_inbound_modal  select#did_tasks');
                }}).then(function () {
                if ($(tasks.TasksModal.self).css('display') === 'block') {
                    $(tasks.TasksModal.table).bootstrapTable('refresh');
                }
                $(tasks.TasksPanel.table).bootstrapTable('refresh');
            });
        },
        /**
         * получение детальной информации о задаче по ее id
         * @param id
         * @returns {*}
         */
        detail: function (id) {
            var self = this;
            var deferred = $.Deferred();
            var task = null;

            $.ajax({
                url: "ajax.php",
                type: "POST",
                data: {
                    command: 'getTaskByID',
                    module: window.modulename,
                    id: id
                },
                success: function (data) {
                    task = data;
                },
                complete: function () {
                    deferred.resolve(task);
                }
            });
            return deferred.promise();
        },
        observersGet: function(){
            if( $(tasks.fields.observers  + ' select') &&  $(tasks.fields.observers  + ' select')[0])
            return $(tasks.fields.observers  + ' select')[0].selectize.getValue();
        },
        observersSet: function(value){
            if( $(tasks.fields.observers + ' select') . length > 0) {
                $(tasks.fields.observers + ' select')[0].selectize.setValue(value);
            }else{
                $(tasks.fields.observers).attr('data-value',value);
            }
        },
        __checkInvalid: function () {
            if (!$(tasks.fields.task_name).val()) {
                warnInvalid($(tasks.fields.task_name));
                return false;
            }
            if (!$(tasks.fields.deadline).val()) {
                warnInvalid($(tasks.fields.deadline));
                return false;
            }
            if (!$(tasks.fields.deadlineMeasure).val()) {
                warnInvalid($(tasks.fields.deadlineMeasure));
                return false;
            }
            return true
        },
        __clearModal: function(){
            $(tasks.fields.taskID).attr('data-id','');
            $(tasks.fields.task_name).val('');
            $(tasks.fields.deadline).val('');
            tasks.observersSet('');
        },

    };

    TasksTab.init();
});