//#region Исполнители
function ExecutorGroupItemData(observer) {
    var that = this;

    var args = [];
    args.push(observer);
    args.push({
        group: 'executorgroup',
        name: 'executorgroupid',
        selector: '#executorgroupid',
        useDefaultEvent: false,
        initConflictAfterSubmit: {
            compareEqualsCurrentWithSubmitValue: true,
            canConflict: true
        },
    });
    ItemData.apply(this, args);
}
ExecutorGroupItemData.prototype = Object.create(ItemData.prototype);

ExecutorGroupItemData.prototype.InitTaskRightsDisplayType = function () {
    this.taskRightsDisplayType = ItemDataHelper.TaskRightsDisplayType[$('#executorgroup').attr(ItemData.taskRightsDisplayTypeKey)] || ItemDataHelper.TaskRightsDisplayType.None;
}

ExecutorGroupItemData.prototype.GetBlockTitle = function () {
    return $('[taskexecutorgrouptitle]').clone().children().remove().end().text().trim();
}
//part2 - пользовательская
ExecutorGroupItemData.prototype.Append2 = function (userConnectionId, userId, userName, data, existUserConnectionId) {
    var $parent = $('[taskexecutorgrouptitle]').parent();
    $parent.find('span.taskFormHub-blockInfo').remove();
    var $span = this.GetSpanTemplate(userConnectionId, userId);
    $parent.append($span);
    this.Highlight();
}
//удалить инфу о всех юзерах которые изменили блок
//вызывает при дисконекте
ExecutorGroupItemData.prototype.ResetAll = function () {
    this.usersEditThisBlock = [];
    var $parent = $('[taskexecutorgrouptitle]').parent();
    //удалить текущий span
    $parent.find('span.taskFormHub-blockInfo').remove();
    this.Unhighlight();
}
//part2 - пользовательская
ExecutorGroupItemData.prototype.Reset2 = function (userConnectionId, userId, userName) {
    var $parent = $('[taskexecutorgrouptitle]').parent();
    //удалить текущий span
    $parent.find('span.taskFormHub-blockInfo').remove();
    //если есть еще пользователи которые редактируют блок
    if (this.usersEditThisBlock.length > 0 && this.TaskRightsDisplayType() != ItemDataHelper.TaskRightsDisplayType.None) {
        //сделать новый span
        var $span = this.GetSpanTemplate(userConnectionId, userId);
        $parent.append($span);
        //подстветить
        this.Highlight();
    }
    else {
        this.Unhighlight();
    }
}
//функция подсветки блока
ExecutorGroupItemData.prototype.Highlight = function () {
    $('#executorgroup [executorgrouphighlight]').addClass('taskFormHub-highlightBlock');
}

