private static ConcurrentDictionary <int, FreeHierarchyTreeItem> GenerateStandartTreeBySupplyPS(FreeHierarchyTreeDescriptor descriptor, bool isHideTi)
        {
            var items  = new List <FreeHierarchyTreeItem>();
            var result = new ConcurrentDictionary <int, FreeHierarchyTreeItem>();

            foreach (var value in from ps in EnumClientServiceDictionary.DetailPSList
                     join ps_sup in GlobalTreeDictionary.PowerSupply_PS_List on ps.Key equals ps_sup.PS_ID into temp
                     from ps_t in temp.DefaultIfEmpty()
                     where ps_t == null
                     orderby ps.Value.Name
                     select ps.Value)
            {
                if (!IsGlobalFilterHaveItem(value))
                {
                    continue;
                }

                UserRightsForTreeObject right;
                if (!Manager.User.AccumulateRightsAndVerify(value, EnumObjectRightType.SeeDbObjects, value.GetObjectRightType(), out right))
                {
                    continue;
                }

                FreeHierarchyTreeItem newItem = new FreeHierarchyTreeItem(descriptor, value, nodeName: value.Name)
                {
                    FreeHierItem_ID       = descriptor.GetMinIdAndDecrement(),
                    IncludeObjectChildren = true,
                    IsHideTi         = isHideTi,
                    FreeHierItemType = EnumFreeHierarchyItemType.PS,
                    NodeRights       = right,
                };

                items.Add(newItem);
                newItem.Descriptor.Tree = result;
                if (newItem.IncludeObjectChildren)
                {
                    newItem.LoadStaticChildren(true, isHideTi);
                    newItem.Descriptor.NeedFindTI = true;
                }
            }
            if (FreeHierarchyTreeDescriptor.Sort != null)
            {
                FreeHierarchyTreeDescriptor.Sort(items);
            }
            foreach (var i in items)
            {
                result[i.FreeHierItem_ID] = i;
            }
            return(result);
        }
        // добавление ТП
        private static void addTP(FreeHierarchyTreeItem parent, TPoint tp, ref int minID,
                                  FreeHierarchyTreeDescriptor descriptor, ConcurrentDictionary <int, FreeHierarchyTreeItem> result, List <int> removedTp)
        {
            minID--;
            var newTP = new FreeHierarchyTreeItem(descriptor, tp)
            {
                FreeHierItem_ID       = minID,
                FreeHierItemType      = EnumFreeHierarchyItemType.TP,
                Parent                = parent,
                NodeRights            = parent.HierObject.GetObjectRightType(),
                IsChildrenInitializet = true,
            };

            parent.Children.Add(newTP);
            result.TryAdd(minID, newTP);
            removedTp.Add(minID);
            newTP.Descriptor.Tree = result;
        }
        public static ConcurrentDictionary <int, FreeHierarchyTreeItem> GenerateJuridicalPersonTree(FreeHierarchyTreeDescriptor descriptor, bool isFactPowerTree, bool isAddVoidJuridicalPerson)
        {
            var result = new ConcurrentDictionary <int, FreeHierarchyTreeItem>();
            int minID  = -1;

            var directConsumerDictionary   = new Dictionary <int, Dictionary <int, FreeHierarchyTreeItem> >();
            var juridicalPersonsDictionary = new Dictionary <int, FreeHierarchyTreeItem>();

            var sectionsWithContracts = new HashSet <int>();

            // Построение договоров
            foreach (var contract in EnumClientServiceDictionary.ContractDict.Values)
            {
                List <int> sectionIds;
                if (EnumClientServiceDictionary.SectionByContract == null || !EnumClientServiceDictionary.SectionByContract.TryGetValue(contract.JuridicalPersonContract_ID, out sectionIds) || sectionIds == null)
                {
                    continue;
                }

                if (isFactPowerTree)
                {
                    sectionsWithContracts.UnionWith(sectionIds);
                }

                UserRightsForTreeObject juridicalPersonRight         = null;
                FreeHierarchyTreeItem   juridicalPersonHierarchyItem = null;
                TJuridicalPerson        juridicalPerson;
                var  isExistsJuridicalPersonRight = false;
                int? rId         = null;
                bool isNewPerson = false;
                // построение Юридических лиц
                if (EnumClientServiceDictionary.JuridicalPersonByContract.TryGetValue(contract.JuridicalPersonContract_ID, out juridicalPerson))
                {
                    isExistsJuridicalPersonRight = Manager.User.AccumulateRightsAndVerify(juridicalPerson, EnumObjectRightType.SeeDbObjects, null, out juridicalPersonRight);
                    isNewPerson = !juridicalPersonsDictionary.TryGetValue(juridicalPerson.Item.JuridicalPerson_ID, out juridicalPersonHierarchyItem);
                    if (isNewPerson || juridicalPersonHierarchyItem == null)
                    {
                        minID--;
                        juridicalPersonHierarchyItem = new FreeHierarchyTreeItem(descriptor, juridicalPerson)
                        {
                            FreeHierItem_ID       = minID,
                            FreeHierItemType      = EnumFreeHierarchyItemType.JuridicalPerson,
                            NodeRights            = juridicalPersonRight,
                            IsChildrenInitializet = true,
                        };

                        // построение родителей иерархической структуры
                        rId = minID;
                        juridicalPersonsDictionary[juridicalPerson.Item.JuridicalPerson_ID] = juridicalPersonHierarchyItem;
                    }
                }

                UserRightsForTreeObject contractRight;
                var isExistsContractRight = Manager.User.AccumulateRightsAndVerify(contract, EnumObjectRightType.SeeDbObjects, juridicalPersonRight, out contractRight);

                minID--;
                var contractTreeId = minID;
                var newContract    = new FreeHierarchyTreeItem(descriptor, contract)
                {
                    FreeHierItem_ID       = minID,
                    FreeHierItemType      = EnumFreeHierarchyItemType.Contract,
                    NodeRights            = contractRight,
                    Parent                = juridicalPersonHierarchyItem,
                    IsChildrenInitializet = true,
                };

                var isExistsChildSeeDbObjects = false;
                var absentSections            = new Dictionary <int, FreeHierarchyTreeItem>();
                var removedItems = new List <int>();
                // построение сечений
                foreach (var section in sectionIds.Select(s => GlobalSectionsDictionary.SectionsList[s]))
                {
                    if (section == null)
                    {
                        continue;
                    }

                    UserRightsForTreeObject sectionRight;
                    var isExistsSectionRight = Manager.User.AccumulateRightsAndVerify(section, EnumObjectRightType.SeeDbObjects, contractRight, out sectionRight);
                    if (sectionRight.IsDeniedRight(EnumObjectRightType.SeeDbObjects))
                    {
                        continue;
                    }

                    minID--;
                    var newSection = new FreeHierarchyTreeItem(descriptor, section)
                    {
                        FreeHierItem_ID       = minID,
                        FreeHierItemType      = EnumFreeHierarchyItemType.Section,
                        Parent                = newContract,
                        NodeRights            = sectionRight,
                        IsChildrenInitializet = true,
                    };
                    var sectionTreeId = minID;
                    var isExistsSectionChildrenRight = false;
                    var removedTp = new List <int>();
                    Dictionary <int, FreeHierarchyTreeItem> dirConsumers;
                    directConsumerDictionary.TryGetValue(section.Section_ID, out dirConsumers);

                    if (section.TP != null)
                    {
                        foreach (var tp in section.TP.OrderBy(s => s.Item.StringName))
                        {
                            if (tp.DirectConsumer_ID != null)
                            {
                                if (dirConsumers == null)
                                {
                                    dirConsumers = new Dictionary <int, FreeHierarchyTreeItem>();
                                    directConsumerDictionary.Add(section.Section_ID, dirConsumers);
                                }

                                FreeHierarchyTreeItem dirCon = null;
                                if (!dirConsumers.TryGetValue(tp.DirectConsumer_ID.Value, out dirCon) || dirCon == null)
                                {
                                    var dc = EnumClientServiceDictionary.DirectConsumers[tp.DirectConsumer_ID.Value];
                                    UserRightsForTreeObject directConsumerRight;
                                    if (!Manager.User.AccumulateRightsAndVerify(dc, EnumObjectRightType.SeeDbObjects, sectionRight, out directConsumerRight))
                                    {
                                        continue;
                                    }
                                    isExistsSectionChildrenRight = true;
                                    minID--;
                                    dirCon = new FreeHierarchyTreeItem(descriptor, dc)
                                    {
                                        FreeHierItem_ID       = minID,
                                        FreeHierItemType      = EnumFreeHierarchyItemType.DirectConsumer,
                                        Parent                = newSection,
                                        NodeRights            = directConsumerRight,
                                        IsChildrenInitializet = true,
                                    };
                                    newSection.Children.Add(dirCon);
                                    result.TryAdd(minID, dirCon);
                                    removedTp.Add(minID);
                                    dirCon.Descriptor.Tree             = result;
                                    dirConsumers[dc.DirectConsumer_ID] = dirCon;
                                }

                                // добавление ТП в объект ЭПУ
                                addTP(dirCon, tp, ref minID, descriptor, result, removedTp);
                            }
                            // добавление ТП в сечение (в случае, если ТП не связано с прямым потребителем)
                            else
                            {
                                addTP(newSection, tp, ref minID, descriptor, result, removedTp);
                            }
                        }
                    }

                    if (isExistsSectionRight || isExistsSectionChildrenRight)
                    {
                        isExistsChildSeeDbObjects = true;
                        newContract.Children.Add(newSection);
                        result.TryAdd(sectionTreeId, newSection);
                        newSection.Descriptor.Tree = result;
                    }
                    else
                    {
                        removedItems.AddRange(removedTp);
                        absentSections.Add(sectionTreeId, newSection);
                    }
                }

                if (juridicalPersonHierarchyItem != null)
                {
                    if (isNewPerson)
                    {
                        UserRightsForTreeObject parentRights;
                        buildParents(juridicalPersonHierarchyItem, isFactPowerTree, isExistsJuridicalPersonRight | isExistsContractRight, isExistsChildSeeDbObjects,
                                     ref minID,
                                     out parentRights);

                        juridicalPersonHierarchyItem.NodeRights = parentRights.AccamulateRights(juridicalPersonRight);
                    }

                    isExistsContractRight = isExistsContractRight |
                                            Manager.User.IsAssentRight(juridicalPersonHierarchyItem.HierObject.GetObjectRightType(), EnumObjectRightType.SeeDbObjects);

                    if (isExistsContractRight || isExistsChildSeeDbObjects)
                    {
                        newContract.NodeRights = newContract.NodeRights.AccamulateRights(juridicalPersonHierarchyItem.NodeRights);
                        //Добавляем пропущенные сечения
                        foreach (var freeHierarchyTreeItem in absentSections)
                        {
                            freeHierarchyTreeItem.Value.NodeRights = freeHierarchyTreeItem.Value.NodeRights.AccamulateRights(juridicalPersonHierarchyItem.NodeRights);
                            newContract.Children.Add(freeHierarchyTreeItem.Value);
                            result.TryAdd(freeHierarchyTreeItem.Key, freeHierarchyTreeItem.Value);
                            freeHierarchyTreeItem.Value.Descriptor.Tree = result;
                            removedItems.Add(freeHierarchyTreeItem.Key);
                            foreach (var sectionChildren in freeHierarchyTreeItem.Value.Children)
                            {
                                sectionChildren.NodeRights = sectionChildren.NodeRights.AccamulateRights(juridicalPersonHierarchyItem.NodeRights);
                            }
                        }

                        if (isNewPerson && rId.HasValue)
                        {
                            juridicalPersonHierarchyItem.Descriptor.Tree = result;
                            result.TryAdd(rId.Value, juridicalPersonHierarchyItem);
                            removedItems.Add(rId.Value);
                        }

                        juridicalPersonHierarchyItem.Children.Add(newContract);
                    }
                }

                if (isExistsContractRight || isExistsChildSeeDbObjects)
                {
                    newContract.Descriptor.Tree = result;
                    result.TryAdd(contractTreeId, newContract);
                }
                else
                {
                    //Удаление т.к. нет прав
                    foreach (var removedItemId in removedItems)
                    {
                        FreeHierarchyTreeItem removed;
                        result.TryRemove(removedItemId, out removed);
                    }
                }
            }


            //Добавляем пропущенные юр. лица (у которых нет привязки к контракту)
            if (isAddVoidJuridicalPerson)
            {
                var contractByPersonDict = EnumClientServiceDictionary.ContractByPersonDict;
                //contractByPersonDict.Prepare(new HashSet<int>(EnumClientServiceDictionary.JuridicalPersonsDict.Values.Select(jp=>jp.Item.JuridicalPerson_ID)));
                foreach (var juridicalPerson in EnumClientServiceDictionary.JuridicalPersonsDict.Values)
                {
                    var id = juridicalPerson.Item.JuridicalPerson_ID;
                    //пропускаем уже добавленные или те на которые нехватает прав
                    if (juridicalPersonsDictionary.ContainsKey(id))
                    {
                        continue;
                    }

                    UserRightsForTreeObject juridicalPersonRight;
                    var isExistsJuridicalPersonRight = Manager.User.AccumulateRightsAndVerify(juridicalPerson, EnumObjectRightType.SeeDbObjects, null, out juridicalPersonRight);

                    var rId = --minID;
                    var juridicalPersonHierarchyItem = new FreeHierarchyTreeItem(descriptor, juridicalPerson)
                    {
                        FreeHierItem_ID  = rId,
                        FreeHierItemType = EnumFreeHierarchyItemType.JuridicalPerson,
                        NodeRights       = juridicalPerson.GetObjectRightType(),
                    };

                    var isExistsContractRight = false;

                    UserRightsForTreeObject parentRights;
                    buildParents(juridicalPersonHierarchyItem, isFactPowerTree, isExistsJuridicalPersonRight, isExistsContractRight,
                                 ref minID,
                                 out parentRights);
                    juridicalPersonHierarchyItem.NodeRights = parentRights.AccamulateRights(juridicalPersonRight);

                    List <Dict_JuridicalPersons_Contract> contracts;
                    if (contractByPersonDict != null && contractByPersonDict.TryGetValue(id, out contracts) && contracts.Count > 0)
                    {
                        //Перебирам контракты для этого юр. лица
                        foreach (var contract in contracts)
                        {
                            UserRightsForTreeObject contractRight;
                            if (!Manager.User.AccumulateRightsAndVerify(contract, EnumObjectRightType.SeeDbObjects, juridicalPersonHierarchyItem.NodeRights, out contractRight))
                            {
                                continue;
                            }

                            isExistsContractRight = true;

                            FreeHierarchyTreeItem newContract = new FreeHierarchyTreeItem(descriptor, contract)
                            {
                                FreeHierItem_ID  = --minID,
                                FreeHierItemType = EnumFreeHierarchyItemType.Contract,
                                NodeRights       = contractRight,
                                Parent           = juridicalPersonHierarchyItem,
                            };

                            newContract.NodeRights      = newContract.NodeRights.AccamulateRights(juridicalPersonHierarchyItem.NodeRights);
                            newContract.Descriptor.Tree = result;
                            juridicalPersonHierarchyItem.Children.Add(newContract);
                            result.TryAdd(minID, newContract);
                        }
                    }

                    if (Manager.User.IsAssentRight(juridicalPersonHierarchyItem.NodeRights, EnumObjectRightType.SeeDbObjects) || isExistsContractRight)
                    {
                        juridicalPersonHierarchyItem.Descriptor.Tree = result;
                        result.TryAdd(rId, juridicalPersonHierarchyItem);
                    }
                }
            }

            if (isFactPowerTree)
            {
                // добавление оставшихся сечений (те, что не привязаны к юр.лицам и договорам)
                foreach (var section in GlobalSectionsDictionary.SectionsList.Values)
                {
                    if (section.Section_ID <= 0 || sectionsWithContracts.Contains(section.Section_ID))
                    {
                        continue;
                    }

                    minID--;
                    UserRightsForTreeObject sectionRight;
                    var isExistsSectionRight = Manager.User.AccumulateRightsAndVerify(section, EnumObjectRightType.SeeDbObjects, null, out sectionRight);

                    var newSection = new FreeHierarchyTreeItem(descriptor, section)
                    {
                        FreeHierItem_ID  = minID,
                        FreeHierItemType = EnumFreeHierarchyItemType.Section,
                    };

                    var rId = minID;
                    newSection.Descriptor.Tree = result;
                    // построение родителей иерархической структуры
                    UserRightsForTreeObject parentRights = null;
                    buildParents(newSection, true, isExistsSectionRight, isExistsSectionRight, ref minID, out parentRights);
                    newSection.NodeRights = parentRights;

                    if (section.TP != null)
                    {
                        result[rId] = newSection;
                        var removedTp = new List <int>();
                        foreach (var tp in section.TP)
                        {
                            addTP(newSection, tp, ref minID, descriptor, result, removedTp);
                        }
                    }
                }
            }

            // просчет кол-ва элементов всех узлов и сортировка
            countElements(result.Where(i => i.Value.Parent == null).Select(i => i.Value));

            return(result);
        }
        private static ConcurrentDictionary <int, FreeHierarchyTreeItem> GenerateOldTelescopeTree(FreeHierarchyTreeDescriptor descriptor)
        {
            var result = new ConcurrentDictionary <int, FreeHierarchyTreeItem>();

            var rootNodes = EnumClientServiceDictionary.OldTelescopeTreeNodes.Values.Where(i => i.TreeLevel == 0);

            if (rootNodes == null)
            {
                return(result);
            }

            foreach (var rootNode in rootNodes)
            {
                rootNode.Parent_Absolute_Number = ""; //иначе зацикливание где нибудь будет

                var newItemNode = new FreeHierarchyTreeItem(descriptor, rootNode, false, string.Empty,
                                                            descriptor.GetMinIdAndDecrement(), null, true, nodeRights: null,
                                                            freeHierItemType: EnumFreeHierarchyItemType.OldTelescopeTreeNode);

                newItemNode.Descriptor.Tree = result;

                result[newItemNode.FreeHierItem_ID] = newItemNode;
            }

            return(result);
        }
        /// <summary>
        /// Генерация дерева (списка) балансов (приложения 63) для выгрузки xml
        /// </summary>
        private static ConcurrentDictionary <int, FreeHierarchyTreeItem> GenerateBalance63Tree(FreeHierarchyTreeDescriptor descriptor)
        {
            var result = new ConcurrentDictionary <int, FreeHierarchyTreeItem>();

            var rootNodes = DeclaratorService.Service.Get_ExportService_Balances63();

            if (rootNodes == null)
            {
                return(result);
            }

            foreach (var rootNode in rootNodes)
            {
                var newItemNode = new FreeHierarchyTreeItem(descriptor, rootNode, false, string.Empty,
                                                            descriptor.GetMinIdAndDecrement(), null, true, nodeRights: null,
                                                            freeHierItemType: EnumFreeHierarchyItemType.FiasFullAddress);
                //{
                //    StringName = rootNode.StringName,
                //};

                newItemNode.Descriptor.Tree = result;

                //newItemNode.UpdateCountParents();

                result[newItemNode.FreeHierItem_ID] = newItemNode;
            }

            return(result);
        }
        private static ConcurrentDictionary <int, FreeHierarchyTreeItem> GenerateStandartTreeSections(FreeHierarchyTreeDescriptor descriptor)
        {
            var result = new ConcurrentDictionary <int, FreeHierarchyTreeItem>();
            var items  = new List <FreeHierarchyTreeItem>();

            HashSet <ID_TypeHierarchy> objectsHasRightDbSee = null;
            var hiers1 = EnumClientServiceDictionary.HierLev1List.Values;

            if (Manager.User != null && !Manager.User.IsAdmin)
            {
                try
                {
                    //Запрашиваем права на список объектов
                    objectsHasRightDbSee = Manager.User.UserHasRightDbSee(hiers1.Select(h1 => new ID_TypeHierarchy
                    {
                        ID            = h1.Id,
                        TypeHierarchy = enumTypeHierarchy.Dict_HierLev1,
                    }).ToList());
                }
                catch (Exception ex)
                {
                    Manager.UI.ShowMessage("Ошибка запроса прав: " + ex.Message);
                }
            }

            foreach (var item in hiers1.OrderBy(v => v.Item))
            {
                //Глобальный фильтр
                if (!IsGlobalFilterHaveItem(item))
                {
                    continue;
                }

                var minID = descriptor.GetMinIdAndDecrement();
                UserRightsForTreeObject hier1Right;
                var isExistsRight = Manager.User.AccumulateRightsAndVerify(item, EnumObjectRightType.SeeDbObjects, null, out hier1Right);
                if (!isExistsRight && Manager.User != null && !Manager.User.IsAdmin && objectsHasRightDbSee != null)
                {
                    //Проверяем через дочерних объектов
                    isExistsRight = objectsHasRightDbSee.Any(o => o.ID == item.Id && o.TypeHierarchy == item.GetTypeHierarchy());
                }

                var newItem = new FreeHierarchyTreeItem(descriptor, item, nodeName: item.Name)
                {
                    FreeHierItem_ID       = minID,
                    IncludeObjectChildren = true,
                    FreeHierItemType      = EnumFreeHierarchyItemType.HierLev1,
                    NodeRights            = hier1Right
                };

                newItem.Descriptor.Tree = result;
                bool isExistsChildSeeDbObjects = false;
                if (newItem.IncludeObjectChildren)
                {
                    isExistsChildSeeDbObjects = newItem.LoadStaticChildren(isExistsRight, isLoadStatic: true);
                }

                isExistsChildSeeDbObjects = newItem.IncludeChildrenSection(item.Id, item.Type, newItem.Children) || isExistsChildSeeDbObjects ||
                                            item.TIStatus.HasFlag(EnumTIStatus.Is_Section_Enabled);

                //У объекта нет прав на просмотр, или нет дочерних объектов на которые есть такие права
                if (isExistsChildSeeDbObjects) //Включаем только если есть сечения
                {
                    items.Add(newItem);
                }
                else
                {
                    newItem.Dispose();
                }
            }

            //Сечения которые не привязаны ни к чему
            foreach (var section in EnumClientServiceDictionary.GetSections().Values.Where(s => s.ParentId <= 0 && s.Section_ID > 0).OrderBy(s => s.Item))
            {
                UserRightsForTreeObject right;
                if (!Manager.User.AccumulateRightsAndVerify(section, EnumObjectRightType.SeeDbObjects, null, out right))
                {
                    continue;
                }

                var minID = descriptor.GetMinIdAndDecrement();
                FreeHierarchyTreeItem newItem = new FreeHierarchyTreeItem(descriptor, section)
                {
                    FreeHierItem_ID       = minID,
                    IncludeObjectChildren = true,
                    NodeRights            = right,
                    FreeHierItemType      = EnumFreeHierarchyItemType.Section,
                };

                newItem.Descriptor.Tree = result;
                newItem.LoadStaticChildren(true);

                items.Add(newItem);
            }

            if (FreeHierarchyTreeDescriptor.Sort != null)
            {
                FreeHierarchyTreeDescriptor.Sort(items);
            }
            foreach (var i in items)
            {
                result[i.FreeHierItem_ID] = i;
            }
            return(result);
        }
        /// <summary>
        /// Генерация стандартного дерева ПС
        /// </summary>
        /// <returns></returns>
        private static ConcurrentDictionary <int, FreeHierarchyTreeItem> GenerateStandartTreePS(FreeHierarchyTreeDescriptor descriptor, bool isHideTi)
        {
            var result = new ConcurrentDictionary <int, FreeHierarchyTreeItem>();

            var hiers1 = EnumClientServiceDictionary.HierLev1List.Values;


            var filterStatus = descriptor.FilterStatus;

            foreach (var item in hiers1.OrderBy(v => v.Item)) //сортируем по названию
            {
                if (item == null ||
                    (filterStatus.HasValue && (item.TIStatus & filterStatus.Value) == EnumTIStatus.None) || //Используется фильтр на дереве
                    !IsGlobalFilterHaveItem(item))    //Глобальный фильтр
                {
                    continue;
                }

                var isExistsChildSeeDbObjects = Manager.User.IsAssentRight(item, EnumObjectRightType.SeeDbObjects, null);

                if (!isExistsChildSeeDbObjects && //Нет собственных прав
                    !FreeHierarchyTreePreparer.ExistsStandartChildSeeDbObjects(item, descriptor.Tree_ID ?? -101, true)   //И нет дочерних объектов с правами
                    )
                {
                    continue;
                }

                var newItem = new FreeHierarchyTreeItem(descriptor, item, false, item.Name, descriptor.GetMinIdAndDecrement(), null, true, isHideTi, item.ObjectRights,
                                                        EnumFreeHierarchyItemType.HierLev1)
                {
                    Descriptor =
                    {
                        Tree = result
                    }
                };

                if (newItem.IncludeObjectChildren)
                {
                    isExistsChildSeeDbObjects = newItem.LoadStaticChildren(isExistsChildSeeDbObjects, isHideTi);
                }

                //У объекта нет прав на просмотр, или нет дочерних объектов на которые есть такие права
                //if (isExistsRight || isExistsChildSeeDbObjects)
                //{
                result[newItem.FreeHierItem_ID] = newItem;
                //}
                //else
                //{
                //    newItem.Dispose();
                //}
            }
            //if (FreeHierarchyTreeDescriptor.Sort != null) FreeHierarchyTreeDescriptor.Sort(items);
            //foreach (var i in items) result[i.FreeHierItem_ID] = i;
            return(result);
        }
        /// <summary>
        /// Генерация стандартного дерева Список OPCUA серверов
        /// </summary>
        private static ConcurrentDictionary <int, FreeHierarchyTreeItem> GenerateStandartTree_Dict_OPCUAServers(FreeHierarchyTreeDescriptor descriptor)
        {
            var items     = new List <FreeHierarchyTreeItem>();
            var result    = new ConcurrentDictionary <int, FreeHierarchyTreeItem>();
            var uaServers = UAHierarchyDictionaries.UaServers(Manager.UI.ShowMessage);

            if (uaServers == null)
            {
                return(null);
            }

            descriptor.NeedFindUaNode = true;

            foreach (var item in uaServers.Values)
            {
                UserRightsForTreeObject right;
                if (!Manager.User.AccumulateRightsAndVerify(item, EnumObjectRightType.SeeDbObjects, null, out right))
                {
                    continue;
                }

                var newItem = new FreeHierarchyTreeItem(descriptor, item)
                {
                    FreeHierItem_ID       = descriptor.GetMinIdAndDecrement(),
                    IncludeObjectChildren = true,
                    IsHideTi         = false,
                    FreeHierItemType = EnumFreeHierarchyItemType.UAServer,
                    NodeRights       = null,
                };

                newItem.Descriptor.Tree = result;

                items.Add(newItem);

                //дабавляем корневые узлы вручную
                //дальше будут подгружаться при раскрытии?
                List <TUANode> rootNodes = UAService.Service.UA_Get_RootNodes(item.UAServer_ID);
                foreach (var rootNode in rootNodes)
                {
                    TUANode node = null;
                    UAHierarchyDictionaries.UANodesDict.TryGetValue(rootNode.UANodeId, out node);
                    if (node == null)
                    {
                        continue;
                    }

                    FreeHierarchyTreeItem newItemNode = new FreeHierarchyTreeItem(newItem.Descriptor, node)
                    {
                        FreeHierItem_ID       = descriptor.GetMinIdAndDecrement(),
                        Parent                = newItem,
                        IncludeObjectChildren = true,
                        FreeHierItemType      = EnumFreeHierarchyItemType.UANode,
                        NodeRights            = right,
                    };

                    newItem.Children.Add(newItemNode);
                    newItem.Descriptor.Tree.TryAdd(newItemNode.FreeHierItem_ID, newItemNode);

                    //добавляем дочерние
                    //newItemNode.IncludeChildrenOPCNodes(newItemNode.Children, false);
                }
            }
            if (FreeHierarchyTreeDescriptor.Sort != null)
            {
                FreeHierarchyTreeDescriptor.Sort(items);
            }
            foreach (var i in items)
            {
                result[i.FreeHierItem_ID] = i;
            }
            return(result);
        }
        private static FreeHierarchyTreeItem Create_FreeHierarchyTreeItem(int minID, KeyValuePair <Guid, TFIASNode> obj, FreeHierarchyTreeDescriptor descriptor)
        {
            var newItemNode = new FreeHierarchyTreeItem(descriptor, obj.Value)
            {
                FreeHierItem_ID       = minID,
                IncludeObjectChildren = true,
                FreeHierItemType      = EnumFreeHierarchyItemType.FiasFullAddress,
                NodeRights            = null,
                StringName            = obj.Value.StringName,
                FIASNode = obj.Value,
            };

            return(newItemNode);
        }
        /// <summary>
        /// Генерация стандартного дерева FIAS адреса, которые используются
        /// </summary>
        private static ConcurrentDictionary <int, FreeHierarchyTreeItem> GenerateStandartTree_FIAS(bool IncludeHerarchyObjects, FreeHierarchyTreeDescriptor descriptor)
        {
            var result = new ConcurrentDictionary <int, FreeHierarchyTreeItem>();

            //добавляем корневые узлы
            IEnumerable <TFIASNode> rootNodes;

            if (!IncludeHerarchyObjects)
            {
                rootNodes = DeclaratorService.FIAS_Get_RootNodes();
            }
            else
            {
                rootNodes = DeclaratorService.FIASToHierarchy_Get_RootNodes();
            }

            if (rootNodes == null)
            {
                return(result);
            }

            foreach (var rootNode in rootNodes)
            {
                var newItemNode = new FreeHierarchyTreeItem(descriptor, rootNode, false, string.Empty, descriptor.GetMinIdAndDecrement(), null, true, nodeRights: null,
                                                            freeHierItemType: EnumFreeHierarchyItemType.FiasFullAddress)
                {
                    StringName = rootNode.StringName,
                    FIASNode   = rootNode,
                };

                newItemNode.Descriptor.Tree = result;

                //newItemNode.UpdateCountParents();

                //добавляем дочерние
                if (rootNode.IsChildrenExists)
                {
                    newItemNode.IncludeChildrenFIASNodes((rootNode.IsHierObjectExists || descriptor.Tree_ID == TreeTypeStandart_Dict_FIASToHierarchy));
                }

                result[newItemNode.FreeHierItem_ID] = newItemNode;
            }

            return(result);
        }
        public static IDictionary <int, FreeHierarchyTreeItem> GetTree(FreeHierarchyTreeDescriptor descriptor, out bool isFirstLoaded, bool isHideTi = false,
                                                                       HashSet <long> selectedNodes = null, bool isFullReload = false, HashSet <int> singreRootFreeHierItemIds = null)
        {
            isFirstLoaded = false;

            //Признак администратора
            bool isUserAdmin = Manager.User.IsAdmin;

#if DEBUG
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();
#endif

            #region это стандартные деревья их не загружаем

            switch (descriptor.Tree_ID)
            {
            //case TreeTypeStandartPS:
            case TreeTypeStandartTIFormula:
            case TreeTypeStandartDistributingArrangementAndBusSystem:

                //if (isFullReload)
                //{
                //    descriptor.UpdateIncludedObjectChildrenAsync(Manager.User.User_ID);
                //}

                return(GenerateStandartTreePS(descriptor, isHideTi));

            case TreeTypeStandartSections:
            case TreeTypeStandartSectionsNSI:
                return(GenerateStandartTreeSections(descriptor));

            case TreeTypeStandartBySupplyPS:
                return(GenerateStandartTreeBySupplyPS(descriptor, isHideTi));

            case TreeTypeStandartGroupTP:
                return(JuridicalPersonTree.GenerateJuridicalPersonTree(descriptor, true, false));

            case TreeTypeStandartJuridicalPerson:
                return(JuridicalPersonTree.GenerateJuridicalPersonTree(descriptor, false, true));

            case TreeTypeStandart_Dict_OPCUAServers:
                return(GenerateStandartTree_Dict_OPCUAServers(descriptor));

            case TreeTypeStandart_Dict_FIAS:
                return(GenerateStandartTree_FIAS(false, descriptor));

            case TreeTypeStandart_Dict_FIASToHierarchy:
                return(GenerateStandartTree_FIAS(true, descriptor));

            case TreeExplXmlExportConfigs:
                return(GenerateExplXmlExportConfigsTree(descriptor));


            case TreeExplXmlBalance63:
                return(GenerateBalance63Tree(descriptor));

            case TreeOldTelescope:
                return(GenerateOldTelescopeTree(descriptor));
            }

            #endregion

            var result = new ConcurrentDictionary <int, FreeHierarchyTreeItem>();
            List <TFreeHierarchyTreeItem> tempList = null;

            try
            {
                int?parenId = null;
                if (singreRootFreeHierItemIds != null)
                {
                    parenId = singreRootFreeHierItemIds.FirstOrDefault();
                }

                tempList = FreeHierarchyTreeDictionary.GetBranch(Manager.User.User_ID, descriptor.Tree_ID.GetValueOrDefault(), parenId,
                                                                 isFullReload, onError: Manager.UI.ShowMessage);
            }
            catch (Exception ex)
            {
                Manager.UI.ShowMessage(ex.Message);
            }

#if DEBUG
            sw.Stop();
            Console.WriteLine("Запрос дерева в БД {0} млс", sw.ElapsedMilliseconds);
            sw.Restart();
#endif

            if (tempList == null)
            {
                return(result);
            }

            FreeHierarchyTreePreparer.PrepareGlobalDictionaries(tempList);

            if (descriptor != null)
            {
                descriptor.Tree = result;
            }

            foreach (var newItem in FreeHierarchyTreePreparer.BuildBranch(null, tempList, descriptor, isHideTi, selectedNodes))
            {
                result.TryAdd(newItem.FreeHierItem_ID, newItem);
            }

            //if ((uspdList!=null&&(uspdList.Count>0)))
            //{
            //   ProcessUspdInTree(result,uspdList, isFilteredBySmallTi, isHideTi);
            //}

#if DEBUG
            sw.Stop();
            Console.WriteLine("Построение дерева {0} млс", sw.ElapsedMilliseconds);
#endif


            return(result);
        }