//#region Категории
function CategoryItemData(observer) {
    var that = this;

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

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

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

//функция убирает подсветку блока
CategoryItemData.prototype.Unhighlight = function () {
    $('#categories').removeClass('taskFormHub-highlightBlock');
}
CategoryItemData.prototype.InitConflictAfterSubmit = function (submitData) {

    if (this.TaskRightsDisplayType() == ItemDataHelper.TaskRightsDisplayType.None)
        return false;

    var that = this;
    var $parent = $('[taskcategorytitle]').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.CategoryId; });
        var curArray = that.GetCurrentVal();
        var oldArray = that.GetOldValue();
        //var myEditedArray = oldArray.filter(function (item) { return curArray.indexOf(item) < 0; });  //$(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 isChanged = this.IsChanged();

        if (isChanged && !ItemDataHelper.ArraysIsEquals(curArray, submitArray) && $('#onecategoryonticket').val() == "True") {

            var $conflictMessage = $(this.tmpl_conflictMessageBase({ blockName: this._options.name }));

            var selectorType = that.GetSelectorType();

            $conflictMessage.find('a').click(function (e) {
                e.preventDefault();

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

                var cur = that.GetCurrentVal();

                var c =
                        '<div>\
                            <label>\
                                <input type="radio" name="conflictradioresolve-' + that._options.name + '" value="1" checked />' + TaskFormHubResources.ConflictDialogContent_UseOldValue + '\
                            </label>';
                if (cur.length == 0) {
                    c += '<div name="conflictradioresolve-' + that._options.name + '-value1" emptyvalue>' + TaskFormHubResources.ConflictDialogContent_Category_Empty + '</div>'
                }
                else {
                    var $li = $('#categories ul.items li:first');
                    c += '<div name="conflictradioresolve-' + that._options.name + '-value1" conflictvalue="' + $li.attr('data-id') + '">';
                    c += $li.clone().children().remove().end().text();
                    c += '</div>';
                }
                c += '</div><hr>\
                        <div>\
                            <label>\
                                <input type="radio" name="conflictradioresolve-' + that._options.name + '" value="0" />' + TaskFormHubResources.ConflictDialogContent_UseNewValue + '\
                            </label>';
                if (submitData.length == 0) {
                    c += '<div name="conflictradioresolve-' + that._options.name + '-value0" emptyvalue>' + TaskFormHubResources.ConflictDialogContent_Category_Empty + '</div>'
                }
                else {
                    c += '<div name="conflictradioresolve-' + that._options.name + '-value0" conflictvalue=\'' + JSON.stringify(submitData[0]) + '\'>';
                    c += submitData[0].CategoryName;
                    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 {
                                //удаляем всех выбранных
                                var $select = $(that._options.selector);
                                $select.find('option').remove();
                                $('#categories ul.items li').remove();

                                var $resolvecontent = $content.find('[name="conflictradioresolve-' + that._options.name + '-value0"]');
                                if ($resolvecontent.is('[emptyvalue]')) {
                                }
                                else {
                                    var conflictvalue = JSON.parse($resolvecontent.attr('conflictvalue'));
                                    categorySelected(conflictvalue.CategoryId, conflictvalue.CategoryName, false);
                                }
                            }

                            //удаляем инфу о конфликте
                            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;
        }
        else {
            //удаляем инфу о конфликте
            that.isConflict = false;
            that.$conflictMessageElement = undefined;
            $parent.find('[conflict-block="' + that._options.name + '"]').remove();

            var $select = $(this._options.selector);
            //var promises = [];
            var serverData = [];
            $.each(submitData, function (k, v) {
                serverData.push(v.CategoryId);
                categorySelected(v.CategoryId, v.CategoryName, false);
            });
            //$.when.apply($, promises).then(function (result) {
                if (curArray.length) {
                    for (var i = 0; i < curArray.length; i++) {
                        var curItem = curArray[i];
                        if (serverData.indexOf(curItem) == -1 && myAddedArray.indexOf(curItem) == -1 && myRemovedArray.indexOf(curItem) == -1) {
                            $('#categories ul.items li[data-id="'+curArray[i]+'"]').remove();
                            $select.find('option[value="' + curArray[i] + '"]').remove();
                        }
                    }
                }

                var $notconflictMessage = $(that.tmpl_notconflictMessageBase({ blockName: that._options.name }));
                //добавить новую инфу
                $parent.append($notconflictMessage);

                that.SetOldValue($(ItemDataHelper.ArraysMergeDistinct(that.GetCurrentVal(), myRemovedArray)).not(myAddedArray).get());
                Promise.all([$select.trigger('change')])
                    .then(function () {
                        checkCategory();
                    });
                that.SendBlockChange();
            //});

            return false;
        }

    }

    return false;
}
CategoryItemData.prototype.AppendNotConflict = function () { }
CategoryItemData.prototype.AppendNotConflictUpdate = function () { }
CategoryItemData.prototype.AppendConflict1 = function () { }
CategoryItemData.prototype.AppendConflict2 = function () { }
//#endregion