//функция убирает подсветку блока
ExecutorGroupItemData.prototype.Unhighlight = function () {
    $('#executorgroup [executorgrouphighlight]').removeClass('taskFormHub-highlightBlock');
}
//функция после сабмита другим пользователем, проверяет равны ли данные в блоке
//если нет, то добавить диалог конфликта
//возвращает false когда нет конфликта, true - есть конфликт
ExecutorGroupItemData.prototype.InitConflictAfterSubmit = function (submitData) {

    if (!this.IsOnForm())
        return false;

    var that = this;
    var $parent = $('[taskexecutorgrouptitle]').parent();
    //удалить старую инфу
    this.isConflict = false;
    this.$conflictMessageElement = undefined;
    $parent.find('[conflict-block="' + this._options.name + '"]').remove();

    var cur = that.GetCurrentVal();

    if (cur == '' && submitData == null || (submitData != null && cur == submitData.Id))
        return false;

    if (!this.IsChanged()) {
        if (this.TaskRightsDisplayType() != ItemDataHelper.TaskRightsDisplayType.None) {
            that.removeExecutorGroup(false);
            var $notconflictMessage = $(that.tmpl_notconflictMessageBase({ blockName: that._options.name }));
            //добавить новую инфу
            $parent.append($notconflictMessage);

            if (submitData != null) {
                that._executorGroupsSelected(submitData.Id, submitData.Name, true);
            }

            that.SetOldValue();
            that.SendBlockChange();
        }
        return false;
    }
    else {

        var $conflictMessage = $(this.tmpl_conflictMessageBase({ blockName: this._options.name }));
        $conflictMessage.find('a').click(function (e) {
            e.preventDefault();

            var $content = $('<div style="background-color:#f7f9fa"></div>');

            var c =
                    '<div>\
                        <label>\
                            <input type="radio" name="conflictradioresolve-' + that._options.name + '" value="1" checked />' + TaskFormHubResources.ConflictDialogContent_UseOldValue + '\
                        </label>';
            if (cur == '') {
                c += '<div name="conflictradioresolve-' + that._options.name + '-value1" emptyvalue>' + TaskFormHubResources.ConflictDialogContent_ExecutorGroup_Empty + '</div>'
            }
            else {
                c += '<div name="conflictradioresolve-' + that._options.name + '-value1" conflictvalue="' + cur + '">';
                c += $('#egroupholder a:first').text();
                c += '</div>';
            }
            c +=    '</div><hr>\
                     <div>\
                        <label>\
                            <input type="radio" name="conflictradioresolve-' + that._options.name + '" value="0" />' + TaskFormHubResources.ConflictDialogContent_UseNewValue + '\
                        </label>';
            if (submitData == null) {
                c += '<div name="conflictradioresolve-' + that._options.name + '-value0" emptyvalue>' + TaskFormHubResources.ConflictDialogContent_ExecutorGroup_Empty + '</div>'
            }
            else {
                c += '<div name="conflictradioresolve-' + that._options.name + '-value0" conflictvalue=\'' + submitData.Id + '\'>';
                c += submitData.Name
                c += '</div>'
            }
            c += '</div>';

            $content.append(c);

            GLOBAL_taskFormHubDialog.openDialog($content, {
                title: that.GetBlockTitle(),
                buttons: {
                    Cancel: function () {
                        GLOBAL_taskFormHubDialog.closeDialog();
                    },
                    Ok: function () {
                        var $content = GLOBAL_taskFormHubDialog.getContent();
                        var checkedVal = $content.find('[name="conflictradioresolve-' + that._options.name + '"]:checked').val();
                        //если оставили то ничего не делаем
                        if (checkedVal == 1) {
                        }
                        else {
                            that.removeExecutorGroup(false);
                            var $resolvecontent = $content.find('[name="conflictradioresolve-' + that._options.name + '-value0"]');
                            if ($resolvecontent.is('[emptyvalue]')) {
                                
                            }
                            else {
                                that._executorGroupsSelected($resolvecontent.attr('conflictvalue'), $resolvecontent.text(), true);
                            }
                            that.SetOldValue();
                            that.SendBlockChange();
                        }

                        //удаляем инфу о конфликте
                        that.isConflict = false;
                        that.$conflictMessageElement = undefined;
                        $parent.find('[conflict-block="' + that._options.name + '"]').remove();

                        GLOBAL_taskFormHubDialog.closeDialog();
                    }
                }
            });

        });

        this.isConflict = true;
        this.$conflictMessageElement = $conflictMessage;
        $parent.append($conflictMessage);

        return true;
    }
}
ExecutorGroupItemData.prototype.AppendNotConflict = function () { }
ExecutorGroupItemData.prototype.AppendNotConflictUpdate = function () { }
ExecutorGroupItemData.prototype.AppendConflict1 = function () { }
ExecutorGroupItemData.prototype.AppendConflict2 = function () { }
ExecutorGroupItemData.prototype.UpdateGroupCallBack = function (groupId, del) {  }

