//#region Наблюдатели
function ParticipantsItemData(observer) {
    var that = this;

    var args = [];
    args.push(observer);
    args.push({
        group: 'taskparticipants',
        name: 'taskparticipants',
        selector: '#participantids',
        useDefaultEvent: true,
        initConflictAfterSubmit: {
            //compareEqualsCurrentWithSubmitValue: false,
            canConflict: false
        },
    });
    ItemData.apply(this, args);

    if (this.IsOnForm() && this.TaskRightsDisplayType() != ItemDataHelper.TaskRightsDisplayType.None) {
        $('#addparticipant').devbridgeAutocomplete({
            serviceUrl: 'Task/FindObservers/' + $('#serviceid').val(),
            minChars: 1,
            autoClearInputOnSelect: true,
            autoQueryOnEmptyField: true,
            onSelect: function (suggestion) {
                var name = suggestion.value;
                var company = suggestion.data.companyName;
                var id = suggestion.data.id;
                _addUserToList(id, name, company, '#participants', undefined, undefined, true, "GLOBAL_taskFormHubObserver.getBlocks()['taskparticipants'].removeUser(this," + id + "); return false;", undefined, -1)
                    .done(function (result) {
                        that.SendBlockChange();
                    });
            }
        });
    }
}
ParticipantsItemData.prototype = Object.create(ItemData.prototype);

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

ParticipantsItemData.prototype.GetBlockTitle = function () {
    return $('[taskparticipantstitle]').clone().children().remove().end().text().trim();
}
ParticipantsItemData.prototype.GetCurrentVal = function () {
    return $(this._options.selector).val() || [];
}
ParticipantsItemData.prototype.IsChanged = function () {
    var cur = this.GetCurrentVal();
    var old = this.GetOldValue();
    var result = ItemDataHelper.ArraysIsEquals(cur, old);
    return !result;
}
//part2 - пользовательская
ParticipantsItemData.prototype.Append2 = function (userConnectionId, userId, userName, data, existUserConnectionId) {
    var $parent = $('[taskparticipantstitle]').parent();
    $parent.find('span.taskFormHub-blockInfo').remove();
    var $span = this.GetSpanTemplate(userConnectionId, userId);
    $parent.append($span);
    this.Highlight();
}
//удалить инфу о всех юзерах которые изменили блок
//вызывает при дисконекте
ParticipantsItemData.prototype.ResetAll = function () {
    this.usersEditThisBlock = [];
    var $parent = $('[taskparticipantstitle]').parent();
    //удалить текущий span
    $parent.find('span.taskFormHub-blockInfo').remove();
    this.Unhighlight();
}
//part2 - пользовательская
ParticipantsItemData.prototype.Reset2 = function (userConnectionId, userId, userName) {
    var $parent = $('[taskparticipantstitle]').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();
    }
}
//функция подсветки блока
ParticipantsItemData.prototype.Highlight = function () {
    $('#participants').addClass('taskFormHub-highlightBlock');
}
//функция убирает подсветку блока
ParticipantsItemData.prototype.Unhighlight = function () {
    $('#participants').removeClass('taskFormHub-highlightBlock');
}
ParticipantsItemData.prototype.InitConflictAfterSubmit = function (submitData) {
    var that = this;
    var $parent = $('[taskparticipantstitle]').parent();
    //удалить старую инфу
    this.isConflict = false;
    this.$conflictMessageElement = undefined;
    $parent.find('[conflict-block="' + this._options.name + '"]').remove();

    if (submitData != null) {
        var submitArray = submitData.map(function (p) { return p.UserId; });
        var curArray = that.GetCurrentVal();
        var oldArray = that.GetOldValue();
        //var myEditedArray = $(curArray).not(oldArray).get();
        var myAddedArray = curArray.filter(function (item) { return oldArray.indexOf(item) < 0 });
        var myRemovedArray = oldArray.filter(function (item) { return curArray.indexOf(item) < 0 });

        var $select = $(this._options.selector);
        var promises = [];
        var serverUsers = [];
        $.each(submitData, function (k, v) {
            serverUsers.push(v.UserId);
            var categoryIds = v.CategoryIds ? v.CategoryIds.split(';') : [];
            $.each(categoryIds, function (i, c) {
                promises.push(_addUserToList(v.UserId, v.UserName, v.CompanyName, "#participants", undefined, v.UserHashId, true, "GLOBAL_taskFormHubObserver.getBlocks()['taskparticipants'].removeUser(this," + v.UserId + "); return false;", c).promise());
            });
            if (!categoryIds)
            {
                promises.push(_addUserToList(v.UserId, v.UserName, v.CompanyName, "#participants", undefined, v.UserHashId, true, "GLOBAL_taskFormHubObserver.getBlocks()['taskparticipants'].removeUser(this," + v.UserId + "); return false;", undefined, -1).promise());
            }
        });
        $.when.apply($, promises).then(function (result) {
            if (curArray.length) {
                for (var i = 0; i < curArray.length; i++) {
                    var curItem = curArray[i];
                    //if (serverUsers.indexOf(curItem) == -1 && myEditedArray.indexOf(curItem) == -1) {
                    if (serverUsers.indexOf(curItem) == -1 && myAddedArray.indexOf(curItem) == -1 && myRemovedArray.indexOf(curItem) == -1) {
                        $('#participants').find('li[userid="' + curArray[i] + '"]').remove();//.addClass('archive changed');
                        $select.find('option[value="' + curArray[i] + '"]').remove();//.attr('selected', false);
                    }
                }
            }

            var $notconflictMessage = $(that.tmpl_notconflictMessageBase({ blockName: that._options.name }));
            //добавить новую инфу
            $parent.append($notconflictMessage);
            
            //в старое значение запишем новые данные, но без тех что мы лично добавили
            //иначе наши изменения не сохранятся...
            //that.SetOldValue($(that.GetCurrentVal()).not(myEditedArray).get());
            that.SetOldValue($(ItemDataHelper.ArraysMergeDistinct(that.GetCurrentVal(), myRemovedArray)).not(myAddedArray).get());
            that.SendBlockChange();
        });
    }

    return false;
}
ParticipantsItemData.prototype.AppendNotConflict = function () { }
ParticipantsItemData.prototype.AppendNotConflictUpdate = function () { }
ParticipantsItemData.prototype.AppendConflict1 = function () { }
ParticipantsItemData.prototype.AppendConflict2 = function () { }