ExecutorGroupItemData.prototype.removeExecutorsStroke = function () {
    if (!$('#egroupholder').hasClass('removed')) {
        $('#executorgroupid').attr('changed', true);
        $('#egroupholder').addClass('removed changed');
        $('#executorgroupid').attr('changed', true).val('');
        UpdateGroupCallBack($('#egroupholder').attr('group-id'), true);
    }
    else {
        $('#egroupholder').removeClass('removed changed');
        $('#executorgroupid').attr('changed', true).val($('#egroupholder').attr('group-id'));
        UpdateGroupCallBack($('#egroupholder').attr('group-id'), false);
    }
    this.SendBlockChange();
}
ExecutorGroupItemData.prototype.removeExecutorGroup = function(notext) {
    $('#executorgroupid').attr('changed', true).val('');
    UpdateGroupCallBack($('#egroupholder').attr('group-id'), true);
    $('#egroupholder').empty();
    if (notext == false) {
        var $nogroup = $('<div/>').addClass('details').attr('id', 'noexecutorgroup').text(TaskResources.ExecutorGroupNotAssigned);
        $('#egroupholder').append($nogroup);
    }
    this.SendBlockChange();
    return false;
}
ExecutorGroupItemData.prototype.selectExecutorGroups = function () {
    var that = this;
    var serviceid = $('#serviceid').val();
    dlg = openDialog('executorgroup/select?targetBlock=ExecutorGroupItemData&tb_mode=SERVICEGROUPS&tb_serviceid=' + serviceid);
    dlg.callback = ExecutorGroupItemData.selectExecutorGroupsCallback;
    return false;
}
ExecutorGroupItemData.selectExecutorGroupsCallback = function (result) {
    var that = GLOBAL_taskFormHubObserver.getBlocks()['executorgroupid'];
    var ids = result["selectedIds"];
    var names = result["selectedNames"];
    var id = ids[0];
    var gn = names['id' + id];

    that._executorGroupsSelected(id, gn);
}
ExecutorGroupItemData.prototype._executorGroupsSelected = function (id, name, canRemove, categoryId, async) {
    var that = this;
    that.removeExecutorGroup(true);
    if (async !== false)
        async = true;
    return $.ajax({
        url: 'ExecutorGroup/GetGroupExecutorHash/?id=' + id,
        async: async,
        success: function (hash) {           
            var $ag = $('<a/>').addClass('nounderline changed').text(name).attr('href', 'executorgroup/viewhash/' + hash).click(function () { return executorGroupDetailsByHash(hash); });
            var $ar = $('<a href="#"/>').click(function () { GLOBAL_taskFormHubObserver.getBlocks()['executorgroupid'].removeExecutorsStroke(this); return false; });
            $ar.append($('<img/>').attr('src', 'img/trash.gif').attr('title', CommonResources.Remove));
            $('#egroupholder').append(TaskResources.Group + ': ').append($ag);
            categoryId = categoryId === undefined ? "" : categoryId.toString();
            $('#egroupholder').attr('group-id', id.toString()).attr('categoryids', categoryId.toString())
                .attr('data-categoryids', categoryId.toString());

            if (canRemove) {
                $('#egroupholder').append($ar);
            }

            if (canRemove === undefined)
                $('#egroupholder').append($ar);

            that.SendBlockChange();

            $('#egroupholder').removeClass("removed");
            $('#executorgroupid').val(id).attr('changed', true);
            $('#egroupholder').data('categoryids', categoryId);
            $.ajax({
                contentType: 'application/json',
                type: 'GET',
                url: 'ExecutorGroup/FindDefaultGroupObservers/?groupid=' + id,
                success: function (response) {
                    var promises = [];
                    $.each(response.Observers, function (i, el) {
                        promises.push(_addUserToList(el.Id, el.Name, el.Company, '#participants', false, undefined, true, "GLOBAL_taskFormHubObserver.getBlocks()['taskparticipants'].removeUser(this," + el.Id + "); return false;", undefined, id).promise());
                    });
                    $.when.apply($, promises).then(function (result) {
                        that.SendBlockChange();
                    });
                }
            })       
        }
    });
}
//#endregion