ParticipantsItemData.prototype.assignSelfParticipant = function (id) {
    var that = this;

    $.getJSON('Task/GetCurrenUserData', { json: "json" }, function (data) {
        _addUserToList(data.Id, data.Name, data.CompanyName, "#participants", undefined, data.HashId, true, "GLOBAL_taskFormHubObserver.getBlocks()['taskparticipants'].removeUser(this," + data.Id + "); return false;", undefined, -1)
            .done(function (result) {
                that.SendBlockChange();
            });

    });
}
ParticipantsItemData.prototype.removeUser = function (athis, id) {
    var that = this;
    removeUser(athis, id);
    this.SendBlockChange();
}

ParticipantsItemData.prototype.selectParticipants = function () {
    var that = this;
    var url = 'taskuser.ivp/selectobservers?targetBlock=ParticipantsItemData&tb_serviceid=' + $('#serviceid').val();
    //utype = '#participants';
    dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
    dlg.callback = ParticipantsItemData.selectParticipantsCallback;
    return false;
}
ParticipantsItemData.selectParticipantsCallback = function (result) {
    var that = GLOBAL_taskFormHubObserver.getBlocks()['taskparticipants'];
    var uids = result["selectedIds"];
    var names = result["selectedNames"];
    var companies = result["selectedCompanies"];
    var promises = [];
    uids.forEach(function (id) {
        var un = names['id' + id];
        var cn = companies['id' + id];
        promises.push(_addUserToList(id, un, cn, '#participants', undefined, undefined, true, "GLOBAL_taskFormHubObserver.getBlocks()['taskparticipants'].removeUser(this," + id + "); return false;", undefined, -1).promise());
    });
    $.when.apply($, promises).then(function (result) {
        that.SendBlockChange();
    });
    //addSelected(uids, names, companies);
}
ParticipantsItemData.prototype.removeAllObservers = function (dontshowdeleted) {
    $('#participants input[type="checkbox"]').each(function (i, e) { $(e).removeAttr('checked'); });
    $('#participants #participantids option').each(function (i, e) { $(e).removeAttr('selected'); });
    if (dontshowdeleted)
        $('#participants ul').empty();
    else
        $('#participants ul.many li').each(function (i, e) {
            if (!$(e).hasClass('empty')) {
                $(e).addClass('archive changed');
                $(e).attr("data-groupids", "")
                $(e).attr("data-categoryids", "")
                $(e).data("groupids", "")
                $(e).data("categoryids", "")
                $(e).attr("groupids", "")
                $(e).attr("categoryids", "")
            }
        });

    $('input#hparticipantids').remove();

    this.SendBlockChange();

    return false;
}

ParticipantsItemData.prototype.BlockChange = function () {
    this.SendBlockChange();
}
//#endregion