Exemplo n.º 1
0
        public void GetBindedItemsForMpd()
        {
            const int aircraftId = 2316;            // Воздушное судно 4LimaTest

            //инициализация core - ов
            var enviroment     = GetEnviroment();
            var itemRelationDA = new ItemsRelationsDataAccess(enviroment);
            var airctaftCore   = new AircraftsCore(enviroment.Loader, enviroment.NewKeeper, enviroment.NewLoader);

            airctaftCore.LoadAllAircrafts();
            var componentCore   = new ComponentCore(enviroment, enviroment.Loader, enviroment.NewLoader, enviroment.NewKeeper, airctaftCore, itemRelationDA);
            var directiveCore   = new DirectiveCore(enviroment.NewKeeper, enviroment.NewLoader, enviroment.Keeper, enviroment.Loader, itemRelationDA);
            var maintenanceCore = new MaintenanceCore(enviroment, enviroment.NewLoader, enviroment.NewKeeper, itemRelationDA, null);
            var bindedItemCore  = new BindedItemsCore(componentCore, directiveCore, maintenanceCore);

            //Загрузка базового компонента для того что бы привязать его к mpd и ad
            var baseDetail = enviroment.BaseComponents.FirstOrDefault(x => x.ParentAircraftId == aircraftId);
            var detail     = componentCore.GetComponents(baseDetail).FirstOrDefault();

            var mpd = new MaintenanceDirective {
                ParentBaseComponent = baseDetail
            };
            var dd = new ComponentDirective {
                ComponentId = detail.ItemId, Remarks = "DDTest"
            };
            var ad = new Directive {
                ParentBaseComponent = baseDetail, Remarks = "ADTest"
            };

            enviroment.NewKeeper.Save(dd);
            enviroment.NewKeeper.Save(ad);
            enviroment.NewKeeper.Save(mpd);

            mpd.ItemRelations.Add(new ItemsRelation
            {
                FirstItemId      = mpd.ItemId,
                FirtsItemTypeId  = mpd.SmartCoreObjectType.ItemId,
                SecondItemId     = dd.ItemId,
                SecondItemTypeId = dd.SmartCoreObjectType.ItemId,
                RelationTypeId   = WorkItemsRelationType.CalculationAffect
            });

            mpd.ItemRelations.Add(new ItemsRelation
            {
                FirstItemId      = mpd.ItemId,
                FirtsItemTypeId  = mpd.SmartCoreObjectType.ItemId,
                SecondItemId     = ad.ItemId,
                SecondItemTypeId = ad.SmartCoreObjectType.ItemId,
                RelationTypeId   = WorkItemsRelationType.CalculationAffect
            });

            foreach (var itemRelation in mpd.ItemRelations)
            {
                enviroment.NewKeeper.Save(itemRelation);
            }


            var bindedItemsADOnly = bindedItemCore.GetBindedItemsFor(aircraftId, new[] { mpd }, new [] { SmartCoreType.Directive.ItemId });
            var bindedItemsDDOnly = bindedItemCore.GetBindedItemsFor(aircraftId, new[] { mpd }, new [] { SmartCoreType.ComponentDirective.ItemId });
            var bindedItemsAll    = bindedItemCore.GetBindedItemsFor(aircraftId, new[] { mpd });


            foreach (var itemRelation in mpd.ItemRelations)
            {
                enviroment.NewKeeper.Delete(itemRelation);
            }

            enviroment.NewKeeper.Delete(mpd);
            enviroment.NewKeeper.Delete(dd);
            enviroment.NewKeeper.Delete(ad);


            Assert.IsTrue(bindedItemsADOnly[mpd].Count == 1);
            var forCheckAd = (Directive)bindedItemsADOnly[mpd].Single();

            Assert.AreEqual(forCheckAd.Remarks, ad.Remarks);

            Assert.IsTrue(bindedItemsDDOnly[mpd].Count == 1);
            var forCheckDd = (ComponentDirective)bindedItemsDDOnly[mpd].Single();

            Assert.AreEqual(forCheckDd.Remarks, dd.Remarks);

            Assert.IsTrue(bindedItemsAll[mpd].Count == 2);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Добавить выполнение работы к задаче
        /// </summary>
        /// <param name="performance"></param>
        /// <param name="saveAttachedFile"></param>
        public void Save(AbstractPerformanceRecord performance, bool saveAttachedFile = true)
        {
            if (performance == null)
            {
                return;
            }

            var type = AuditOperation.Created;

            if (performance.ItemId > 0)
            {
                type = AuditOperation.Changed;
            }

            performance.CorrectorId = _casEnvironment.IdentityUser.ItemId;

            _casEnvironment.Keeper.Save(performance, saveAttachedFile);
            _auditRepository.WriteAsync(performance, type, _casEnvironment.IdentityUser);

            if (performance.Parent.PerformanceRecords.GetItemById(performance.ItemId) == null)
            {
                performance.Parent.PerformanceRecords.Add(performance);
            }

            if (performance.Parent is MaintenanceDirective)
            {
                DirectiveRecord ddr = _casEnvironment.NewLoader.GetObjectListAll <DirectiveRecordDTO, DirectiveRecord>(new Filter("MaintenanceDirectiveRecordId", performance.ItemId)).FirstOrDefault();

                if (ddr != null)
                {
                    ComponentDirective dd = _casEnvironment.NewLoader.GetObject <ComponentDirectiveDTO, ComponentDirective>(new Filter("ItemId", ddr.ParentId));
                    if (dd != null)
                    {
                        BaseComponent bd = _componentCore.GetBaseComponentById(dd.ComponentId);
                        if (bd != null)
                        {
                            ddr.OnLifelength =
                                _casEnvironment.Calculator.GetFlightLifelengthOnStartOfDay(bd, performance.RecordDate);
                        }
                        else
                        {
                            General.Accessory.Component d = _componentCore.GetComponentById(dd.ComponentId);
                            if (d != null)
                            {
                                ddr.OnLifelength = _casEnvironment.Calculator.GetFlightLifelengthOnStartOfDay(d, performance.RecordDate);
                            }
                        }
                    }
                    ddr.RecordDate = performance.RecordDate;
                    _casEnvironment.NewKeeper.Save(ddr, saveAttachedFile);
                }
            }
            else if (performance.Parent is ComponentDirective)
            {
                DirectiveRecord ddr = performance as DirectiveRecord;
                if (ddr != null)
                {
                    DirectiveRecord mpdRecord = _casEnvironment.NewLoader.GetObject <DirectiveRecordDTO, DirectiveRecord>(new Filter("ItemId", ddr.MaintenanceDirectiveRecordId));
                    if (mpdRecord != null)
                    {
                        MaintenanceDirective md = _maintenanceCore.GetMaintenanceDirective(mpdRecord.ParentId);
                        if (md != null)
                        {
                            mpdRecord.OnLifelength = _casEnvironment.Calculator.GetFlightLifelengthOnStartOfDay(md.ParentBaseComponent, ddr.RecordDate);
                        }
                        mpdRecord.RecordDate = ddr.RecordDate;
                        _casEnvironment.NewKeeper.Save(mpdRecord, saveAttachedFile);
                    }
                }
            }
        }
Exemplo n.º 3
0
        protected override List <CustomCell> GetListViewSubItems(BaseEntityObject item)
        {
            var subItems = new List <CustomCell>();
            var author   = GlobalObjects.CasEnvironment.GetCorrector(item);

            DateTime?  approx;
            Lifelength remains = Lifelength.Null, next;
            AtaChapter ata;
            MaintenanceControlProcess maintenanceType;
            DateTime   transferDate;
            DateTime?  lastPerformanceDate = null;
            DateTime?  nextEstimated       = null;
            DateTime?  nextLimit           = null;
            Lifelength firstPerformance    = Lifelength.Null,
                       lastPerformance     = Lifelength.Null,
                       expiryRemain        = Lifelength.Null,
                       nextEstimatedData   = Lifelength.Null,
                       nextEstimatedDataC  = Lifelength.Null,
                       remainEstimated     = Lifelength.Null,
                       nextLimitData       = Lifelength.Null,
                       nextLimitDataC      = Lifelength.Null,
                       remainLimit         = Lifelength.Null,
                       remainLimitC        = Lifelength.Null,
                       IDD = Lifelength.Null,
                       IDDC = Lifelength.Null,
                       warranty, repeatInterval = Lifelength.Null;
            string partNumber,
                   description,
                   serialNumber,
                   position,
                   mpdString             = "",
                   mpdNumString          = "",
                   lastPerformanceString = "",
                   type        = getGroupName(item),
                   classString = "",
                   kitRequieredString,
                   remarks,
                   hiddenRemarks,
                   workType        = "",
                   zone            = "",
                   access          = "",
                   expiryDate      = "",
                   condition       = "",
                   conditionRepeat = "",
                   ndtString       = "";
            double manHours,
                   cost,
                   costServiceable = 0,
                   costOverhaul    = 0;

            if (item is Component)
            {
                Component componentItem = (Component)item;
                approx = componentItem.NextPerformanceDate;
                next   = componentItem.NextPerformanceSource;

                if (ShowGroup)
                {
                    remains = componentItem.LLPCategories ? componentItem.LLPRemains : componentItem.Remains;
                }
                else
                {
                    var selectedCategory = componentItem.ChangeLLPCategoryRecords.GetLast()?.ToCategory;
                    if (selectedCategory != null)
                    {
                        var llp = componentItem.LLPData.GetItemByCatagory(selectedCategory);
                        remains = llp?.Remain;
                    }
                }


                if (componentItem.LLPCategories)
                {
                    nextEstimated      = componentItem.NextPerformance?.PerformanceDate;
                    nextEstimatedData  = componentItem.NextPerformance?.PerformanceSource;
                    nextEstimatedDataC = componentItem.NextPerformance?.PerformanceSourceC;
                    remainEstimated    = componentItem.NextPerformance?.Remains;

                    nextLimit      = componentItem.NextPerformance?.NextPerformanceDateNew;
                    nextLimitData  = componentItem.NextPerformance?.NextLimit;
                    nextLimitDataC = componentItem.NextPerformance?.NextLimitC;
                    remainLimit    = componentItem.NextPerformance?.RemainLimit;
                    remainLimitC   = componentItem.NextPerformance?.RemainLimitC;

                    IDD  = componentItem.NextPerformance?.IDD;
                    IDDC = componentItem.NextPerformance?.IDDC;
                }


                ata              = componentItem.Model != null ? componentItem.Model.ATAChapter : componentItem.ATAChapter;
                partNumber       = componentItem.PartNumber;
                description      = componentItem.Model != null ? componentItem.Model.Description : componentItem.Description;
                serialNumber     = componentItem.SerialNumber;
                position         = componentItem.TransferRecords.GetLast().Position.ToUpper();
                maintenanceType  = componentItem.MaintenanceControlProcess;
                transferDate     = componentItem.TransferRecords.GetLast().TransferDate;
                firstPerformance = componentItem.LifeLimit;
                warranty         = componentItem.Warranty;
                classString      = componentItem.GoodsClass != null?componentItem.GoodsClass.ToString() : "";

                kitRequieredString = componentItem.Kits.Count + " kits";
                manHours           = componentItem.ManHours;
                cost            = componentItem.Cost;
                costOverhaul    = componentItem.CostOverhaul;
                costServiceable = componentItem.CostServiceable;
                remarks         = componentItem.Remarks;
                hiddenRemarks   = componentItem.HiddenRemarks;
                expiryDate      = " ";
                expiryRemain    = Lifelength.Null;
                condition       = !firstPerformance.IsNullOrZero() ? (componentItem.Threshold.FirstPerformanceConditionType == ThresholdConditionType.WhicheverFirst
                                        ? "/WF"
                                        : "/WL") : "";
                conditionRepeat = !componentItem.Threshold.RepeatInterval.IsNullOrZero() ? (componentItem.Threshold.RepeatPerformanceConditionType == ThresholdConditionType.WhicheverFirst
                                        ? "/WF"
                                        : "/WL") : "";
            }
            else
            {
                ComponentDirective dd = (ComponentDirective)item;
                if (dd.Threshold.FirstPerformanceSinceNew != null && !dd.Threshold.FirstPerformanceSinceNew.IsNullOrZero())
                {
                    firstPerformance = dd.Threshold.FirstPerformanceSinceNew;
                }

                if (dd.LastPerformance != null)
                {
                    lastPerformanceString = SmartCore.Auxiliary.Convert.GetDateFormat(dd.LastPerformance.RecordDate);
                    lastPerformance       = dd.LastPerformance.OnLifelength;
                    lastPerformanceDate   = dd.LastPerformance.RecordDate;
                }
                if (dd.Threshold.RepeatInterval != null && !dd.Threshold.RepeatInterval.IsNullOrZero())
                {
                    repeatInterval = dd.Threshold.RepeatInterval;
                }
                //GlobalObjects.CasEnvironment.Calculator.GetNextPerformance(dd, out next, out remains, out approx, out cond);
                //GlobalObjects.CasEnvironment.Calculator.GetNextPerformance(dd);
                approx  = dd.NextPerformanceDate;
                next    = dd.NextPerformanceSource;
                remains = dd.Remains;


                nextEstimated      = dd.NextPerformance?.PerformanceDate;
                nextEstimatedData  = dd.NextPerformance?.PerformanceSource;
                nextEstimatedDataC = dd.NextPerformance?.PerformanceSourceC;
                remainEstimated    = dd.NextPerformance?.Remains;

                nextLimit      = dd.NextPerformance?.NextPerformanceDateNew;
                nextLimitData  = dd.NextPerformance?.NextLimit;
                nextLimitDataC = dd.NextPerformance?.NextLimitC;
                remainLimit    = dd.NextPerformance?.RemainLimit;
                remainLimitC   = dd.NextPerformance?.RemainLimitC;


                IDD  = dd.NextPerformance?.IDD;
                IDDC = dd.NextPerformance?.IDDC;

                ata        = dd.ParentComponent.Model != null ? dd.ParentComponent.Model.ATAChapter : dd.ParentComponent.ATAChapter;
                partNumber = "    " + dd.PartNumber;
                var desc = dd.ParentComponent.Model != null
                                        ? dd.ParentComponent.Model.Description
                                        : dd.ParentComponent.Description;

                description     = "    " + desc;
                serialNumber    = "    " + dd.SerialNumber;
                position        = "    " + dd.ParentComponent.TransferRecords.GetLast().Position.ToUpper();
                transferDate    = dd.ParentComponent.TransferRecords.GetLast().TransferDate;
                maintenanceType = dd.ParentComponent.MaintenanceControlProcess;
                warranty        = dd.Threshold.Warranty;
                classString     = dd.ParentComponent.GoodsClass != null?dd.ParentComponent.GoodsClass.ToString() : "";

                kitRequieredString = dd.Kits.Count + " kits";
                manHours           = dd.ManHours;
                cost          = dd.Cost;
                zone          = dd.ZoneArea;
                access        = dd.AccessDirective;
                remarks       = dd.Remarks;
                hiddenRemarks = dd.HiddenRemarks;
                workType      = dd.DirectiveType.ToString();
                ndtString     = dd.NDTType.ShortName;
                condition     = !firstPerformance.IsNullOrZero() ? (dd.Threshold.FirstPerformanceConditionType == ThresholdConditionType.WhicheverFirst
                                        ? "/WF"
                                        : "/WL") : "";
                conditionRepeat = !dd.Threshold.RepeatInterval.IsNullOrZero() ? (dd.Threshold.RepeatPerformanceConditionType == ThresholdConditionType.WhicheverFirst
                                        ? "/WF"
                                        : "/WL") : "";



                if (dd.IsExpiry)
                {
                    expiryDate   = dd.IsExpiry ? (dd.ExpiryDate.HasValue ? SmartCore.Auxiliary.Convert.GetDateFormat(dd.ExpiryDate.Value) : "") : "";
                    expiryRemain = dd.IsExpiry ? new Lifelength((int)(dd.ExpiryDate.Value - DateTime.Today).TotalDays, 0, 0) : Lifelength.Null;
                }

                if (dd.MaintenanceDirective != null)
                {
                    mpdString    = dd.MaintenanceDirective.TaskNumberCheck;
                    mpdNumString = dd.MaintenanceDirective.TaskCardNumber;
                }
            }
            if (ShowGroup)
            {
                subItems.Add(CreateRow(type, type));
            }
            subItems.Add(CreateRow(ata.ToString(), ata));
            subItems.Add(CreateRow(partNumber, partNumber));
            subItems.Add(CreateRow(description, description));
            subItems.Add(CreateRow(workType, workType));
            subItems.Add(CreateRow(serialNumber, serialNumber));
            subItems.Add(CreateRow(mpdString, mpdString));
            subItems.Add(CreateRow(mpdNumString, mpdNumString));
            subItems.Add(CreateRow(position, position));
            subItems.Add(CreateRow(maintenanceType.ShortName, maintenanceType));
            subItems.Add(CreateRow(zone, zone));
            subItems.Add(CreateRow(access, access));
            subItems.Add(CreateRow(transferDate > DateTimeExtend.GetCASMinDateTime()
                                ? SmartCore.Auxiliary.Convert.GetDateFormat(transferDate) : "", transferDate));
            subItems.Add(CreateRow(IDD?.ToString(), IDD));
            subItems.Add(CreateRow(IDDC?.ToString(), IDDC));
            subItems.Add(CreateRow($"{firstPerformance} {condition}", firstPerformance));
            subItems.Add(CreateRow($"{repeatInterval} {conditionRepeat}", repeatInterval));


            subItems.Add(CreateRow(SmartCore.Auxiliary.Convert.GetDateFormat(nextEstimated), nextEstimated));
            subItems.Add(CreateRow(nextEstimatedData?.ToString(), nextEstimatedData));
            subItems.Add(CreateRow(nextEstimatedDataC?.ToString(), nextEstimatedDataC));
            subItems.Add(CreateRow(remainEstimated?.ToString(), remainEstimated));
            subItems.Add(CreateRow(nextLimitData?.Days != null ? SmartCore.Auxiliary.Convert.GetDateFormat(nextLimit) : "", nextLimit));
            subItems.Add(CreateRow(nextLimitData?.ToString(), nextLimitData));
            subItems.Add(CreateRow(nextLimitDataC?.ToString(), nextLimitDataC));
            subItems.Add(CreateRow(remainLimit?.ToString(), remainLimit));
            subItems.Add(CreateRow(remainLimitC?.ToString(), remainLimitC));
            subItems.Add(CreateRow(lastPerformanceString, lastPerformanceDate));
            subItems.Add(CreateRow(lastPerformance?.ToString(), lastPerformance));

            subItems.Add(CreateRow(expiryDate, expiryDate));
            subItems.Add(CreateRow(!expiryRemain.IsNullOrZero() ? $"{expiryRemain?.Days}d" : "", expiryRemain));
            subItems.Add(CreateRow(warranty.ToString(), warranty));
            subItems.Add(CreateRow(classString, classString));
            subItems.Add(CreateRow(kitRequieredString, kitRequieredString));
            subItems.Add(CreateRow(ndtString, ndtString));
            subItems.Add(CreateRow(manHours.ToString(), manHours));
            subItems.Add(CreateRow(cost.ToString(), cost));
            subItems.Add(CreateRow(costOverhaul.ToString(), costOverhaul));
            subItems.Add(CreateRow(costServiceable.ToString(), costServiceable));
            subItems.Add(CreateRow(remarks, remarks));
            subItems.Add(CreateRow(hiddenRemarks, hiddenRemarks));
            subItems.Add(CreateRow(author, author));

            return(subItems);
        }
Exemplo n.º 4
0
        protected override ListViewItem.ListViewSubItem[] GetListViewSubItems(BaseEntityObject item)
        {
            List <ListViewItem.ListViewSubItem> subItems = new List <ListViewItem.ListViewSubItem>();

            //if(item.ItemId == 41043)
            //{

            //}
            if (item is NextPerformance)
            {
                NextPerformance np = (NextPerformance)item;

                double manHours = np.Parent is IEngineeringDirective ? ((IEngineeringDirective)np.Parent).ManHours : 0;
                double cost     = np.Parent is IEngineeringDirective ? ((IEngineeringDirective)np.Parent).Cost : 0;

                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = np.ATAChapter.ToString(), Tag = np.ATAChapter
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = np.Title, Tag = np.Title
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = np.Description, Tag = np.Description
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = np.Type, Tag = np.Type
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = np.KitsToString, Tag = np.Kits.Count
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = np.PerformanceSource.ToString(), Tag = np.PerformanceSource
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = np.Parent.Threshold.RepeatInterval.ToString(), Tag = np.Parent.Threshold.RepeatInterval
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = np.Remains.ToString(), Tag = np.Remains
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = np.WorkType, Tag = np.WorkType
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = np.PerformanceDate == null ? "N/A" : SmartCore.Auxiliary.Convert.GetDateFormat((DateTime)np.PerformanceDate), Tag = np.PerformanceDate
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = manHours.ToString(), Tag = manHours
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = cost.ToString(), Tag = cost
                });
            }
            else if (item is AbstractPerformanceRecord)
            {
                AbstractPerformanceRecord apr = (AbstractPerformanceRecord)item;
                Lifelength remains            = Lifelength.Null;

                double manHours = apr.Parent is IEngineeringDirective ? ((IEngineeringDirective)apr.Parent).ManHours : 0;
                double cost     = apr.Parent is IEngineeringDirective ? ((IEngineeringDirective)apr.Parent).Cost : 0;

                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = apr.ATAChapter.ToString(), Tag = apr.ATAChapter
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = apr.Title, Tag = apr.Title
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = apr.Description, Tag = apr.Description
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = "", Tag = ""
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = apr.KitsToString, Tag = apr.Kits.Count
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = apr.OnLifelength.ToString(), Tag = apr.OnLifelength
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = apr.Parent.Threshold.RepeatInterval.ToString(), Tag = apr.Parent.Threshold.RepeatInterval
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = remains.ToString(), Tag = remains
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = apr.WorkType, Tag = apr.WorkType
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = SmartCore.Auxiliary.Convert.GetDateFormat(apr.RecordDate), Tag = apr.RecordDate
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = manHours.ToString(), Tag = manHours
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = cost.ToString(), Tag = cost
                });
            }
            else if (item is Directive)
            {
                Directive     directive = (Directive)item;
                AtaChapter    ata       = directive.ATAChapter;
                DirectiveType pdType    = directive.DirectiveType;
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = ata.ToString(), Tag = ata
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = directive.Title, Tag = directive.Title
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = directive.Description, Tag = directive.Description
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = pdType.ShortName, Tag = pdType.ShortName
                });

                #region Определение текста для колонки "КИТы"
                subItems.Add(new ListViewItem.ListViewSubItem
                {
                    Text = directive.Kits.Count > 0 ? directive.Kits.Count + " kits" : "",
                    Tag  = directive.Kits.Count
                });
                #endregion

                #region Определение текста для колонки "Первое выполнение"

                ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
                if (directive.Threshold.FirstPerformanceSinceNew != null && !directive.Threshold.FirstPerformanceSinceNew.IsNullOrZero())
                {
                    subItem.Text = "s/n: " + directive.Threshold.FirstPerformanceSinceNew;
                    subItem.Tag  = directive.Threshold.FirstPerformanceSinceNew;
                }
                if (directive.Threshold.FirstPerformanceSinceEffectiveDate != null &&
                    !directive.Threshold.FirstPerformanceSinceEffectiveDate.IsNullOrZero())
                {
                    if (subItem.Text != "")
                    {
                        subItem.Text += " or ";
                    }
                    else
                    {
                        subItem.Text = "";
                        subItem.Tag  = directive.Threshold.FirstPerformanceSinceEffectiveDate;
                    }
                    subItem.Text += "s/e.d: " + directive.Threshold.FirstPerformanceSinceEffectiveDate;
                }

                subItems.Add(subItem);
                #endregion

                #region Определение текста для колонки "повторяющийся интервал"

                subItem = new ListViewItem.ListViewSubItem();
                if (!directive.Threshold.RepeatInterval.IsNullOrZero())
                {
                    subItem.Text = directive.Threshold.RepeatInterval.ToString();
                    subItem.Tag  = directive.Threshold.RepeatInterval;
                }
                else
                {
                    subItem.Text = "";
                    subItem.Tag  = Lifelength.Null;
                }
                subItems.Add(subItem);
                #endregion

                #region Определение текста для колонки "Остаток/Просрочено на сегодня"
                subItems.Add(new ListViewItem.ListViewSubItem
                {
                    Text = directive.Remains.ToString(),
                    Tag  = directive.Remains
                });
                #endregion

                #region Определение текста для колонки "Тип работ"

                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = directive.WorkType.ToString(), Tag = directive.WorkType
                });
                #endregion

                #region Определение текста для колонки "Следующее выполнение"
                subItems.Add(new ListViewItem.ListViewSubItem
                {
                    Text = directive.NextPerformanceDate == null ? "N/A" : SmartCore.Auxiliary.Convert.GetDateFormat((DateTime)directive.NextPerformanceDate),
                    Tag  = directive.NextPerformanceDate
                });
                #endregion

                #region Определение текста для колонки "Человек/Часы"

                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = directive.ManHours.ToString(), Tag = directive.ManHours
                });
                #endregion

                #region Определение текста для колонки "Стоимость"

                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = directive.Cost.ToString(), Tag = directive.Cost
                });
                #endregion
            }
            else if (item is BaseComponent)
            {
                BaseComponent bd  = (BaseComponent)item;
                AtaChapter    ata = bd.ATAChapter;

                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = ata.ToString(), Tag = ata
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = bd.PartNumber, Tag = bd.PartNumber
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = bd.Description, Tag = bd.Description
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = bd.MaintenanceControlProcess.ShortName, Tag = bd.MaintenanceControlProcess.ShortName
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = bd.Kits.Count > 0 ? bd.Kits.Count + " kits" : "", Tag = bd.Kits.Count
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = bd.LifeLimit.ToString(), Tag = bd.LifeLimit
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = "", Tag = Lifelength.Null
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = bd.Remains.ToString(), Tag = bd.Remains
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = ComponentRecordType.Remove.ToString(), Tag = ComponentRecordType.Remove
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = bd.NextPerformanceDate == null ? "N/A" : SmartCore.Auxiliary.Convert.GetDateFormat((DateTime)bd.NextPerformanceDate), Tag = bd.NextPerformanceDate
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = bd.ManHours.ToString(), Tag = bd.ManHours
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = bd.Cost.ToString(), Tag = bd.Cost
                });
            }
            else if (item is Component)
            {
                Component  d   = (Component)item;
                AtaChapter ata = d.ATAChapter;

                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = ata.ToString(), Tag = ata
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = d.PartNumber, Tag = d.PartNumber
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = d.Description, Tag = d.Description
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = d.MaintenanceControlProcess.ShortName, Tag = d.MaintenanceControlProcess.ShortName
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = d.Kits.Count > 0 ? d.Kits.Count + " kits" : "", Tag = d.Kits.Count
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = d.LifeLimit != null ? d.LifeLimit.ToString() : "", Tag = d.LifeLimit
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = "", Tag = Lifelength.Null
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = d.Remains != null ? d.Remains.ToString() : "", Tag = d.Remains
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = ComponentRecordType.Remove.ToString(), Tag = ComponentRecordType.Remove
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = d.NextPerformanceDate == null ? "N/A" : SmartCore.Auxiliary.Convert.GetDateFormat((DateTime)d.NextPerformanceDate), Tag = d.NextPerformanceDate
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = d.ManHours.ToString(), Tag = d.ManHours
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = d.Cost.ToString(), Tag = d.Cost
                });
            }
            else if (item is ComponentDirective)
            {
                ComponentDirective dd  = (ComponentDirective)item;
                AtaChapter         ata = dd.ParentComponent.ATAChapter;

                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = ata != null ? ata.ToString() : "", Tag = ata
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = "", Tag = ""
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = dd.Remarks, Tag = dd.Remarks
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = "", Tag = ""
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = dd.Kits.Count > 0 ? dd.Kits.Count + " kits" : "", Tag = dd.Kits.Count
                });
                #region Определение текста для колонки "Первое выполнение"

                ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
                if (dd.Threshold.FirstPerformanceSinceNew != null && !dd.Threshold.FirstPerformanceSinceNew.IsNullOrZero())
                {
                    subItem.Text = "s/n: " + dd.Threshold.FirstPerformanceSinceNew;
                    subItem.Tag  = dd.Threshold.FirstPerformanceSinceNew;
                }
                subItems.Add(subItem);
                #endregion
                #region Определение текста для колонки "повторяющийся интервал"

                subItem = new ListViewItem.ListViewSubItem();
                if (!dd.Threshold.RepeatInterval.IsNullOrZero())
                {
                    subItem.Text = dd.Threshold.RepeatInterval.ToString();
                    subItem.Tag  = dd.Threshold.RepeatInterval;
                }
                else
                {
                    subItem.Text = "";
                    subItem.Tag  = Lifelength.Null;
                }
                subItems.Add(subItem);
                #endregion
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = dd.Remains.ToString(), Tag = dd.Remains
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = dd.DirectiveType.ToString(), Tag = dd.DirectiveType
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = dd.NextPerformanceDate == null ? "N/A" : SmartCore.Auxiliary.Convert.GetDateFormat((DateTime)dd.NextPerformanceDate), Tag = dd.NextPerformanceDate
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = dd.ManHours.ToString(), Tag = dd.ManHours
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = dd.Cost.ToString(), Tag = dd.Cost
                });
            }
            else if (item is MaintenanceCheck)
            {
                MaintenanceCheck mc = (MaintenanceCheck)item;
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = "", Tag = null
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = "", Tag = ""
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = mc.Name + (mc.Schedule ? " Shedule" : " Unshedule"), Tag = mc.Name
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = mc.Name, Tag = mc.Name
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = mc.Kits.Count > 0 ? mc.Kits.Count + " kits" : "", Tag = mc.Kits.Count
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = mc.Interval.ToString(), Tag = mc.Interval
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = "", Tag = Lifelength.Null
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = mc.Remains.ToString(), Tag = mc.Remains
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = "", Tag = ""
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = mc.NextPerformanceDate == null ? "N/A" : SmartCore.Auxiliary.Convert.GetDateFormat((DateTime)mc.NextPerformanceDate), Tag = mc.NextPerformanceDate
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = mc.ManHours.ToString(), Tag = mc.ManHours
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = mc.Cost.ToString(), Tag = mc.Cost
                });
            }
            else if (item is MaintenanceDirective)
            {
                MaintenanceDirective md  = (MaintenanceDirective)item;
                AtaChapter           ata = md.ATAChapter;
                string type = md.MaintenanceCheck != null ? md.MaintenanceCheck.Name : "MPD";

                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = ata != null ? ata.ToString() : "", Tag = ata
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = md.TaskNumberCheck, Tag = md.TaskNumberCheck
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = md.Description, Tag = md.Description,
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = type, Tag = type,
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = md.Kits.Count > 0 ? md.Kits.Count + " kits" : "", Tag = md.Kits.Count
                });
                #region Определение текста для колонки "Первое выполнение"

                ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
                if (md.Threshold.FirstPerformanceSinceNew != null && !md.Threshold.FirstPerformanceSinceNew.IsNullOrZero())
                {
                    subItem.Text = "s/n: " + md.Threshold.FirstPerformanceSinceNew;
                    subItem.Tag  = md.Threshold.FirstPerformanceSinceNew;
                }
                if (md.Threshold.FirstPerformanceSinceEffectiveDate != null &&
                    !md.Threshold.FirstPerformanceSinceEffectiveDate.IsNullOrZero())
                {
                    if (subItem.Text != "")
                    {
                        subItem.Text += " or ";
                    }
                    else
                    {
                        subItem.Text = "";
                        subItem.Tag  = md.Threshold.FirstPerformanceSinceEffectiveDate;
                    }
                    subItem.Text += "s/e.d: " + md.Threshold.FirstPerformanceSinceEffectiveDate;
                }

                subItems.Add(subItem);
                #endregion
                #region Определение текста для колонки "повторяющийся интервал"

                subItem = new ListViewItem.ListViewSubItem();
                if (!md.Threshold.RepeatInterval.IsNullOrZero())
                {
                    subItem.Text = md.Threshold.RepeatInterval.ToString();
                    subItem.Tag  = md.Threshold.RepeatInterval;
                }
                else
                {
                    subItem.Text = "";
                    subItem.Tag  = Lifelength.Null;
                }
                subItems.Add(subItem);
                #endregion
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = md.Remains.ToString(), Tag = md.Remains
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = md.WorkType.ToString(), Tag = md.WorkType
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = md.NextPerformanceDate == null ? "N/A" : SmartCore.Auxiliary.Convert.GetDateFormat((DateTime)md.NextPerformanceDate), Tag = md.NextPerformanceDate
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = md.ManHours.ToString(), Tag = md.ManHours
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = md.Cost.ToString(), Tag = md.Cost
                });
            }
            else if (item is NonRoutineJob)
            {
                NonRoutineJob job = (NonRoutineJob)item;
                AtaChapter    ata = job.ATAChapter;
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = ata != null ? ata.ToString() : "", Tag = ata
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = "", Tag = ""
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = job.Description, Tag = job.Description
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = "NRC", Tag = "NRC"
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = job.Kits.Count > 0 ? job.Kits.Count + " kits" : "", Tag = job.Kits.Count
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = "", Tag = Lifelength.Null
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = "", Tag = Lifelength.Null
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = "", Tag = Lifelength.Null
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = "", Tag = ""
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = "", Tag = DateTimeExtend.GetCASMinDateTime()
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = job.ManHours.ToString(), Tag = job.ManHours
                });
                subItems.Add(new ListViewItem.ListViewSubItem {
                    Text = job.Cost.ToString(), Tag = job.Cost
                });
            }
            else
            {
                throw new ArgumentOutOfRangeException($"1135: Takes an argument has no known type {item.GetType()}");
            }

            return(subItems.ToArray());
        }
Exemplo n.º 5
0
        /// <summary>
        /// Добавляется элемент в таблицу данных
        /// </summary>
        /// <param name="destinationDataSet">Таблица, в которую добавляется элемент</param>
        private void AddBaseDetailToDataset(AircraftTechicalConditionDataSet destinationDataSet)
        {
            if (_reportedAircraft == null)
            {
                return;
            }

            int engineNum = 1;

            foreach (BaseComponent baseDetail in _aircraftBaseDetails.Where(bd => bd.BaseComponentType == BaseComponentType.Engine ||
                                                                            bd.BaseComponentType == BaseComponentType.Apu))
            {
                if (baseDetail.BaseComponentType == BaseComponentType.Frame)
                {
                    continue;
                }

                string position = "";
                if (baseDetail.BaseComponentType == BaseComponentType.Engine)
                {
                    position = engineNum.ToString();
                    engineNum++;
                }
                else if (baseDetail.BaseComponentType == BaseComponentType.Apu)
                {
                    position = "ВСУ";
                }
                Lifelength currentDetailSource =
                    GlobalObjects.CasEnvironment.Calculator.GetCurrentFlightLifelength(baseDetail);

                string status        = baseDetail.Serviceable ? "Serviceable" : "Unserviceable";
                string sinceNewHours = currentDetailSource.Hours != null?currentDetailSource.Hours.ToString() : "";

                string sinceNewCycles = currentDetailSource.Cycles != null?currentDetailSource.Cycles.ToString() : "";

                string sinceNewDays = currentDetailSource.Days != null?currentDetailSource.Days.ToString() : "";

                Lifelength lifeLimit      = baseDetail.LifeLimit;
                string     lifeLimitHours = lifeLimit.Hours != null?lifeLimit.Hours.ToString() : "";

                string lifeLimitCycles = lifeLimit.Cycles != null?lifeLimit.Cycles.ToString() : "";

                string lifeLimitDays = lifeLimit.Days != null?lifeLimit.Days.ToString() : "";

                Lifelength remain = Lifelength.Null;
                if (!lifeLimit.IsNullOrZero())
                {
                    remain = new Lifelength(lifeLimit);
                    remain.Substract(currentDetailSource);
                    remain.Resemble(lifeLimit);
                }
                string remainHours = remain.Hours != null?remain.Hours.ToString() : "";

                string remainCycles = remain.Cycles != null?remain.Cycles.ToString() : "";

                string remainDays = remain.Days != null?remain.Days.ToString() : "";

                Lifelength betweenOverhaul = Lifelength.Null, lastCompliance = Lifelength.Null;
                DateTime   lastOverhaulDate = DateTime.MinValue;

                string lastOverhaulDateString = "", lastOverhaulHours = "", lastOverhaulCycles = "";
                string remainOverhaulDays = "", remainOverhaulHours = "", remainOverhaulCycles = "";
                string type = "";

                if (baseDetail.BaseComponentType == BaseComponentType.LandingGear)
                {
                    type = "Part C: Landing Gears";
                }
                if (baseDetail.BaseComponentType == BaseComponentType.Engine)
                {
                    type = "Part B: Engines";
                }
                if (baseDetail.BaseComponentType == BaseComponentType.Apu)
                {
                    type = "Part D: Auxiliary Power Unit ";
                }

                #region поиск последнего ремонта и расчет времени, прошедшего с него
                //поиск директив деталей
                List <ComponentDirective> directives = GlobalObjects.ComponentCore.GetComponentDirectives(baseDetail, true);
                //поиск директивы ремонта
                List <ComponentDirective> overhauls =
                    directives.Where(d => d.DirectiveType == ComponentRecordType.Overhaul).ToList();
                //поиск последнего ремонта
                if (overhauls.Count != 0)
                {
                    ComponentDirective lastOverhaul = null;
                    foreach (ComponentDirective d in overhauls)
                    {
                        if (d.LastPerformance == null || d.LastPerformance.RecordDate <= lastOverhaulDate)
                        {
                            continue;
                        }

                        lastOverhaulDate = d.LastPerformance.RecordDate;
                        lastOverhaul     = d;
                    }

                    if (lastOverhaul != null)
                    {
                        betweenOverhaul        = lastOverhaul.Threshold.RepeatInterval;
                        lastOverhaulDateString = lastOverhaulDate.ToString(new GlobalTermsProvider()["DateFormat"].ToString());
                        lastOverhaulHours      = lastOverhaul.LastPerformance.OnLifelength.Hours != null
                                                ? lastOverhaul.LastPerformance.OnLifelength.Hours.ToString()
                                                : "";

                        lastOverhaulCycles = lastOverhaul.LastPerformance.OnLifelength.Cycles != null
                                                ? lastOverhaul.LastPerformance.OnLifelength.Cycles.ToString()
                                                : "";

                        if (lastOverhaul.NextPerformance != null)
                        {
                            NextPerformance np = lastOverhaul.NextPerformance;
                            remainOverhaulHours = np.Remains.Hours != null?np.Remains.Hours.ToString() : "";

                            remainOverhaulCycles = np.Remains.Cycles != null?np.Remains.Cycles.ToString() : "";

                            remainOverhaulDays = np.Remains.Days != null?np.Remains.Days.ToString() : "";
                        }

                        GlobalObjects.PerformanceCalculator.GetNextPerformance(lastOverhaul);
                        if (lastOverhaul.NextPerformanceDate != null)
                        {
                            remainOverhaulHours = lastOverhaul.Remains.Hours != null?lastOverhaul.Remains.Hours.ToString() : "";

                            remainOverhaulCycles = lastOverhaul.Remains.Cycles != null?lastOverhaul.Remains.Cycles.ToString() : "";

                            remainOverhaulDays = lastOverhaul.Remains.Days != null?lastOverhaul.Remains.Days.ToString() : "";
                        }
                    }
                    else
                    {
                        betweenOverhaul = overhauls[0].Threshold.RepeatInterval;
                    }
                }

                ComponentDirective lastPerformance = directives.Where(d => d.LastPerformance != null).
                                                     OrderBy(d => d.LastPerformance.RecordDate).LastOrDefault();
                if (lastPerformance != null)
                {
                    lastCompliance.Add(currentDetailSource);
                    lastCompliance.Substract(lastPerformance.LastPerformance.OnLifelength);
                }
                #endregion

                destinationDataSet.BaseDetailTable.AddBaseDetailTableRow(baseDetail.PartNumber,
                                                                         baseDetail.SerialNumber,
                                                                         baseDetail.Model != null ? baseDetail.Model.ToString() : "",
                                                                         type,
                                                                         baseDetail.GetParentAircraftRegNumber(),
                                                                         position,
                                                                         status,
                                                                         lifeLimitHours,
                                                                         lifeLimitCycles,
                                                                         lifeLimitDays,
                                                                         sinceNewHours,
                                                                         sinceNewCycles,
                                                                         sinceNewDays,
                                                                         remainCycles,
                                                                         remainHours,
                                                                         remainDays,
                                                                         lastOverhaulDateString,
                                                                         lastOverhaulHours,
                                                                         lastOverhaulCycles,
                                                                         betweenOverhaul.Days != null ? betweenOverhaul.Days.ToString() : "",
                                                                         betweenOverhaul.Hours != null ? betweenOverhaul.Hours.ToString() : "",
                                                                         betweenOverhaul.Cycles != null ? betweenOverhaul.Hours.ToString() : "",
                                                                         remainOverhaulDays,
                                                                         remainOverhaulHours,
                                                                         remainOverhaulCycles,
                                                                         lastCompliance.Days != null ? lastCompliance.Days.ToString() : "",
                                                                         lastCompliance.Hours != null ? lastCompliance.Hours.ToString() : "",
                                                                         lastCompliance.Cycles != null ? lastCompliance.Hours.ToString() : "",
                                                                         baseDetail.ManufactureDate.ToString("dd.MM.yyyy"));
            }
        }
        private void ButtonAddClick(object sender, EventArgs e)
        {
            if (listViewTasksForSelect.SelectedItems.Count == 0)
            {
                return;
            }

            if (_maintenanceDirective.IsFirst == null)
            {
                _maintenanceDirective.NormalizeItemRelations();
                comboBoxRelationType.SelectedValue = ItemRelationHelper.ConvertBLItemRelationToUIITem(_maintenanceDirective.WorkItemsRelationType, false);
            }

            //коллекция элементов которые нужно добавить в список, содержащий все связные задачи
            var itemsToInsert = new CommonCollection <BaseEntityObject>();
            //Список выбранных задач по компонентам для привязки
            var selectedDirectives = listViewTasksForSelect.SelectedItems.OfType <ComponentDirective>().ToList();
            //Коллекция выбранных компонентов для привязки
            var selectedComponents = new ComponentCollection(listViewTasksForSelect.SelectedItems.OfType <Component>());

            if (selectedComponents.Count == 0 && selectedDirectives.Count == 0)
            {
                return;
            }
            //список уже призязанных задач по компонетам
            var bindedDirectives = listViewBindedTasks.SelectedItems.OfType <ComponentDirective>().ToList();
            //Объединенный список выбранных и привязанных компонентов
            var concatenatedDirectives = selectedDirectives.Concat(bindedDirectives);

            foreach (ComponentDirective dd in concatenatedDirectives)
            {
                if (concatenatedDirectives.Count(d => d.ComponentId == dd.ComponentId) > 1)
                {
                    //проверка, не выбраны ли 2 или более задач по одному компоненту для привязки
                    //т.к. MPD Item может быть привязан только к одной задаче каждого выбранного компонента
                    string parentComponent;
                    if (dd.ParentComponent != null)
                    {
                        parentComponent = dd.ParentComponent.SerialNumber;
                    }
                    else
                    {
                        parentComponent = "Component ID: " + dd.ComponentId;
                    }

                    MessageBox.Show("the MPD Item can not be bound to two or more tasks of a one component:" +
                                    "\n" + parentComponent,
                                    (string)new GlobalTermsProvider()["SystemName"],
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                try
                {
                    var singleItemRelation = dd.ItemRelations.SingleOrDefault();
                    if (singleItemRelation != null &&
                        !CheckThatItemHaveRelationsOnlyWithProvidedItem(dd.IsFirst.HasValue && dd.IsFirst.Value,
                                                                        singleItemRelation, _maintenanceDirective.ItemId,
                                                                        SmartCoreType.MaintenanceDirective.ItemId))
                    {
                        //Проверка не имеет ли выбранная задача по компоненту привязки к другой задаче
                        string parentComponent;
                        if (dd.ParentComponent != null)
                        {
                            parentComponent = dd.ParentComponent.SerialNumber;
                        }
                        else
                        {
                            parentComponent = "Component ID: " + dd.ComponentId;
                        }

                        MessageBox.Show("You can not select a task: " +
                                        "\n" + parentComponent + " " + dd.DirectiveType +
                                        "\n" + "because task already has a binding",
                                        (string)new GlobalTermsProvider()["SystemName"],
                                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }
                catch (InvalidOperationException)
                {
                    ItemRelationHelper.ShowDialogIfItemLinksCountMoreThanOne($"Component {dd.PartNumber}", dd.ItemRelations.Count);
                }
                catch (Exception ex)
                {
                    Program.Provider.Logger.Log(ex);
                }
            }
            //Удаление из коллекции выбранных компонентов тех компонентов,
            //задачи по которым содержатся в коллекции selectedDirectives
            foreach (ComponentDirective directive in selectedDirectives)
            {
                selectedComponents.RemoveById(directive.ComponentId);
            }
            //Производится привязка выбранных задач по компонентам к выполнению данного MPD
            foreach (ComponentDirective dd in selectedDirectives.Where(d => d.ItemRelations.Count == 0))
            {
                try
                {
                    //TODO:(Evgenii Babak) проверить использования свойств
                    dd.MPDTaskType   = _maintenanceDirective.WorkType;
                    dd.FaaFormFile   = _maintenanceDirective.TaskCardNumberFile;
                    dd.FaaFormFileId = _maintenanceDirective.TaskCardNumberFile != null
                                                                                        ? _maintenanceDirective.TaskCardNumberFile.ItemId
                                                                                        : -1;

                    AddComponentAndDirectiveToBindedItemsCollections(dd.ParentComponent, dd, itemsToInsert, _bindedItems, _newBindedItems);
                    //Удаление задачи по компоненту из элемента управления содержащего список всех задач
                    listViewTasksForSelect.RemoveItem(dd);
                }
                catch (Exception ex)
                {
                    Program.Provider.Logger.Log("Error while save bind task record", ex);
                }
            }

            //Производится привязка выбранных компонентов к выполнению данного MPD
            //В результате предыдущих манипуляций в коллекции выбранных компонентов
            //должны остаться компоненты у которых либо нет задач, либо не одна не была выбрана
            foreach (Component selectedComponent in selectedComponents)
            {
                if (selectedComponent.ComponentDirectives.Count == 0)
                {
                    //Выбранный компонент не имеет задач.
                    //Для привязки необходимо создать задачу
                    if (MessageBox.Show("Component:" +
                                        "\n" + selectedComponent +
                                        "\n" + "has no directives!" +
                                        "\n" +
                                        "\n" + "Create and save directive for this MPD Item?",
                                        (string)new GlobalTermsProvider()["SystemName"],
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation)
                        != DialogResult.Yes)
                    {
                        continue;
                    }
                }
                else if (selectedComponent.ComponentDirectives.All(dd => dd.ItemRelations.Any(i => !CheckThatItemHaveRelationsOnlyWithProvidedItem(dd.IsFirst.HasValue && dd.IsFirst.Value,
                                                                                                                                                   i,
                                                                                                                                                   _maintenanceDirective.ItemId,
                                                                                                                                                   SmartCoreType.MaintenanceDirective.ItemId))))

                {
                    //Выбранный компонент имеет задачи
                    //Но все они привязаны к другим задачам
                    if (MessageBox.Show("Component:" +
                                        "\n" + selectedComponent +
                                        "\n" + "has directives, but they are bound to other tasks" +
                                        "\n" +
                                        "\n" + "Create and save directive for this MPD Item?",
                                        (string)new GlobalTermsProvider()["SystemName"],
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation)
                        != DialogResult.Yes)
                    {
                        continue;
                    }
                }
                else if (selectedComponent.ComponentDirectives.Count > 0)
                {
                    //Выбранный компонент имеет задачи
                    //Но ни одна из его задач не была выбрана для привязки
                    //Необходимо задать вопрос: создать ли овую задачу для привязки
                    //или пользователь должен быбрать задачу для привязки сам из имеющихся задач по компоненту
                    if (MessageBox.Show("Component:" +
                                        "\n" + selectedComponent +
                                        "\n" + "has a tasks, but none of them is selected for binding!" +
                                        "\n" +
                                        "\n" + "Create and save directive for this MPD Item, or You choose task to bind yourself" +
                                        "\n" +
                                        "\n" + "Yes - Create and Save directive" +
                                        "\n" + "No - You choose task to bind yourself",
                                        (string)new GlobalTermsProvider()["SystemName"],
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation)
                        != DialogResult.Yes)
                    {
                        continue;
                    }
                }

                try
                {
                    var neComponentDirective = new ComponentDirective();

                    neComponentDirective.DirectiveType = (ComponentRecordType)ComponentRecordType.Items.GetByShortName(_maintenanceDirective.WorkType.ShortName);

                    neComponentDirective.ManHours = _maintenanceDirective.ManHours;
                    neComponentDirective.Cost     = _maintenanceDirective.Cost;
                    neComponentDirective.Kits.Clear();
                    neComponentDirective.Kits.AddRange(_maintenanceDirective.Kits.ToArray());
                    neComponentDirective.Remarks       = _maintenanceDirective.Remarks;
                    neComponentDirective.HiddenRemarks = _maintenanceDirective.HiddenRemarks;
                    neComponentDirective.MPDTaskType   = _maintenanceDirective.WorkType;
                    neComponentDirective.FaaFormFile   = _maintenanceDirective.TaskCardNumberFile;
                    neComponentDirective.FaaFormFileId = _maintenanceDirective.TaskCardNumberFile != null
                                                                                                                   ? _maintenanceDirective.TaskCardNumberFile.ItemId
                                                                                                                   : -1;
                    neComponentDirective.ComponentId     = selectedComponent.ItemId;
                    neComponentDirective.ParentComponent = selectedComponent;

                    MaintenanceDirectiveThreshold mdt = _maintenanceDirective.Threshold;
                    ComponentDirectiveThreshold   ddt = neComponentDirective.Threshold;

                    ddt.FirstPerformanceSinceNew      = mdt.FirstPerformanceSinceNew;
                    ddt.FirstNotification             = mdt.FirstNotification;
                    ddt.RepeatInterval                = mdt.RepeatInterval;
                    ddt.RepeatNotification            = mdt.RepeatNotification;
                    ddt.FirstPerformanceConditionType = mdt.FirstPerformanceConditionType;


                    AddComponentAndDirectiveToBindedItemsCollections(selectedComponent, neComponentDirective, itemsToInsert, _bindedItems, _newBindedItems);
                }
                catch (Exception ex)
                {
                    Program.Provider.Logger.Log("Error while save bind task record", ex);
                }
            }

            listViewBindedTasks.InsertItems(itemsToInsert);
        }
        /// <summary>
        /// Добавляется элемент в таблицу данных
        /// </summary>
        /// <param name="destinationDataSet">Таблица, в которую добавляется элемент</param>
        private void AddBaseDetailToDataset(DirectivesListDataSet destinationDataSet)
        {
            if (_reportedAircraft != null)
            {
                return;
            }
            var parentAircaft            = GlobalObjects.AircraftsCore.GetAircraftById(_reportedBaseComponent.ParentAircraftId);
            var parentStore              = GlobalObjects.StoreCore.GetStoreById(_reportedBaseComponent.ParentStoreId);
            var reportAircraftLifeLenght =
                GlobalObjects.CasEnvironment.Calculator.GetCurrentFlightLifelength(_reportedBaseComponent);
            var regNumber = _reportedBaseComponent.GetParentAircraftRegNumber();
            var location  = !string.IsNullOrEmpty(regNumber)
                                  ? regNumber
                                                                  : parentStore != null ? parentStore.Name : "";
            var manufactureDate = _reportedBaseComponent.ManufactureDate.ToString(new GlobalTermsProvider()["DateFormat"].ToString());
            var deliveryDate    = _reportedBaseComponent.DeliveryDate.ToString(new GlobalTermsProvider()["DateFormat"].ToString());
            var status          = _reportedBaseComponent.Serviceable ? "Serviceable" : "Unserviceable";
            var sinceNewHours   = reportAircraftLifeLenght.Hours != null ? (int)reportAircraftLifeLenght.Hours : 0;
            var sinceNewCycles  = reportAircraftLifeLenght.Cycles != null ? (int)reportAircraftLifeLenght.Cycles : 0;
            var sinceNewDays    = reportAircraftLifeLenght.Days != null?reportAircraftLifeLenght.Days.ToString() : "";

            var lifeLimit      = _reportedBaseComponent.LifeLimit;
            var lifeLimitHours = lifeLimit.Hours != null?lifeLimit.Hours.ToString() : "";

            var lifeLimitCycles = lifeLimit.Cycles != null?lifeLimit.Cycles.ToString() : "";

            var lifeLimitDays = lifeLimit.Days != null?lifeLimit.Days.ToString() : "";

            var remain = Lifelength.Null;

            if (!lifeLimit.IsNullOrZero())
            {
                remain.Add(lifeLimit);
                remain.Substract(reportAircraftLifeLenght);
                remain.Resemble(lifeLimit);
            }
            var remainHours = remain.Hours != null?remain.Hours.ToString() : "";

            var remainCycles = remain.Cycles != null?remain.Cycles.ToString() : "";

            var remainDays = remain.Days != null?remain.Days.ToString() : "";

            var lastTransferRecord = _reportedBaseComponent.TransferRecords.GetLast();
            var installationDate   = lastTransferRecord.TransferDate;
            var onInstall          = lastTransferRecord.OnLifelength;
            var onInstallDate      = installationDate.ToString(new GlobalTermsProvider()["DateFormat"].ToString());
            var onInstallHours     = onInstall.Hours != null?onInstall.Hours.ToString() : "";

            var onInstallCycles = onInstall.Cycles != null?onInstall.Cycles.ToString() : "";

            var onInstallDays = onInstall.Days != null?onInstall.Days.ToString() : "";

            var sinceInstall = new Lifelength(reportAircraftLifeLenght);

            sinceInstall.Substract(onInstall);
            var sinceInstallHours = sinceInstall.Hours != null?sinceInstall.Hours.ToString() : "";

            var sinceInstallCycles = sinceInstall.Cycles != null?sinceInstall.Cycles.ToString() : "";

            var sinceInstallDays = sinceInstall.Days != null?sinceInstall.Days.ToString() : "";

            var warranty       = _reportedBaseComponent.Warranty;
            var warrantyRemain = new Lifelength(warranty);

            warrantyRemain.Substract(reportAircraftLifeLenght);
            warrantyRemain.Resemble(warranty);
            var warrantyHours = warranty.Hours != null?warranty.Hours.ToString() : "";

            var warrantyCycles = warranty.Cycles != null?warranty.Cycles.ToString() : "";

            var warrantyDays = warranty.Days != null?warranty.Days.ToString() : "";

            var warrantyRemainHours = warrantyRemain.Hours != null?warrantyRemain.Hours.ToString() : "";

            var warrantyRemainCycles = warrantyRemain.Cycles != null?warrantyRemain.Cycles.ToString() : "";

            var warrantyRemainDays = warrantyRemain.Days != null?warrantyRemain.Days.ToString() : "";

            var aircraftOnInstall = Lifelength.Null;

            if (parentAircaft != null)
            {
                var aircraftFrame = GlobalObjects.ComponentCore.GetBaseComponentById(parentAircaft.AircraftFrameId);
                aircraftOnInstall = GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnEndOfDay(aircraftFrame, installationDate);
                GlobalObjects.CasEnvironment.Calculator.GetCurrentFlightLifelength(parentAircaft);
            }
            var aircraftOnInstallHours = aircraftOnInstall.Hours != null?aircraftOnInstall.Hours.ToString() : "";

            var aircraftOnInstallCycles = aircraftOnInstall.Cycles != null?aircraftOnInstall.Cycles.ToString() : "";

            var aircraftOnInstallDays = aircraftOnInstall.Days != null?aircraftOnInstall.Days.ToString() : "";


            var sinceOverhaul          = Lifelength.Null;
            var lastOverhaulDate       = DateTime.MinValue;
            var lastOverhaulDateString = "";

            #region поиск последнего ремонта и расчет времени, прошедшего с него
            //поиск директив деталей
            var directives = GlobalObjects.ComponentCore.GetComponentDirectives(_reportedBaseComponent, true);
            //поиск директивы ремонта
            var overhauls =
                directives.Where(d => d.DirectiveType == ComponentRecordType.Overhaul).ToList();
            //поиск последнего ремонта
            ComponentDirective lastOverhaul = null;
            foreach (var d in overhauls)
            {
                if (d.LastPerformance == null || d.LastPerformance.RecordDate <= lastOverhaulDate)
                {
                    continue;
                }

                lastOverhaulDate = d.LastPerformance.RecordDate;
                lastOverhaul     = d;
            }

            if (lastOverhaul != null)
            {
                sinceOverhaul.Add(reportAircraftLifeLenght);
                sinceOverhaul.Substract(lastOverhaul.LastPerformance.OnLifelength);
                lastOverhaulDateString = lastOverhaul.LastPerformance.RecordDate.ToString(new GlobalTermsProvider()["DateFormat"].ToString());
            }

            #endregion

            destinationDataSet.BaseDetailTable.AddBaseDetailTableRow(_reportedBaseComponent.ATAChapter.ToString(),
                                                                     _reportedBaseComponent.AvionicsInventory.ToString(),
                                                                     _reportedBaseComponent.PartNumber,
                                                                     _reportedBaseComponent.SerialNumber,
                                                                     _reportedBaseComponent.Model != null ? _reportedBaseComponent.Model.ToString() : "",
                                                                     _reportedBaseComponent.BaseComponentType.ToString(),
                                                                     location,
                                                                     lastTransferRecord.Position,
                                                                     _reportedBaseComponent.Manufacturer,
                                                                     manufactureDate,
                                                                     deliveryDate,
                                                                     _reportedBaseComponent.MPDItem,
                                                                     _reportedBaseComponent.Suppliers != null
                                                                        ? _reportedBaseComponent.Suppliers.ToString()
                                                                        : "",
                                                                     status,
                                                                     _reportedBaseComponent.Cost,
                                                                     _reportedBaseComponent.CostOverhaul,
                                                                     _reportedBaseComponent.CostServiceable,
                                                                     lifeLimitHours,
                                                                     lifeLimitCycles,
                                                                     lifeLimitDays,
                                                                     sinceNewHours,
                                                                     sinceNewCycles,
                                                                     sinceNewDays,
                                                                     remainCycles,
                                                                     remainHours,
                                                                     remainDays,
                                                                     onInstallDate,
                                                                     onInstallHours,
                                                                     onInstallCycles,
                                                                     onInstallDays,
                                                                     sinceInstallHours,
                                                                     sinceInstallCycles,
                                                                     sinceInstallDays,
                                                                     warrantyHours,
                                                                     warrantyCycles,
                                                                     warrantyDays,
                                                                     warrantyRemainHours,
                                                                     warrantyRemainCycles,
                                                                     warrantyRemainDays,
                                                                     aircraftOnInstallHours,
                                                                     aircraftOnInstallCycles,
                                                                     aircraftOnInstallDays,
                                                                     lastOverhaulDateString,
                                                                     sinceOverhaul.Hours ?? 0,
                                                                     sinceOverhaul.Cycles ?? 0);

            int    averageUtilizationHours;
            int    averageUtilizationCycles;
            string averageUtilizationType;
            if (_forecastData == null)
            {
                AverageUtilization au;
                if (parentAircaft != null)
                {
                    var aircraftFrame = GlobalObjects.ComponentCore.GetBaseComponentById(_reportedAircraft.AircraftFrameId);
                    au = GlobalObjects.AverageUtilizationCore.GetAverageUtillization(aircraftFrame);
                }
                else
                {
                    au = _reportedBaseComponent.AverageUtilization;
                }

                averageUtilizationHours  = (int)au.Hours;
                averageUtilizationCycles = (int)au.Cycles;
                averageUtilizationType   = au.SelectedInterval == UtilizationInterval.Dayly ? "Day" : "Month";
            }
            else
            {
                averageUtilizationHours  = (int)_forecastData.AverageUtilization.Hours;
                averageUtilizationCycles = (int)_forecastData.AverageUtilization.Cycles;
                averageUtilizationType   =
                    _forecastData.AverageUtilization.SelectedInterval == UtilizationInterval.Dayly ? "Day" : "Month";
            }
            destinationDataSet.AircraftDataTable.AddAircraftDataTableRow("",
                                                                         manufactureDate,
                                                                         reportAircraftLifeLenght.ToHoursMinutesFormat(""),
                                                                         reportAircraftLifeLenght.Cycles != null && reportAircraftLifeLenght.Cycles != 0
                                                                            ? reportAircraftLifeLenght.Cycles.ToString()
                                                                            : "",
                                                                         "", "", "", "",
                                                                         averageUtilizationHours, averageUtilizationCycles, averageUtilizationType);
        }
        /// <summary>
        /// Выполняет группировку элементов
        /// </summary>
        //protected override void SetGroupsToItems(int columnIndex)
        //      {
        //          itemsListView.Groups.Clear();
        //          foreach (var item in ListViewItemList)
        //          {
        //		var temp = ListViewGroupHelper.GetGroupString(item.Tag);

        //		itemsListView.Groups.Add(temp, temp);
        //		item.Group = itemsListView.Groups[temp];
        //	}
        //      }
        #endregion

        #region protected override ListViewItem.ListViewSubItem[] GetListViewSubItems(BaseSmartCoreObject item)

        protected override List <CustomCell> GetListViewSubItems(BaseEntityObject item)
        {
            var subItems = new List <CustomCell>();

            //if(item.ItemId == 41043)
            //{

            //}
            if (item is NextPerformance)
            {
                NextPerformance np = (NextPerformance)item;

                double manHours = np.Parent is IEngineeringDirective ? ((IEngineeringDirective)np.Parent).ManHours : 0;
                double cost     = np.Parent is IEngineeringDirective ? ((IEngineeringDirective)np.Parent).Cost : 0;
                var    author   = GlobalObjects.CasEnvironment.GetCorrector(item);

                subItems.Add(CreateRow(np.ATAChapter.ToString(), np.ATAChapter));
                subItems.Add(CreateRow(np.Title, np.Title));
                subItems.Add(CreateRow(np.Description, np.Description));
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = np.KitsToString, Tag = np.Kits.Count });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = np.PerformanceSource.ToString(), Tag = np.PerformanceSource });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = np.Parent.Threshold.RepeatInterval.ToString(), Tag = np.Parent.Threshold.RepeatInterval });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = np.Remains.ToString(), Tag = np.Remains });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = np.WorkType, Tag = np.WorkType });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = np.PerformanceDate == null ? "N/A" : SmartCore.Auxiliary.Convert.GetDateFormat((DateTime)np.PerformanceDate), Tag = np.PerformanceDate });
                subItems.Add(CreateRow(manHours.ToString(), manHours));
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = np.Parent.Cost.ToString(), Tag = np.Parent.Cost });
                subItems.Add(CreateRow(author, author));
            }
            else if (item is AbstractPerformanceRecord)
            {
                //DirectiveRecord directiveRecord = (DirectiveRecord)item;
                AbstractPerformanceRecord apr = (AbstractPerformanceRecord)item;
                Lifelength remains            = Lifelength.Null;

                double manHours = apr.Parent is IEngineeringDirective ? ((IEngineeringDirective)apr.Parent).ManHours : 0;
                double cost     = apr.Parent is IEngineeringDirective ? ((IEngineeringDirective)apr.Parent).Cost : 0;

                subItems.Add(CreateRow(apr.ATAChapter.ToString(), apr.ATAChapter));
                subItems.Add(CreateRow(apr.Title, apr.Title));
                subItems.Add(CreateRow(apr.Description, apr.Description));
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = apr.KitsToString, Tag = apr.Kits.Count });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = apr.OnLifelength.ToString(), Tag = apr.OnLifelength });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = apr.Parent.Threshold.RepeatInterval.ToString(), Tag = apr.Parent.Threshold.RepeatInterval });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = remains.ToString(), Tag = remains });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = apr.WorkType, Tag = apr.WorkType });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = SmartCore.Auxiliary.Convert.GetDateFormat(apr.RecordDate), Tag = apr.RecordDate });
                subItems.Add(CreateRow(manHours.ToString(), manHours));
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = apr.Parent.Cost.ToString(), Tag = apr.Parent.Cost });
            }
            else if (item is Directive)
            {
                Directive directive = (Directive)item;

                AtaChapter ata = directive.ATAChapter;
                subItems.Add(CreateRow(ata.ToString(), Tag = ata));
                subItems.Add(CreateRow(directive.Title, directive.Title));
                subItems.Add(CreateRow(directive.Description, directive.Description));

                #region Определение текста для колонки "КИТы"
                //subItems.Add(new ListViewItem.ListViewSubItem
                //{
                //    Text = directive.Kits.Count > 0 ? directive.Kits.Count + " kits" : "",
                //    Tag = directive.Kits.Count
                //});
                #endregion

                #region Определение текста для колонки "Первое выполнение"

                //ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
                //if (directive.Threshold.FirstPerformanceSinceNew != null && !directive.Threshold.FirstPerformanceSinceNew.IsNullOrZero())
                //{
                //    subItem.Text = "s/n: " + directive.Threshold.FirstPerformanceSinceNew;
                //    subItem.Tag = directive.Threshold.FirstPerformanceSinceNew;
                //}
                //if (directive.Threshold.FirstPerformanceSinceEffectiveDate != null &&
                //    !directive.Threshold.FirstPerformanceSinceEffectiveDate.IsNullOrZero())
                //{
                //    if (subItem.Text != "") subItem.Text += " or ";
                //    else
                //    {
                //        subItem.Text = "";
                //        subItem.Tag = directive.Threshold.FirstPerformanceSinceEffectiveDate;
                //    }
                //    subItem.Text += "s/e.d: " + directive.Threshold.FirstPerformanceSinceEffectiveDate;
                //}

                //subItems.Add(subItem);
                #endregion

                #region Определение текста для колонки "повторяющийся интервал"

                //subItem = new ListViewItem.ListViewSubItem();
                //if (!directive.Threshold.RepeatInterval.IsNullOrZero())
                //{
                //    subItem.Text = directive.Threshold.RepeatInterval.ToString();
                //    subItem.Tag = directive.Threshold.RepeatInterval;
                //}
                //else
                //{
                //    subItem.Text = "";
                //    subItem.Tag = Lifelength.Null;
                //}
                //subItems.Add(subItem);
                #endregion

                #region Определение текста для колонки "Остаток/Просрочено на сегодня"
                //subItems.Add(new ListViewItem.ListViewSubItem
                //{
                //    Text = directive.Remains.ToString(),
                //    Tag = directive.Remains
                //});
                #endregion

                #region Определение текста для колонки "Тип работ"

                //subItems.Add(new ListViewItem.ListViewSubItem { Text = directive.WorkType.ToString(), Tag = directive.WorkType });
                #endregion

                #region Определение текста для колонки "Следующее выполнение"
                //subItems.Add(new ListViewItem.ListViewSubItem
                //{
                //    Text = directive.NextPerformanceDate == null ? "N/A" : SmartCore.Auxiliary.Convert.GetDateFormat((DateTime)directive.NextPerformanceDate),
                //    Tag = directive.NextPerformanceDate
                //});
                #endregion

                #region Определение текста для колонки "Человек/Часы"

                subItems.Add(CreateRow(directive.ManHours.ToString(), directive.ManHours));
                #endregion

                #region Определение текста для колонки "Стоимость"

                //subItems.Add(new ListViewItem.ListViewSubItem { Text = directive.Cost.ToString(), Tag = directive.Cost });
                #endregion
            }
            else if (item is BaseComponent)
            {
                BaseComponent bd  = (BaseComponent)item;
                AtaChapter    ata = bd.ATAChapter;

                subItems.Add(CreateRow(ata.ToString(), ata));
                subItems.Add(CreateRow(bd.PartNumber, bd.PartNumber));
                subItems.Add(CreateRow(bd.Description, bd.Description));
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = bd.Kits.Count > 0 ? bd.Kits.Count + " kits" : "", Tag = bd.Kits.Count });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = bd.LifeLimit.ToString(), Tag = bd.LifeLimit });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = "", Tag = Lifelength.Null });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = bd.Remains.ToString(), Tag = bd.Remains });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = DetailRecordType.Removal.ToString(), Tag = DetailRecordType.Removal });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = bd.NextPerformanceDate == null ? "N/A" : SmartCore.Auxiliary.Convert.GetDateFormat((DateTime)bd.NextPerformanceDate), Tag = bd.NextPerformanceDate });
                subItems.Add(CreateRow(bd.ManHours.ToString(), bd.ManHours));
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = bd.Cost.ToString(), Tag = bd.Cost });
            }
            else if (item is Component)
            {
                Component  d   = (Component)item;
                AtaChapter ata = d.ATAChapter;

                subItems.Add(CreateRow(ata.ToString(), ata));
                subItems.Add(CreateRow(d.PartNumber, d.PartNumber));
                subItems.Add(CreateRow(d.Description, d.Description));
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = d.Kits.Count > 0 ? d.Kits.Count + " kits" : "", Tag = d.Kits.Count });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = d.LifeLimit != null ? d.LifeLimit.ToString() : "", Tag = d.LifeLimit });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = "", Tag = Lifelength.Null });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = d.Remains != null ? d.Remains.ToString() : "", Tag = d.Remains });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = DetailRecordType.Removal.ToString(), Tag = DetailRecordType.Removal });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = d.NextPerformanceDate == null ? "N/A" : SmartCore.Auxiliary.Convert.GetDateFormat((DateTime)d.NextPerformanceDate), Tag = d.NextPerformanceDate });
                subItems.Add(CreateRow(d.ManHours.ToString(), d.ManHours));
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = d.Cost.ToString(), Tag = d.Cost });
            }
            else if (item is ComponentDirective)
            {
                ComponentDirective dd  = (ComponentDirective)item;
                AtaChapter         ata = dd.ParentComponent.ATAChapter;

                subItems.Add(CreateRow(ata != null ? ata.ToString() : "", ata));
                subItems.Add(CreateRow("", ""));
                subItems.Add(CreateRow(dd.Remarks, dd.Remarks));
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = dd.Kits.Count > 0 ? dd.Kits.Count + " kits" : "", Tag = dd.Kits.Count });
                #region Определение текста для колонки "Первое выполнение"

                //ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
                //if (dd.Threshold.FirstPerformanceSinceNew != null && !dd.Threshold.FirstPerformanceSinceNew.IsNullOrZero())
                //{
                //    subItem.Text = "s/n: " + dd.Threshold.FirstPerformanceSinceNew;
                //    subItem.Tag = dd.Threshold.FirstPerformanceSinceNew;
                //}
                //subItems.Add(subItem);
                #endregion

                #region Определение текста для колонки "повторяющийся интервал"

                //subItem = new ListViewItem.ListViewSubItem();
                //if (!dd.Threshold.RepeatInterval.IsNullOrZero())
                //{
                //    subItem.Text = dd.Threshold.RepeatInterval.ToString();
                //    subItem.Tag = dd.Threshold.RepeatInterval;
                //}
                //else
                //{
                //    subItem.Text = "";
                //    subItem.Tag = Lifelength.Null;
                //}
                //subItems.Add(subItem);

                #endregion
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = dd.Remains.ToString(), Tag = dd.Remains });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = dd.DirectiveType.ToString(), Tag = dd.DirectiveType });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = dd.NextPerformanceDate == null ? "N/A" : SmartCore.Auxiliary.Convert.GetDateFormat((DateTime)dd.NextPerformanceDate), Tag = dd.NextPerformanceDate });
                subItems.Add(CreateRow(dd.ManHours.ToString(), dd.ManHours));
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = dd.Cost.ToString(), Tag = dd.Cost });
            }
            else if (item is MaintenanceCheck)
            {
                MaintenanceCheck mc = (MaintenanceCheck)item;
                subItems.Add(CreateRow("", null));
                subItems.Add(CreateRow("", Tag = ""));
                subItems.Add(CreateRow(mc.Name + (mc.Schedule ? " Shedule" : " Unshedule"), mc.Name));
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = mc.Kits.Count > 0 ? mc.Kits.Count + " kits" : "", Tag = mc.Kits.Count });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = mc.Interval.ToString(), Tag = mc.Interval });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = "", Tag = Lifelength.Null });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = mc.Remains.ToString(), Tag = mc.Remains });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = "", Tag = "" });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = mc.NextPerformanceDate == null ? "N/A" : SmartCore.Auxiliary.Convert.GetDateFormat((DateTime)mc.NextPerformanceDate), Tag = mc.NextPerformanceDate });
                subItems.Add(CreateRow(mc.ManHours.ToString(), mc.ManHours));
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = mc.Cost.ToString(), Tag = mc.Cost });
            }
            else if (item is MaintenanceDirective)
            {
                MaintenanceDirective md  = (MaintenanceDirective)item;
                AtaChapter           ata = md.ATAChapter;

                subItems.Add(CreateRow(ata != null ? ata.ToString() : "", ata));
                subItems.Add(CreateRow(md.ToString(), md.ToString()));
                subItems.Add(CreateRow(md.Description, md.Description));
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = md.Kits.Count > 0 ? md.Kits.Count + " kits" : "", Tag = md.Kits.Count });
                #region Определение текста для колонки "Первое выполнение"

                //ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
                //if (md.Threshold.FirstPerformanceSinceNew != null && !md.Threshold.FirstPerformanceSinceNew.IsNullOrZero())
                //{
                //    subItem.Text = "s/n: " + md.Threshold.FirstPerformanceSinceNew;
                //    subItem.Tag = md.Threshold.FirstPerformanceSinceNew;
                //}
                //if (md.Threshold.FirstPerformanceSinceEffectiveDate != null &&
                //    !md.Threshold.FirstPerformanceSinceEffectiveDate.IsNullOrZero())
                //{
                //    if (subItem.Text != "") subItem.Text += " or ";
                //    else
                //    {
                //        subItem.Text = "";
                //        subItem.Tag = md.Threshold.FirstPerformanceSinceEffectiveDate;
                //    }
                //    subItem.Text += "s/e.d: " + md.Threshold.FirstPerformanceSinceEffectiveDate;
                //}

                //subItems.Add(subItem);
                #endregion

                #region Определение текста для колонки "повторяющийся интервал"

                //subItem = new ListViewItem.ListViewSubItem();
                //if (!md.Threshold.RepeatInterval.IsNullOrZero())
                //{
                //    subItem.Text = md.Threshold.RepeatInterval.ToString();
                //    subItem.Tag = md.Threshold.RepeatInterval;
                //}
                //else
                //{
                //    subItem.Text = "";
                //    subItem.Tag = Lifelength.Null;
                //}
                //subItems.Add(subItem);

                #endregion
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = md.Remains.ToString(), Tag = md.Remains });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = md.WorkType.ToString(), Tag = md.WorkType });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = md.NextPerformanceDate == null ? "N/A" : SmartCore.Auxiliary.Convert.GetDateFormat((DateTime)md.NextPerformanceDate), Tag = md.NextPerformanceDate });
                subItems.Add(CreateRow(md.ManHours.ToString(), md.ManHours));
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = md.Cost.ToString(), Tag = md.Cost });
            }
            else if (item is NonRoutineJob)
            {
                NonRoutineJob job = (NonRoutineJob)item;
                AtaChapter    ata = job.ATAChapter;
                subItems.Add(CreateRow(ata != null ? ata.ToString() : "", ata));
                subItems.Add(CreateRow(job.Title, job.Title));
                subItems.Add(CreateRow(job.Description, job.Description));
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = job.Kits.Count > 0 ? job.Kits.Count + " kits" : "", Tag = job.Kits.Count });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = "", Tag = Lifelength.Null });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = "", Tag = Lifelength.Null });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = "", Tag = Lifelength.Null });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = "", Tag = "" });
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = "", Tag = new DateTime(1950,1,1) });
                subItems.Add(CreateRow(job.ManHours.ToString(), job.ManHours));
                //subItems.Add(new ListViewItem.ListViewSubItem { Text = job.Cost.ToString(), Tag = job.Cost });
            }
            else
            {
                throw new ArgumentOutOfRangeException($"1135: Takes an argument has no known type {item.GetType()}");
            }

            return(subItems);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Добавляет элементы в ListView
        /// </summary>
        /// <param name="itemsArray"></param>
        //protected override void AddItems(IBaseCoreObject[] itemsArray)
        //{
        //    ColumnHeader ch = ColumnHeaderList.FirstOrDefault(h => h.Text == "Performances");
        //    if (ch == null)
        //    {
        //        base.AddItems(itemsArray);
        //        return;
        //    }

        //    if(itemsArray == null || itemsArray.Length == 0)
        //    {
        //        ch.Width = 0;
        //        base.AddItems(itemsArray);
        //        return;
        //    }
        //    ch.Width = itemsArray.OfType<IDirective>()
        //                         .Count(d => d.NextPerformances != null && d.NextPerformances.Count > 1) > 0 ? 100 : 0;

        //    base.AddItems(itemsArray);
        //}

        #endregion

        #region protected override void SetGroupsToItems(int columnIndex)

        /// <summary>
        /// Возвращает название группы в списке агрегатов текущего склада, согласно тому, какого типа элемент
        /// </summary>
        //protected override void SetGroupsToItems(int columnIndex)
        //      {
        //     itemsListView.Groups.Clear();
        //     itemsListView.Groups.AddRange(new[]
        //                                       {
        //                                           new ListViewGroup("Engines", "Engines"),
        //                                           new ListViewGroup("APU's", "APU's"),
        //                                           new ListViewGroup("Landing Gears", "Landing Gears"),
        //                                       });
        //     foreach (ListViewItem item in ListViewItemList.OrderBy(x => x.Text))
        //     {
        //         String temp = "";

        //         if (!(item.Tag is IDirective)) continue;

        //         IDirective parent = (IDirective)item.Tag;

        //         #region Группировка по типу задачи

        //         if (parent is ComponentDirective)
        //             parent = ((ComponentDirective) parent).ParentComponent;
        //         if (parent is BaseComponent)
        //         {
        //             if (((BaseComponent)parent).BaseComponentType == BaseComponentType.Engine)
        //                 temp = "Engines";
        //             else if (((BaseComponent)parent).BaseComponentType == BaseComponentType.Apu)
        //                 temp = "APU's";
        //             else if (((BaseComponent)parent).BaseComponentType == BaseComponentType.LandingGear)
        //                 temp = "Landing Gears";

        //             item.Group = itemsListView.Groups[temp];
        //         }
        //         else if (parent is Component)
        //         {
        //             Component component = (Component)parent;

        //                 if (component.ParentBaseComponent != null)
        //                 {
        //                     BaseComponent baseComponent = component.ParentBaseComponent;//TODO:(Evgenii Babak) заменить на использование ComponentCore
        //temp = baseComponent + " Components";
        //                 }
        //                 else
        //                 {
        //                  AtaChapter ata = null;

        //if (component.Product != null)
        //{
        //	ata = component.Product.ATAChapter;
        //}
        //                  else ata = component.ATAChapter;

        //                     temp = ata.ShortName + " " + ata.FullName;
        //                 }
        //                 itemsListView.Groups.Add(temp, temp);
        //             item.Group = itemsListView.Groups[temp];
        //         }
        //         #endregion
        //     }
        //}

        #endregion

        #region protected override ListViewItem.ListViewSubItem[] GetListViewSubItems(IBaseCoreObject item)

        protected override List <CustomCell> GetListViewSubItems(IBaseEntityObject item)
        {
            var subItems = new List <CustomCell>();

            DateTime?  approx = null;
            AtaChapter ata;
            Store      store = null;
            string     maintenanceTypeString = "";
            DateTime   transferDate = DateTimeExtend.GetCASMinDateTime();
            bool       isPool = false, IsDangerous = false;
            Lifelength firstPerformance = Lifelength.Null,
                       lastPerformance  = Lifelength.Null,
                       remains = null,
                       next = null,
                       warranty = Lifelength.Null, repeatInterval = Lifelength.Null;
            string partNumber            = "",
                   description           = "",
                   altPartNumber         = "",
                   name                  = "",
                   standart              = "",
                   serialNumber          = "",
                   refference            = "",
                   effectivity           = "",
                   code                  = "",
                   id                    = "",
                   classString           = "",
                   batchNumber           = "",
                   idNumber              = "",
                   supplier              = "";
            string status                = "",
                   location              = "",
                   facility              = "",
                   lastPerformanceString = "",
                   kitRequieredString    = "",
                   remarks               = "",
                   hiddenRemarks         = "",
                   workType              = "",
                   timesString,
                   quantityString        = "",
                   currentString         = "",
                   shouldBeOnStockString = "",
                   from = "",
                   quantityInString = "",
                   currency = "",
                   author = "";
            double manHours = 0,
                   unitPrice = 0,
                   totalPrice = 0,
                   shipPrice = 0,
                   subTotal = 0,
                   tax1 = 0,
                   tax2 = 0,
                   tax3 = 0,
                   total = 0,
                   quantity = 0,
                   current = 0,
                   quantityIn = 0,
                   shouldBeOnStock = 0, needWpQuantity = 0, reserve = 0;
            int times,
                kitCount        = 0;
            var        position = ComponentStorePosition.UNK.ToString();
            IDirective parent;

            if (item is NextPerformance)
            {
                NextPerformance np = (NextPerformance)item;
                parent = np.Parent;

                int index = np.Parent.NextPerformances.IndexOf(np);
                timesString = index == 0 ? np.Parent.TimesToString : "#" + (index + 1);
                times       = index == 0 ? np.Parent.Times : index + 1;
            }
            else
            {
                parent = item as IDirective;
                if (parent == null)
                {
                    return(subItems);
                }
                timesString = parent.TimesToString;
                times       = parent.Times;
            }

            if (parent is Component)
            {
                Component componentItem = (Component)parent;
                id    = componentItem.ItemId.ToString();
                store = GlobalObjects.StoreCore.GetStoreById(componentItem.ParentStoreId);
                if (store == null)
                {
                    MessageBox.Show("qwe");
                }
                author                = GlobalObjects.CasEnvironment.GetCorrector(componentItem);
                approx                = componentItem.NextPerformanceDate;
                next                  = componentItem.NextPerformanceSource;
                remains               = componentItem.Remains;
                name                  = componentItem.Product?.Name;
                ata                   = componentItem.Product?.ATAChapter ?? componentItem.ATAChapter;
                partNumber            = componentItem.Product?.PartNumber ?? componentItem.PartNumber;
                altPartNumber         = componentItem.Product?.AltPartNumber ?? componentItem.ALTPartNumber;
                standart              = componentItem.Product?.Standart?.ToString() ?? componentItem.Standart?.ToString();
                refference            = componentItem.Product?.Reference;
                effectivity           = componentItem.Product?.IsEffectivity;
                description           = componentItem.Description;
                serialNumber          = componentItem.SerialNumber;
                code                  = componentItem.Product != null ? componentItem.Product.Code :componentItem.Code;
                classString           = componentItem.GoodsClass.ToString();
                batchNumber           = componentItem.BatchNumber;
                idNumber              = componentItem.IdNumber;
                position              = componentItem.TransferRecords.GetLast()?.State?.ToString();
                status                = componentItem.ComponentStatus.ToString();
                location              = componentItem.Location.ToString();
                facility              = componentItem.Location.LocationsType?.ToString() ?? LocationsType.Unknown.ToString();
                maintenanceTypeString =
                    componentItem.GoodsClass.IsNodeOrSubNodeOf(GoodsClass.ComponentsAndParts)
                                                ? componentItem.MaintenanceControlProcess.ShortName
                                                : componentItem.LifeLimit.IsNullOrZero()
                                                        ? ""
                                                        : MaintenanceControlProcess.HT.ShortName;
                transferDate       = componentItem.TransferRecords.GetLast().TransferDate;
                firstPerformance   = componentItem.LifeLimit;
                warranty           = componentItem.Warranty;
                kitRequieredString = componentItem.Kits.Count > 0 ? componentItem.Kits.Count + " kits" : "";
                kitCount           = componentItem.Kits.Count;
                bool isComponent =
                    componentItem.GoodsClass.IsNodeOrSubNodeOf(new IDictionaryTreeItem[]
                {
                    GoodsClass.ComponentsAndParts,
                    GoodsClass.ProductionAuxiliaryEquipment,
                });

                quantity              = isComponent && componentItem.ItemId > 0 ? 1 : componentItem.Quantity;
                quantityString        = quantity.ToString();
                quantityIn            = isComponent && componentItem.ItemId > 0 ? 1 : componentItem.QuantityIn;
                quantityInString      = $"{quantityIn:0.##}" + (componentItem.Measure != null ? " " + componentItem.Measure + "(s)" : "") + componentItem.Packing;
                needWpQuantity        = Math.Round(componentItem.NeedWpQuantity, 2);
                reserve               = quantity - needWpQuantity;
                shouldBeOnStock       = componentItem.ShouldBeOnStock;
                shouldBeOnStockString = componentItem.ShouldBeOnStock > 0 ? "Yes" : "No";
                manHours              = componentItem.ManHours;
                remarks               = componentItem.Remarks;
                hiddenRemarks         = componentItem.HiddenRemarks;
                isPool      = componentItem.IsPOOL;
                IsDangerous = componentItem.IsDangerous;
                supplier    = componentItem.FromSupplier.ToString();

                if (componentItem.ProductCosts.Count > 0)
                {
                    var productost = componentItem.ProductCosts.FirstOrDefault();
                    unitPrice  = productost.UnitPrice;
                    totalPrice = productost.TotalPrice;
                    shipPrice  = productost.ShipPrice;
                    subTotal   = productost.SubTotal;
                    tax1       = productost.Tax;
                    tax2       = productost.Tax1;
                    tax3       = productost.Tax2;
                    total      = productost.Total;
                    currency   = productost.Currency.ToString();
                }


                TransferRecord tr = componentItem.TransferRecords.GetLast();
                if (tr.FromAircraftId == 0 &&
                    tr.FromBaseComponentId == 0 &&
                    tr.FromStoreId == 0 &&
                    tr.FromSupplierId == 0 &&
                    tr.FromSpecialistId == 0)
                {
                    from = componentItem.Suppliers.ToString();
                }
                else
                {
                    from = DestinationHelper.FromObjectString(tr);
                }
            }
            else if (parent is ComponentDirective)
            {
                ComponentDirective dd = (ComponentDirective)parent;
                if (dd.Threshold.FirstPerformanceSinceNew != null && !dd.Threshold.FirstPerformanceSinceNew.IsNullOrZero())
                {
                    firstPerformance = dd.Threshold.FirstPerformanceSinceNew;
                }
                if (dd.LastPerformance != null)
                {
                    lastPerformanceString =
                        SmartCore.Auxiliary.Convert.GetDateFormat(dd.LastPerformance.RecordDate) + " " +
                        dd.LastPerformance.OnLifelength;
                    lastPerformance = dd.LastPerformance.OnLifelength;
                }
                if (dd.Threshold.RepeatInterval != null && !dd.Threshold.RepeatInterval.IsNullOrZero())
                {
                    repeatInterval = dd.Threshold.RepeatInterval;
                }
                store = GlobalObjects.StoreCore.GetStoreById(dd.ParentComponent.ParentStoreId);

                if (store == null)
                {
                    MessageBox.Show("qwe");
                }
                author = GlobalObjects.CasEnvironment.GetCorrector(dd);

                approx  = dd.NextPerformanceDate;
                next    = dd.NextPerformanceSource;
                remains = dd.Remains;
                ata     = dd.ParentComponent.Product?.ATAChapter ?? dd.ParentComponent.ATAChapter;
                maintenanceTypeString = dd.ParentComponent.MaintenanceControlProcess.ShortName;
                warranty           = dd.Threshold.Warranty;
                kitRequieredString = dd.Kits.Count > 0 ? dd.Kits.Count + " kits" : "";
                kitCount           = dd.Kits.Count;
                manHours           = dd.ManHours;
                remarks            = dd.Remarks;
                hiddenRemarks      = dd.HiddenRemarks;
                workType           = dd.DirectiveType.ToString();
                position           = "    " + dd.ParentComponent.TransferRecords.GetLast()?.State?.ToString();
                isPool             = dd.IsPOOL;
                IsDangerous        = dd.IsDangerous;
                partNumber         = "    " + (dd.ParentComponent.Product?.PartNumber ?? dd.ParentComponent.PartNumber);
                altPartNumber      = "    " + (dd.ParentComponent.Product?.AltPartNumber ?? dd.ParentComponent.ALTPartNumber);
                standart           = dd.ParentComponent.Product?.Standart?.ToString() ?? dd.ParentComponent.Standart?.ToString();
                name         = "    " + dd.ParentComponent.Product?.Name;
                description  = "    " + dd.ParentComponent.Description;
                serialNumber = "    " + dd.ParentComponent.SerialNumber;
                classString  = dd.ParentComponent.GoodsClass.ToString();
            }
            else
            {
                ata = (AtaChapter)GlobalObjects.CasEnvironment.GetDictionary <AtaChapter>().GetItemById(21);
            }

            subItems.Add(CreateRow(store?.ToString() ?? "N/A", store.ToString()));
            subItems.Add(CreateRow(id, id));
            subItems.Add(CreateRow(ata.ToString(), ata));
            subItems.Add(CreateRow(refference, refference));
            subItems.Add(CreateRow(partNumber, partNumber));
            subItems.Add(CreateRow(altPartNumber, altPartNumber));
            subItems.Add(CreateRow(standart, standart));
            subItems.Add(CreateRow(name, name));
            subItems.Add(CreateRow(description, description));
            subItems.Add(CreateRow(serialNumber, serialNumber));
            subItems.Add(CreateRow(classString, classString));
            subItems.Add(CreateRow(batchNumber, batchNumber));
            subItems.Add(CreateRow(idNumber, idNumber));
            subItems.Add(CreateRow(position?.ToString().ToUpper(), position));
            subItems.Add(CreateRow(status, status));
            subItems.Add(CreateRow(location, location));
            subItems.Add(CreateRow(facility, facility));
            subItems.Add(CreateRow(from, from));
            subItems.Add(CreateRow(transferDate > DateTimeExtend.GetCASMinDateTime()
                                        ? SmartCore.Auxiliary.Convert.GetDateFormat(transferDate) : "", transferDate));
            subItems.Add(CreateRow(workType, Tag = workType));
            subItems.Add(CreateRow(needWpQuantity.ToString(), needWpQuantity));
            subItems.Add(CreateRow(reserve.ToString(), reserve));
            subItems.Add(CreateRow(quantityString, quantity));
            subItems.Add(CreateRow(shouldBeOnStockString, shouldBeOnStock));
            subItems.Add(CreateRow(quantityInString, quantityIn));
            subItems.Add(CreateRow(unitPrice.ToString(), unitPrice));
            subItems.Add(CreateRow(totalPrice.ToString(), totalPrice));
            subItems.Add(CreateRow(shipPrice.ToString(), shipPrice));
            subItems.Add(CreateRow(subTotal.ToString(), subTotal));
            subItems.Add(CreateRow(tax1.ToString(), tax1));
            subItems.Add(CreateRow(tax2.ToString(), tax2));
            subItems.Add(CreateRow(tax3.ToString(), tax3));
            subItems.Add(CreateRow(total.ToString(), total));
            subItems.Add(CreateRow(currency, currency));
            subItems.Add(CreateRow(supplier, supplier));
            subItems.Add(CreateRow(code, code));
            subItems.Add(CreateRow(remarks, remarks));
            subItems.Add(CreateRow(effectivity, effectivity));
            subItems.Add(CreateRow(isPool ? "Yes" : "No", isPool));
            subItems.Add(CreateRow(IsDangerous ? "Yes" : "No", IsDangerous));
            subItems.Add(CreateRow(maintenanceTypeString, maintenanceTypeString));
            subItems.Add(CreateRow(manHours.ToString(), manHours));
            subItems.Add(CreateRow(firstPerformance.ToString(), firstPerformance));
            subItems.Add(CreateRow(repeatInterval.ToString(), repeatInterval));
            subItems.Add(CreateRow(timesString, times));
            subItems.Add(CreateRow(approx != null ? SmartCore.Auxiliary.Convert.GetDateFormat((DateTime)approx) + " " + next
                                        : next != null && !next.IsNullOrZero() ? next.ToString() : "", approx == null ? DateTimeExtend.GetCASMinDateTime() : (DateTime)approx));
            subItems.Add(CreateRow(remains != null && !remains.IsNullOrZero() ? remains.ToString() : "", remains ?? Lifelength.Null));
            subItems.Add(CreateRow(lastPerformanceString, lastPerformance));
            subItems.Add(CreateRow(warranty.ToString(), warranty));
            subItems.Add(CreateRow(kitRequieredString, kitCount));
            subItems.Add(CreateRow(hiddenRemarks, hiddenRemarks));
            subItems.Add(CreateRow(author, author));

            return(subItems);
        }
        protected override void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            //TODO:(Evgenii Babak) много повторяющегося кода, требуется оптимизация
            backgroundWorker.ReportProgress(50);

            Invoke(new Action(() => listViewCompliance.Items.Clear()));

            if (_currentDirective == null)
            {
                e.Cancel = true;
                return;
            }

            var lastRecords      = new List <AbstractPerformanceRecord>();
            var nextPerformances = new List <NextPerformance>();

            if (_openPubWorkPackages == null)
            {
                _openPubWorkPackages = new CommonCollection <WorkPackage>();
            }
            _openPubWorkPackages.Clear();

            var parentAircraft = GlobalObjects.AircraftsCore.GetAircraftById(_currentDirective.ParentBaseComponent.ParentAircraftId);    //TODO:(Evgenii Babak) пересмотреть использование ParentAircrafId здесь

            _openPubWorkPackages.AddRange(GlobalObjects.WorkPackageCore.GetWorkPackagesLite(parentAircraft, WorkPackageStatus.Opened));
            _openPubWorkPackages.AddRange(GlobalObjects.WorkPackageCore.GetWorkPackagesLite(parentAircraft, WorkPackageStatus.Published));

            var allWorkPackagesIncludedTask = new CommonCollection <WorkPackage>();
            var openPubWorkPackages         = new CommonCollection <WorkPackage>();
            var closedWorkPackages          = new CommonCollection <WorkPackage>();

            if (_currentDirective.IsAffect().GetValueOrDefault(true))
            {
                //Поиск и заполнение просроченных директив и записей о перемещении
                //Объекты для в которые будет извлекаться информация
                //из записеи о перемещении

                //прогнозируемый ресурс
                var forecastData = new ForecastData(DateTime.Now,
                                                    _currentDirective.ParentBaseComponent.AverageUtilization,
                                                    GlobalObjects.CasEnvironment.Calculator.GetCurrentFlightLifelength(_currentDirective.ParentBaseComponent));

                //расчет след. выполнений директивы.
                //если известен ресурс прогноза, то будут расчитаны все просрочнные выполнения
                //если неизвестне, то только первое
                //GlobalObjects.PerformanceCalculator.GetNextPerformance(_currentDirective, forecastData);
                nextPerformances.AddRange(_currentDirective.NextPerformances);
                lastRecords.AddRange(_currentDirective.PerformanceRecords.ToArray());
                ////////////////////////////////////////////
                //загрузка рабочих пакетов для определения
                //перекрытых ими выполнений задач
                _openPubWorkPackages.AddRange(GlobalObjects.WorkPackageCore.GetWorkPackages(parentAircraft, WorkPackageStatus.Opened, true));
                _openPubWorkPackages.AddRange(GlobalObjects.WorkPackageCore.GetWorkPackages(parentAircraft, WorkPackageStatus.Published, true));

                allWorkPackagesIncludedTask.AddRange(GlobalObjects.WorkPackageCore.GetWorkPackagesLite(parentAircraft,
                                                                                                       WorkPackageStatus.All,
                                                                                                       new IDirective[] { _currentDirective }));


                #region Добавление в список просроченных выполнений
                //и сравнение их с открытыми и опубликованными рабочими пакетами
                openPubWorkPackages.AddRange(allWorkPackagesIncludedTask.Where(wp => wp.Status == WorkPackageStatus.Opened ||
                                                                               wp.Status == WorkPackageStatus.Published));
                //сбор всех записей рабочих пакетов для удобства фильтрации
                List <WorkPackageRecord> openPubWpRecords = openPubWorkPackages.SelectMany(wp => wp.WorkPakageRecords).ToList();
                //LINQ запрос для сортировки записей по дате
                List <NextPerformance> sortNextRecords = (from record in nextPerformances
                                                          orderby GetDate(record) descending
                                                          select record).ToList();

                for (int i = 0; i < sortNextRecords.Count; i++)
                {
                    if (backgroundWorker.CancellationPending)
                    {
                        allWorkPackagesIncludedTask.Clear();
                        openPubWorkPackages.Clear();
                        closedWorkPackages.Clear();

                        e.Cancel = true;
                        return;
                    }

                    //поиск записи в рабочих пакетах по данному чеку
                    //чей номер группы выполнения (по записи) совпадает с расчитанным
                    MaintenanceDirective directive = (MaintenanceDirective)sortNextRecords[i].Parent;
                    //номер выполнения
                    int parentCountPerf;
                    if (directive.LastPerformance != null)
                    {
                        parentCountPerf = directive.LastPerformance.PerformanceNum <= 0
                            ? 1
                            : directive.LastPerformance.PerformanceNum;
                    }
                    else
                    {
                        parentCountPerf = 0;
                    }
                    parentCountPerf += directive.NextPerformances.IndexOf(sortNextRecords[i]);
                    parentCountPerf += 1;

                    WorkPackageRecord wpr =
                        openPubWpRecords.FirstOrDefault(r => r.PerformanceNumFromStart == parentCountPerf &&
                                                        r.WorkPackageItemType == directive.SmartCoreObjectType.ItemId &&
                                                        r.DirectiveId == directive.ItemId);
                    if (wpr != null)
                    {
                        WorkPackage wp = openPubWorkPackages.GetItemById(wpr.WorkPakageId);
                        //запись о выполнении блокируется найденым пакетом
                        sortNextRecords[i].BlockedByPackage = wp;
                        //последующие записи о выполнении так же должны быть заблокированы
                        for (int j = i - 1; j >= 0; j--)
                        {
                            //блокировать нужно все рабочие записи, или до первой записи,
                            //заблокированной другим рабочим пакетом
                            if (sortNextRecords[j].BlockedByPackage != null ||
                                sortNextRecords[j].Condition != ConditionState.Overdue)
                            {
                                break;
                            }
                            if (sortNextRecords[j].Parent == directive)
                            {
                                sortNextRecords[j].BlockedByPackage = wp;
                                Invoke(new Action <int, Color>(SetItemColor), new object[] { j, Color.FromArgb(Highlight.GrayLight.Color) });
                            }
                        }
                    }
                    Invoke(new Action <NextPerformance>(AddListViewItem), sortNextRecords[i]);
                }
                #endregion

                #region Добавление в список записей о произведенных выполнениях
                //и сравнение их с закрытыми рабочими пакетами
                closedWorkPackages.AddRange(allWorkPackagesIncludedTask.Where(wp => wp.Status == WorkPackageStatus.Closed));

                //LINQ запрос для сортировки записей по дате
                List <AbstractPerformanceRecord> sortLastRecords = (from record in lastRecords
                                                                    orderby record.RecordDate descending
                                                                    select record).ToList();
                ////////////////////////////////////////////

                for (int i = 0; i < sortLastRecords.Count(); i++)
                {
                    if (backgroundWorker.CancellationPending)
                    {
                        allWorkPackagesIncludedTask.Clear();
                        openPubWorkPackages.Clear();
                        closedWorkPackages.Clear();

                        e.Cancel = true;
                        return;
                    }

                    DirectiveRecord directiveRecord = (DirectiveRecord)sortLastRecords[i];
                    WorkPackage     workPackage     =
                        closedWorkPackages.Where(wp => wp.ItemId == directiveRecord.DirectivePackageId).FirstOrDefault();
                    if (workPackage != null)
                    {
                        Invoke(new Action <AbstractPerformanceRecord, WorkPackage, MaintenanceCheckRecord>(AddListViewItem),
                               new object[] { sortLastRecords[i], workPackage, null });
                    }
                    else if (directiveRecord.MaintenanceCheckRecordId > 0)
                    {
                        var mcr = GlobalObjects.CasEnvironment.NewLoader.GetObject <DirectiveRecordDTO, MaintenanceCheckRecord>(new Filter("ItemId", directiveRecord.MaintenanceCheckRecordId));

                        if (mcr != null)
                        {
                            mcr.ParentCheck = GlobalObjects.CasEnvironment.NewLoader.GetObjectById <MaintenanceCheckDTO, MaintenanceCheck>(mcr.ParentId);
                        }

                        Invoke(new Action <AbstractPerformanceRecord, WorkPackage, MaintenanceCheckRecord>(AddListViewItem),
                               new object[] { sortLastRecords[i], workPackage, mcr });
                    }
                    else
                    {
                        Invoke(new Action <AbstractPerformanceRecord, WorkPackage>(AddListViewItem),
                               new object[] { sortLastRecords[i], workPackage });
                    }
                }
                #endregion
            }
            else
            {
                //Поиск и заполнение просроченных директив и записей о перемещении
                //Объекты для в которые будет извлекаться информация
                //из записеи о перемещении

                //прогнозируемый ресурс
                foreach (var directive in _bindedItems)
                {
                    if (directive is ComponentDirective)
                    {
                        var componentDirective = (ComponentDirective)directive;
                        var detail             = componentDirective.ParentComponent ?? _currentDirective.ParentBaseComponent;
                        //прогнозируемый ресурс
                        //если известна родительская деталь данной директивы,
                        //то ее текущая наработка и средняя утилизация
                        //используются в качестве ресурсов прогноза
                        //для расчета всех просроченных выполнений
                        var forecastData = new ForecastData(DateTime.Now,
                                                            GlobalObjects.AverageUtilizationCore.GetAverageUtillization(detail),
                                                            GlobalObjects.CasEnvironment.Calculator.GetCurrentFlightLifelength(detail));
                        //расчет след. выполнений директивы.
                        //если известен ресурс прогноза, то будут расчитаны все просрочнные выполнения
                        //если неизвестне, то только первое
                        GlobalObjects.PerformanceCalculator.GetNextPerformance(componentDirective, forecastData);
                        nextPerformances.AddRange(componentDirective.NextPerformances);
                        lastRecords.AddRange(componentDirective.PerformanceRecords.ToArray());
                    }
                }
                var directiveRecords = _bindedItems.SelectMany(dd => dd.PerformanceRecords.Cast <DirectiveRecord>());
                lastRecords.AddRange(_currentDirective.PerformanceRecords
                                     .Where(performanceRecord => directiveRecords.Count(d => d.MaintenanceDirectiveRecordId == performanceRecord.ItemId) == 0)
                                     .Cast <AbstractPerformanceRecord>());
                ////////////////////////////////////////////
                //загрузка рабочих пакетов для определения
                _openPubWorkPackages.AddRange(GlobalObjects.WorkPackageCore.GetWorkPackagesLite(parentAircraft, WorkPackageStatus.Opened));
                _openPubWorkPackages.AddRange(GlobalObjects.WorkPackageCore.GetWorkPackagesLite(parentAircraft, WorkPackageStatus.Published));

                allWorkPackagesIncludedTask.AddRange(GlobalObjects.WorkPackageCore.GetWorkPackagesLite(parentAircraft,
                                                                                                       WorkPackageStatus.All,
                                                                                                       _bindedItems));

                #region Добавление в список просроченных выполнений
                //и сравнение их с открытыми и опубликованными рабочими пакетами
                openPubWorkPackages.AddRange(allWorkPackagesIncludedTask.Where(wp => wp.Status == WorkPackageStatus.Opened ||
                                                                               wp.Status == WorkPackageStatus.Published));
                //сбор всех записей рабочих пакетов для удобства фильтрации
                List <WorkPackageRecord> openPubWpRecords = new List <WorkPackageRecord>();
                foreach (WorkPackage openWorkPackage in openPubWorkPackages)
                {
                    openPubWpRecords.AddRange(openWorkPackage.WorkPakageRecords);
                }

                //LINQ запрос для сортировки записей по дате
                List <NextPerformance> sortNextRecords = (from record in nextPerformances
                                                          orderby GetDate(record) descending
                                                          select record).ToList();

                for (int i = 0; i < sortNextRecords.Count; i++)
                {
                    if (backgroundWorker.CancellationPending)
                    {
                        allWorkPackagesIncludedTask.Clear();
                        openPubWorkPackages.Clear();
                        closedWorkPackages.Clear();

                        e.Cancel = true;
                        return;
                    }

                    //поиск записи в рабочих пакетах по данному чеку
                    //чей номер группы выполнения (по записи) совпадает с расчитанным
                    ComponentDirective directive = (ComponentDirective)sortNextRecords[i].Parent;
                    //номер выполнения
                    int parentCountPerf;
                    if (directive.LastPerformance != null)
                    {
                        parentCountPerf = directive.LastPerformance.PerformanceNum <= 0
                            ? 1
                            : directive.LastPerformance.PerformanceNum;
                    }
                    else
                    {
                        parentCountPerf = 0;
                    }
                    parentCountPerf += directive.NextPerformances.IndexOf(sortNextRecords[i]);
                    parentCountPerf += 1;

                    WorkPackageRecord wpr =
                        openPubWpRecords.Where(r => r.PerformanceNumFromStart == parentCountPerf &&
                                               r.WorkPackageItemType == directive.SmartCoreObjectType.ItemId &&
                                               r.DirectiveId == directive.ItemId).FirstOrDefault();
                    if (wpr != null)
                    {
                        WorkPackage wp = openPubWorkPackages.GetItemById(wpr.WorkPakageId);
                        //запись о выполнении блокируется найденым пакетом
                        sortNextRecords[i].BlockedByPackage = wp;
                        //последующие записи о выполнении так же должны быть заблокированы
                        for (int j = i - 1; j >= 0; j--)
                        {
                            //блокировать нужно все рабочие записи, или до первой записи,
                            //заблокированной другим рабочим пакетом
                            if (sortNextRecords[j].BlockedByPackage != null ||
                                sortNextRecords[j].Condition != ConditionState.Overdue)
                            {
                                break;
                            }
                            if (sortNextRecords[j].Parent == directive)
                            {
                                sortNextRecords[j].BlockedByPackage = wp;
                                Invoke(new Action <int, Color>(SetItemColor), new object[] { j, Color.FromArgb(Highlight.GrayLight.Color) });
                            }
                        }
                    }
                    Invoke(new Action <NextPerformance>(AddListViewItem), sortNextRecords[i]);
                }
                #endregion

                #region Добавление в список записей о произведенных выполнениях
                //и сравнение их с закрытыми рабочими пакетами
                closedWorkPackages.AddRange(allWorkPackagesIncludedTask.Where(wp => wp.Status == WorkPackageStatus.Closed));

                //LINQ запрос для сортировки записей по дате
                List <AbstractPerformanceRecord> sortLastRecords = (from record in lastRecords
                                                                    orderby record.RecordDate descending
                                                                    select record).ToList();
                ////////////////////////////////////////////

                for (int i = 0; i < sortLastRecords.Count; i++)
                {
                    if (backgroundWorker.CancellationPending)
                    {
                        allWorkPackagesIncludedTask.Clear();
                        openPubWorkPackages.Clear();
                        closedWorkPackages.Clear();

                        e.Cancel = true;
                        return;
                    }
                    WorkPackage workPackage =
                        closedWorkPackages.FirstOrDefault(wp => wp.ItemId == sortLastRecords[i].DirectivePackageId);
                    Invoke(new Action <AbstractPerformanceRecord, WorkPackage>(AddListViewItem),
                           new object[] { sortLastRecords[i], workPackage });
                }
                #endregion
            }

            allWorkPackagesIncludedTask.Clear();
            openPubWorkPackages.Clear();
            closedWorkPackages.Clear();

            backgroundWorker.ReportProgress(100);
        }
Exemplo n.º 11
0
 /// <summary>
 /// Создает элемент управления, использующийся для задания отдельной информации Compliance/Performance при добавлении агрегата
 /// </summary>
 /// <param name="parentComponentеталь, для которой добавляется задача</param>
 public ComponentAddCompliancePerformanceControl(Component parentComponent) : this()
 {
     _parentComponent           = parentComponent;
     _currentComponentDirective = new ComponentDirective();
     UpdateInformation(parentComponent);
 }
        private void AddPerformance()
        {
            if (listViewCompliance.SelectedItems.Count == 0)
            {
                return;
            }

            DirectiveComplianceDialog dlg;
            DirectiveRecord           record;
            NextPerformance           np;

            if (listViewCompliance.SelectedItems[0].Tag is NextPerformance)
            {
                //if (_currentDirective.MaintenanceCheck != null)
                //{
                //    MessageBox.Show("This MPD is binded to maintenance check '" + _currentDirective.MaintenanceCheck.Name + "'." +
                //                    "\nPerformance for this item introduced by performance of maintenance check.",
                //                    (string)new GlobalTermsProvider()["SystemName"],
                //                    MessageBoxButtons.OK,
                //                    MessageBoxIcon.Warning,
                //                    MessageBoxDefaultButton.Button1);
                //    return;
                //}

                np = (NextPerformance)listViewCompliance.SelectedItems[0].Tag;

                //if (np.Condition != ConditionState.Overdue || np.PerformanceDate > DateTime.Now)
                //{
                //    MessageBox.Show("You can not enter a record for not delayed performance",
                //                    (string)new GlobalTermsProvider()["SystemName"],
                //                    MessageBoxButtons.OK,
                //                    MessageBoxIcon.Warning,
                //                    MessageBoxDefaultButton.Button1);
                //    return;
                //}
                if (np.BlockedByPackage != null)
                {
                    MessageBox.Show("Perform of the task:" + listViewCompliance.SelectedItems[0].Text +
                                    "\nblocked by Work Package:" +
                                    "\n" + np.BlockedByPackage.Title,
                                    (string)new GlobalTermsProvider()["SystemName"],
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning,
                                    MessageBoxDefaultButton.Button1);
                    return;
                }
                dlg = new DirectiveComplianceDialog(np.Parent, np)
                {
                    Text = "Add new compliance for " + np.WorkType
                };
                dlg.ShowDialog();

                if (dlg.DialogResult == DialogResult.OK)
                {
                    InvokeComplianceAdded(null);
                }
            }
            else if (listViewCompliance.SelectedItems[0].Tag is DirectiveRecord)
            {
                record = (DirectiveRecord)listViewCompliance.SelectedItems[0].Tag;
                IDirective directive = record.Parent;

                if (directive is MaintenanceDirective)
                {
                    MaintenanceDirective parentDirective = (MaintenanceDirective)directive;
                    dlg = new DirectiveComplianceDialog(record.Parent, record)
                    {
                        Text = "Edit exist compliance for " + parentDirective.WorkType
                    };
                    dlg.ShowDialog();

                    if (dlg.DialogResult == DialogResult.OK)
                    {
                        InvokeComplianceAdded(null);
                    }
                }
                else if (directive is ComponentDirective)
                {
                    ComponentDirective parentDirective = (ComponentDirective)directive;
                    dlg = new DirectiveComplianceDialog(record.Parent, record)
                    {
                        Text = "Edit exist compliance for " + parentDirective.DirectiveType + " of " + parentDirective.ParentComponent.Description
                    };
                    dlg.ShowDialog();

                    if (dlg.DialogResult == DialogResult.OK)
                    {
                        InvokeComplianceAdded(null);
                    }
                }
            }
            else
            {
                return;
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Добавляется элемент в таблицу данных
        /// </summary>
        /// <param name="destinationDataSet">Таблица, в которую добавляется элемент</param>
        private void AddBaseDetailToDataset(LLPDiskSheetDataSet destinationDataSet)
        {
            if (_reportedBaseComponent == null)
            {
                return;
            }

            var reportAircraftLifeLenght = GlobalObjects.CasEnvironment.Calculator.GetCurrentFlightLifelength(_reportedBaseComponent);

            var manufactureDate = _reportedBaseComponent.ManufactureDate.ToString(new GlobalTermsProvider()["DateFormat"].ToString());
            var deliveryDate    = _reportedBaseComponent.DeliveryDate.ToString(new GlobalTermsProvider()["DateFormat"].ToString());
            var status          = _reportedBaseComponent.Serviceable ? "Serviceable" : "Unserviceable";
            var sinceNewHours   = reportAircraftLifeLenght.Hours != null ? (int)reportAircraftLifeLenght.Hours : 0;
            var sinceNewCycles  = reportAircraftLifeLenght.Cycles != null ? (int)reportAircraftLifeLenght.Cycles : 0;
            var sinceNewDays    = reportAircraftLifeLenght.Days != null?reportAircraftLifeLenght.Days.ToString() : "";

            var lifeLimit      = _reportedBaseComponent.LifeLimit;
            var lifeLimitHours = lifeLimit.Hours != null?lifeLimit.Hours.ToString() : "";

            var lifeLimitCycles = lifeLimit.Cycles != null?lifeLimit.Cycles.ToString() : "";

            var lifeLimitDays = lifeLimit.Days != null?lifeLimit.Days.ToString() : "";

            var remain = new Lifelength(lifeLimit);

            remain.Substract(reportAircraftLifeLenght);
            var remainHours = remain.Hours != null?remain.Hours.ToString() : "";

            var remainCycles = remain.Cycles != null?remain.Cycles.ToString() : "";

            var remainDays = remain.Days != null?remain.Days.ToString() : "";

            var installationDate = _reportedBaseComponent.TransferRecords.GetLast().TransferDate;
            //TODO:(Evgenii Babak)  нужно брать наработку с записи о перемещении, а не пересчитывать заново
            var onInstall      = GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnEndOfDay(_reportedBaseComponent, installationDate);
            var onInstallDate  = installationDate.ToString(new GlobalTermsProvider()["DateFormat"].ToString());
            var onInstallHours = onInstall.Hours != null?onInstall.Hours.ToString() : "";

            var onInstallCycles = onInstall.Cycles != null?onInstall.Cycles.ToString() : "";

            var onInstallDays = onInstall.Days != null?onInstall.Days.ToString() : "";

            var sinceInstall = new Lifelength(reportAircraftLifeLenght);

            sinceInstall.Substract(onInstall);
            var sinceInstallHours = sinceInstall.Hours != null?sinceInstall.Hours.ToString() : "";

            var sinceInstallCycles = sinceInstall.Cycles != null?sinceInstall.Cycles.ToString() : "";

            var sinceInstallDays = sinceInstall.Days != null?sinceInstall.Days.ToString() : "";

            var warranty       = _reportedBaseComponent.Warranty;
            var warrantyRemain = new Lifelength(warranty);

            warrantyRemain.Substract(reportAircraftLifeLenght);
            warrantyRemain.Resemble(warranty);
            var warrantyHours = warranty.Hours != null?warranty.Hours.ToString() : "";

            var warrantyCycles = warranty.Cycles != null?warranty.Cycles.ToString() : "";

            var warrantyDays = warranty.Days != null?warranty.Days.ToString() : "";

            var warrantyRemainHours = warrantyRemain.Hours != null?warrantyRemain.Hours.ToString() : "";

            var warrantyRemainCycles = warrantyRemain.Cycles != null?warrantyRemain.Cycles.ToString() : "";

            var warrantyRemainDays = warrantyRemain.Days != null?warrantyRemain.Days.ToString() : "";

            var parentAircaft          = GlobalObjects.AircraftsCore.GetAircraftById(_reportedBaseComponent.ParentAircraftId);
            var aircraftFrame          = GlobalObjects.ComponentCore.GetBaseComponentById(parentAircaft.AircraftFrameId);
            var aircraftOnInstall      = GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnEndOfDay(aircraftFrame, installationDate);
            var aircraftOnInstallHours = aircraftOnInstall.Hours != null?aircraftOnInstall.Hours.ToString() : "";

            var aircraftOnInstallCycles = aircraftOnInstall.Cycles != null?aircraftOnInstall.Cycles.ToString() : "";

            var aircraftOnInstallDays = aircraftOnInstall.Days != null?aircraftOnInstall.Days.ToString() : "";

            var aircraftCurrent = GlobalObjects.CasEnvironment.Calculator.GetCurrentFlightLifelength(parentAircaft);

            var sinceOverhaul          = Lifelength.Null;
            var lastOverhaulDate       = DateTime.MinValue;
            var lastOverhaulDateString = "";

            #region поиск последнего ремонта и расчет времени, прошедшего с него
            //поиск директив деталей
            List <ComponentDirective> directives = GlobalObjects.ComponentCore.GetComponentDirectives(_reportedBaseComponent, true);
            //поиск директивы ремонта
            List <ComponentDirective> overhauls = directives.Where(d => d.DirectiveType == ComponentRecordType.Overhaul).ToList();
            //поиск последнего ремонта
            ComponentDirective lastOverhaul = null;
            foreach (ComponentDirective d in directives)
            {
                if (d.LastPerformance == null || d.LastPerformance.RecordDate <= lastOverhaulDate)
                {
                    continue;
                }

                lastOverhaulDate = d.LastPerformance.RecordDate;
                lastOverhaul     = d;
            }

            if (lastOverhaul != null)
            {
                sinceOverhaul.Add(reportAircraftLifeLenght);
                sinceOverhaul.Substract(lastOverhaul.LastPerformance.OnLifelength);
                lastOverhaulDateString = lastOverhaul.LastPerformance.RecordDate.ToString(new GlobalTermsProvider()["DateFormat"].ToString());
            }

            #endregion

            destinationDataSet.BaseDetailTable.AddBaseDetailTableRow(_reportedBaseComponent.ATAChapter.ToString(),
                                                                     _reportedBaseComponent.AvionicsInventory.ToString(),
                                                                     _reportedBaseComponent.PartNumber,
                                                                     _reportedBaseComponent.SerialNumber,
                                                                     _reportedBaseComponent.Model != null ? _reportedBaseComponent.Model.FullName : "",
                                                                     _reportedBaseComponent.BaseComponentType.ToString(),
                                                                     _reportedBaseComponent.GetParentAircraftRegNumber(),
                                                                     _reportedBaseComponent.TransferRecords.GetLast().Position,
                                                                     _reportedBaseComponent.Thrust,
                                                                     manufactureDate,
                                                                     deliveryDate,
                                                                     _reportedBaseComponent.MPDItem,
                                                                     _reportedBaseComponent.Suppliers != null
                                                                        ? _reportedBaseComponent.Suppliers.ToString()
                                                                        : "",
                                                                     status,
                                                                     _reportedBaseComponent.Cost,
                                                                     _reportedBaseComponent.CostOverhaul,
                                                                     _reportedBaseComponent.CostServiceable,
                                                                     lifeLimitHours,
                                                                     lifeLimitCycles,
                                                                     lifeLimitDays,
                                                                     sinceNewHours,
                                                                     sinceNewCycles,
                                                                     sinceNewDays,
                                                                     reportAircraftLifeLenght.ToStrings(),
                                                                     remainCycles,
                                                                     remainHours,
                                                                     remainDays,
                                                                     onInstallDate,
                                                                     onInstallHours,
                                                                     onInstallCycles,
                                                                     onInstallDays,
                                                                     sinceInstallHours,
                                                                     sinceInstallCycles,
                                                                     sinceInstallDays,
                                                                     warrantyHours,
                                                                     warrantyCycles,
                                                                     warrantyDays,
                                                                     warrantyRemainHours,
                                                                     warrantyRemainCycles,
                                                                     warrantyRemainDays,
                                                                     aircraftOnInstallHours,
                                                                     aircraftOnInstallCycles,
                                                                     aircraftOnInstallDays,
                                                                     lastOverhaulDateString,
                                                                     sinceOverhaul.Hours ?? 0,
                                                                     sinceOverhaul.Cycles ?? 0,
                                                                     sinceOverhaul.ToStrings());
        }
        private void AddComponentAndDirectiveToBindedItemsCollections(Component component, ComponentDirective componentDirective,
                                                                      ICommonCollection <BaseEntityObject> itemsToInsert,
                                                                      ICommonCollection <BaseEntityObject> allbindedItems,
                                                                      Dictionary <Component, List <ComponentDirective> > newBindedItems)
        {
            itemsToInsert.Add(componentDirective);

            // Добавление задачи по компоненту из коллекции содержащих все связаные задачи
            allbindedItems.Add(componentDirective);

            //если в коллекции содержащей все связные задачи нет родительского компонента от задачи по компоненту
            //требуется добавить компонент в коллекцию содержащую все связные задачи
            if (allbindedItems.OfType <Component>().All(i => i.ItemId != component.ItemId))
            {
                itemsToInsert.Add(component);
                allbindedItems.Add(component);
            }

            if (newBindedItems.ContainsKey(component))
            {
                newBindedItems[component].Add(componentDirective);
            }
            else
            {
                newBindedItems.Add(component, new List <ComponentDirective> {
                    componentDirective
                });
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Возвращает имя цвета директивы в отчете
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        //TODO:(Evgenii Babak) пересмотреть подход с формированием conditionState
        private static Highlight GetHighlight(object item)
        {
            Highlight      conditionState = Highlight.White;
            ConditionState cond;

            if (item is Directive)
            {
                Directive directive = (Directive)item;
                if (directive.NextPerformanceIsBlocked)
                {
                    conditionState = Highlight.DarkGreen;
                }
                else
                {
                    cond = directive.Condition;
                    if (cond == ConditionState.NotEstimated)
                    {
                        conditionState = Highlight.Blue;
                        if (directive.Status != DirectiveStatus.Closed && directive.IsApplicability && directive.Threshold.FirstPerformanceSinceNew.IsNullOrZero() && directive.Threshold.RepeatInterval.IsNullOrZero())
                        {
                            conditionState = Highlight.Orange;
                        }
                    }
                    if (cond == ConditionState.Notify)
                    {
                        conditionState = Highlight.Yellow;
                    }
                    if (cond == ConditionState.Overdue)
                    {
                        conditionState = Highlight.Red;
                    }
                }
            }
            else if (item is AircraftFlight)
            {
                if (!((AircraftFlight)item).Correct)
                {
                    conditionState = Highlight.Blue;
                }
            }
            else if (item is BaseComponent)
            {
                conditionState = Highlight.White;
            }
            else if (item is Component)
            {
                Component component = (Component)item;
                if (component.NextPerformanceIsBlocked)
                {
                    conditionState = Highlight.DarkGreen;
                }
                else
                {
                    cond = component.Condition;
                    if (cond == ConditionState.NotEstimated)
                    {
                        conditionState = Highlight.Blue;
                    }
                    if (cond == ConditionState.Notify)
                    {
                        conditionState = Highlight.Yellow;
                    }
                    if (cond == ConditionState.Overdue)
                    {
                        conditionState = Highlight.Red;
                    }
                }
            }
            else if (item is ComponentDirective)
            {
                ComponentDirective detDir = (ComponentDirective)item;
                if (detDir.NextPerformanceIsBlocked)
                {
                    conditionState = Highlight.DarkGreen;
                }
                else
                {
                    cond = detDir.Condition;
                    if (cond == ConditionState.NotEstimated)
                    {
                        conditionState = Highlight.Blue;
                    }
                    if (cond == ConditionState.Notify)
                    {
                        conditionState = Highlight.Yellow;
                    }
                    if (cond == ConditionState.Overdue)
                    {
                        conditionState = Highlight.Red;
                    }
                }
            }
            else if (item is MaintenanceDirective)
            {
                MaintenanceDirective mpd = (MaintenanceDirective)item;
                if (mpd.NextPerformanceIsBlocked)
                {
                    conditionState = Highlight.DarkGreen;
                }
                else
                {
                    cond = mpd.Condition;
                    if (cond == ConditionState.NotEstimated)
                    {
                        conditionState = Highlight.Blue;
                        if (mpd.Status != DirectiveStatus.Closed && mpd.IsApplicability && mpd.IsApplicability && mpd.Threshold.FirstPerformanceSinceNew.IsNullOrZero() && mpd.Threshold.RepeatInterval.IsNullOrZero())
                        {
                            conditionState = Highlight.Orange;
                        }
                    }
                    if (cond == ConditionState.Notify)
                    {
                        conditionState = Highlight.Yellow;
                    }
                    if (cond == ConditionState.Overdue)
                    {
                        conditionState = Highlight.Red;
                    }
                }
            }
            else if (item is NextPerformance)
            {
                conditionState = Highlight.White;
                cond           = ((NextPerformance)item).Condition;
                if (cond == ConditionState.Notify)
                {
                    conditionState = Highlight.Yellow;
                }
                if (cond == ConditionState.Overdue)
                {
                    conditionState = Highlight.Red;
                }
                if (((NextPerformance)item).BlockedByPackage != null)
                {
                    conditionState = Highlight.DarkGreen;
                }
            }
            else if (item is Document)
            {
                var document = (Document)item;
                if (document.NextPerformanceIsBlocked)
                {
                    conditionState = Highlight.DarkGreen;
                }
                else
                {
                    cond = document.Condition;
                    if (cond == ConditionState.NotEstimated)
                    {
                        conditionState = Highlight.Blue;
                    }
                    if (cond == ConditionState.Notify)
                    {
                        conditionState = Highlight.Yellow;
                    }
                    if (cond == ConditionState.Overdue)
                    {
                        conditionState = Highlight.Red;
                    }
                }
            }
            return(conditionState);
        }
        private void AddDetailDirectiveToDatatSet(string number, string mpdItem, string partNumber, string description, string serialNumber, string positionNumber, string installationDate, string installationTsncsn, string currentTsncsn, ComponentDirective directive, AtaChapter ataChapter, DetailListDataSet destinationDataSet)
        {
            var workType             = directive.DirectiveType.ShortName;
            var lastComplianceTsncsn = "";
            var lastComplianceDate   = "";
            var nextDate             = "";

            GlobalObjects.PerformanceCalculator.GetNextPerformance(directive);
            var nextTsncsn = LifelengthFormatter.GetHoursData(directive.NextPerformanceSource, " hrs\r\n") + LifelengthFormatter.GetCyclesData(directive.NextPerformanceSource, " cyc\r\n");

            if (directive.NextPerformanceDate != null)
            {
                nextDate = ((DateTime)directive.NextPerformanceDate).ToString(new GlobalTermsProvider()["DateFormat"].ToString());
            }
            var remains = LifelengthFormatter.GetCalendarData(directive.Remains, " d\r\n") + LifelengthFormatter.GetHoursData(directive.Remains, " h\r\n") + LifelengthFormatter.GetCyclesData(directive.Remains, " c\r\n");

            if (remains == "")
            {
                nextDate   = "";
                nextTsncsn = "";
            }
            var directiveRemarks = "";

            if (directive.LastPerformance != null)
            {
                var lastComplianceTsncsnlLifelength = directive.LastPerformance.OnLifelength;
                lastComplianceTsncsn = LifelengthFormatter.GetHoursData(lastComplianceTsncsnlLifelength, " hrs\r\n") + LifelengthFormatter.GetCyclesData(lastComplianceTsncsnlLifelength, " cyc\r\n");
                lastComplianceDate   = directive.LastPerformance.RecordDate.ToString(new GlobalTermsProvider()["DateFormat"].ToString());
                directiveRemarks     = directive.LastPerformance.Remarks;
            }

            var condition = directive.Condition.ToString();

            destinationDataSet.ItemsTable.AddItemsTableRow(number,
                                                           ataChapter.ShortName, ataChapter.FullName, partNumber, description,
                                                           serialNumber, positionNumber,
                                                           "",
                                                           installationDate,
                                                           lastComplianceTsncsn,
                                                           lastComplianceDate,
                                                           workType, nextTsncsn,
                                                           nextDate,
                                                           "",
                                                           "", condition, "", remains, "", "", "", "", mpdItem, installationTsncsn,
                                                           directiveRemarks, currentTsncsn);
        }
Exemplo n.º 17
0
        private void SetWorkTimeGA(BaseComponent powerUnit, FlightRegime flightRegime)
        {
            if (powerUnit == null)
            {
                return;
            }
            List <PowerUnitTimeInRegimeControlItem> fcs =
                flowLayoutPanelMain.Controls
                .OfType <PowerUnitTimeInRegimeControlItem>()
                .Where(c => c.PowerUnit != null &&
                       c.PowerUnit.ItemId == powerUnit.ItemId &&
                       c.FlightRegime == flightRegime)
                .ToList();
            int t = fcs.Sum(cr => cr.WorkTime);

            Lifelength baseDetailLifeLenghtInRegimeSinceLastOverhaul = null;
            Lifelength baseDetailLifeLenghtSinceLastOverhaul         = null;
            Lifelength baseDetailOhInterval = null;
            Lifelength baseDetailLifeLenghtInRegimeSinceNew =
                GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnStartOfDay(powerUnit, _flightDate, flightRegime);
            Lifelength baseDetailLifeLenghtSinceNew =
                GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnStartOfDay(powerUnit, _flightDate);
            Lifelength baseDetailLifeLimit = powerUnit.LifeLimit;

            ComponentWorkInRegimeParams inRegimeParams =
                powerUnit.ComponentWorkParams.Where(p => p.FlightRegime == flightRegime).FirstOrDefault();

            if (inRegimeParams != null &&
                inRegimeParams.ResorceProvider == SmartCoreType.ComponentDirective &&
                powerUnit.ComponentDirectives.GetItemById(inRegimeParams.ResorceProviderId) != null)
            {
                //в парамтрах работы требуется расчитать время работы в режиме с
                //последнего выполнения директивы
                ComponentDirective dd = powerUnit.ComponentDirectives.GetItemById(inRegimeParams.ResorceProviderId);
                if (dd.LastPerformance == null)
                {
                    baseDetailOhInterval = dd.Threshold.FirstPerformanceSinceNew;
                    //если последнего выполнения директивы нет,
                    //то расчитывается полная работа агрегата в указанном режиме
                    baseDetailLifeLenghtInRegimeSinceLastOverhaul =
                        GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnStartOfDay(powerUnit, _flightDate, flightRegime);
                    baseDetailLifeLenghtSinceLastOverhaul =
                        GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthOnStartOfDay(powerUnit, _flightDate);
                }
                else
                {
                    baseDetailOhInterval = dd.Threshold.RepeatInterval;
                    //т.к. может просматриваться старый полет (н: месячной давности)
                    //производится поиск последней записи о выполнении перед текущим полетов
                    AbstractPerformanceRecord r = dd.PerformanceRecords.GetLastKnownRecord(_flightDate);
                    if (r != null)
                    {
                        baseDetailLifeLenghtInRegimeSinceLastOverhaul =
                            GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthForPeriod(powerUnit, r.RecordDate, _flightDate.AddHours(-1), flightRegime);
                        baseDetailLifeLenghtSinceLastOverhaul =
                            GlobalObjects.CasEnvironment.Calculator.GetFlightLifelengthForPeriod(powerUnit, r.RecordDate, _flightDate.AddHours(-1));//TODO:(Evgenii Babak) выяснить почему AddHours(-1)
                    }
                }
            }

            if (Flight.AircraftId <= 0)
            {
                //извлечение всех полетов ВС
                var flights = GlobalObjects.AircraftFlightsCore.GetAircraftFlightsOnDate(Flight.AircraftId, _flightDate);
                //И поиск всех полетов, что были раньше текущего
                foreach (AircraftFlight aircraftFlight in flights)
                {
                    //Если полет был раньше текущего, то его наработка добавляется
                    //к рассчитываемым ресурсам базового агрегата
                    if (aircraftFlight.FlightDate < _flightDate.Date.Add(_outTime.TimeOfDay))
                    {
                        baseDetailLifeLenghtInRegimeSinceNew.Add(GlobalObjects.CasEnvironment.Calculator.GetFlightLifelength(aircraftFlight, powerUnit, flightRegime));
                        baseDetailLifeLenghtSinceNew.Add(GlobalObjects.CasEnvironment.Calculator.GetFlightLifelength(aircraftFlight, powerUnit));
                        if (baseDetailLifeLenghtInRegimeSinceLastOverhaul == null)
                        {
                            continue;
                        }
                        baseDetailLifeLenghtInRegimeSinceLastOverhaul.Add(GlobalObjects.CasEnvironment.Calculator.GetFlightLifelength(aircraftFlight, powerUnit, flightRegime));
                        if (baseDetailLifeLenghtSinceLastOverhaul == null)
                        {
                            continue;
                        }
                        baseDetailLifeLenghtSinceLastOverhaul.Add(GlobalObjects.CasEnvironment.Calculator.GetFlightLifelength(aircraftFlight, powerUnit));
                    }
                }
            }
            baseDetailLifeLenghtInRegimeSinceNew.Add(LifelengthSubResource.Minutes, t);

            if (baseDetailLifeLenghtInRegimeSinceLastOverhaul != null)
            {
                baseDetailLifeLenghtInRegimeSinceLastOverhaul.Add(LifelengthSubResource.Minutes, t);
            }


            double persentSN = 0, persentLifeLimit = 0, persentSLO = 0, persentOhInt = 0;
            int?   resInRegimeSN = baseDetailLifeLenghtInRegimeSinceNew.GetSubresource(LifelengthSubResource.Minutes);
            int?   resSN         = baseDetailLifeLenghtSinceNew.GetSubresource(LifelengthSubResource.Minutes);
            int?   resLl         = baseDetailLifeLimit.GetSubresource(LifelengthSubResource.Minutes);

            if (resSN != null && resInRegimeSN != null && resSN > 0)
            {
                persentSN = Convert.ToDouble((double)resInRegimeSN * 100 / resSN);
            }
            if (resLl != null && resInRegimeSN != null && resLl > 0)
            {
                persentLifeLimit = Convert.ToDouble((double)resInRegimeSN * 100 / resLl);
            }

            if (baseDetailLifeLenghtInRegimeSinceLastOverhaul != null)
            {
                int?resInRegimeSLO = baseDetailLifeLenghtInRegimeSinceLastOverhaul.GetSubresource(LifelengthSubResource.Minutes);

                if (baseDetailLifeLenghtSinceLastOverhaul != null)
                {
                    int?resSLO = baseDetailLifeLenghtSinceLastOverhaul.GetSubresource(LifelengthSubResource.Minutes);
                    if (resSLO != null && resInRegimeSLO != null && resSLO > 0)
                    {
                        persentSLO = Convert.ToDouble((double)resInRegimeSLO * 100 / resSLO);
                    }
                }
                if (baseDetailOhInterval != null)
                {
                    int?resOhInt = baseDetailOhInterval.GetSubresource(LifelengthSubResource.Minutes);
                    if (resOhInt != null && resInRegimeSLO != null && resOhInt > 0)
                    {
                        persentOhInt = Convert.ToDouble((double)resInRegimeSLO * 100 / resOhInt);
                    }
                }
            }


            foreach (PowerUnitTimeInRegimeControlItem fc in fcs)
            {
                fc.WorkTimeGA       = t;
                fc.WorkTimeSinceNew = baseDetailLifeLenghtInRegimeSinceNew;
                fc.WorkTimeSLO      = baseDetailLifeLenghtInRegimeSinceLastOverhaul;
                fc.PersentSN        = persentSN;
                fc.PersentLifeLimit = persentLifeLimit;
                fc.PersentSLO       = persentSLO;
                fc.PersentOhInt     = persentOhInt;
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Заполняет краткую информацию о директиве
        /// </summary>
        /// <param name="bindedItems"></param>
        private void UpdateInformation(IList <IDirective> bindedItems)
        {
            if ((_currentDirective == null) || _currentDirective.ParentBaseComponent == null)
            {
                return;
            }

            var inspectedComponent = _currentDirective.ParentBaseComponent;

            labelDirectiveValue.Text    = _currentDirective.TaskNumberCheck;
            labelDescriptionValue.Text  = _currentDirective.Description;
            labelRevisionDateValue.Text = _currentDirective.MpdRevisionNum + " " + Convert.GetDateFormat(_currentDirective.MpdRevisionDate);
            labelAMP.Text             = _currentDirective.ScheduleItem;
            labelAMPRevison.Text      = _currentDirective.ScheduleRevisionNum + " " + (_currentDirective.ScheduleRevisionDate > DateTimeExtend.GetCASMinDateTime() ? Convert.GetDateFormat(_currentDirective.ScheduleRevisionDate) : "");
            labelSBValue.Text         = _currentDirective.ServiceBulletinNo;
            labelATAChapterValue.Text = _currentDirective.ATAChapter != null
                ? _currentDirective.ATAChapter.ToString()
                : "";

            labelRemarksLast.Text         = "";
            labelApplicabilityValue.Text  = _currentDirective.Applicability;
            labelRemarksValue.Text        = _currentDirective.Remarks;
            labelHiddenRemarksValue.Text  = _currentDirective.HiddenRemarks;
            labelMRBValue.Text            = _currentDirective.MRB;
            labelMaintManualValue.Text    = _currentDirective.MaintenanceManual;
            labelTaskCardNumberValue.Text = _currentDirective.TaskCardNumber;
            labelMPDNumberValue.Text      = _currentDirective.MPDTaskNumber;
            labelWorkArea.Text            = _currentDirective.Workarea;
            labelSkill.Text               = _currentDirective.Skill.ToString();
            labelCategory.Text            = _currentDirective.Category.ToString();
            labelProgramValue.Text        = _currentDirective.Program.ToString();
            labelCriticalSystemValue.Text = _currentDirective.CriticalSystem.ToString();
            labelZoneValue.Text           = _currentDirective.Zone;
            labelAccessValue.Text         = _currentDirective.Access;
            labelCheckValue.Text          = _currentDirective.MaintenanceCheck != null
                    ? _currentDirective.MaintenanceCheck.Name
                    : "N/A";
            SetTextBoxComponentsString(bindedItems);
            if (CurrentBaseComponent != null)
            {
                linkDirectiveStatus.Text = BackLinkText;
            }

            ///////////////////////////////////////////////////////////////////////
            // Расчетные данные
            //////////////////////////////////////////////////////////////////////

            if (_currentDirective.ItemRelations.Count == 0)
            {
                #region  асчет при отсутствии привязанных задач

                if (_currentDirective.Remains != null && _currentDirective.Condition != ConditionState.NotEstimated)
                {
                    if (_currentDirective.Remains.IsOverdue() && _currentDirective.Condition == ConditionState.Overdue)
                    {
                        labelRemains.Text           = "Overdue:";
                        imageLinkLabelStatus.Status = Statuses.NotSatisfactory;
                    }
                    else if (_currentDirective.Condition == ConditionState.Notify)
                    {
                        labelRemains.Text           = "Remains:";
                        imageLinkLabelStatus.Status = Statuses.Notify;
                    }
                    else if (_currentDirective.Condition == ConditionState.Satisfactory)
                    {
                        labelRemains.Text           = "Remains:";
                        imageLinkLabelStatus.Status = Statuses.Satisfactory;
                    }
                    else
                    {
                        labelRemains.Text           = "Remains:";
                        imageLinkLabelStatus.Status = Statuses.NotActive;
                    }
                }
                imageLinkLabelStatus.Text = _currentDirective.WorkType.ToString();

                labelRemainsValue.Text = "";

                if (_currentDirective.Remains != null)
                {
                    labelRemainsValue.Text = _currentDirective.Remains.ToString();
                }

                labelCostValue.Text     = _currentDirective.Cost.ToString();
                labelManHoursValue.Text = _currentDirective.ManHours.ToString();
                labelKitValue.Text      = _currentDirective.Kits.Count == 0 ? "N" : _currentDirective.Kits.Count + "Kits";
                labelNDTvalue.Text      = _currentDirective.NDTType.ShortName;
                //labelRemarksValue.Text = _currentDirective.Remarks;

                //labelHiddenRemarksValue.Text = "";
                //if (labelHiddenRemarksValue.Text == "")
                //    labelHiddenRemarksValue.Text = "No Important information"; // labelHiddenRemarks.Visible = false;

                labelDateLast.Text            = "";
                labelAircraftTsnCsnLast.Text  = "";
                labelNextCompliance.Text      = "Next Compliance";
                labelDateNext.Text            = "n/a";
                labelAircraftTsnCsnNext.Text  = "n/a";
                labelComponentTsnCsnNext.Text = "n/a";
                //labelRemarksValue.Text = "";

                if (_currentDirective.LastPerformance != null)
                {
                    labelDateLast.Text = Convert.GetDateFormat(_currentDirective.LastPerformance.RecordDate);
                    //labelRemarksLast.Text = currentDirective.LastPerformance.Description;

                    if (!_currentDirective.LastPerformance.OnLifelength.IsNullOrZero())
                    {
                        labelComponentTsnCsnLast.Text = _currentDirective.LastPerformance.OnLifelength.ToString();
                    }
                    else
                    {
                        labelComponentTsnCsnLast.Text = _currentDirective.LastPerformance.OnLifelength.ToString();
                    }

                    //TODO:(Evgenii Babak)Если тип inspectedDetail будет Frame, то при перерасчете будет проверен тип базового агрегата и если он равен Frame,
                    //то берется parentAircraft от базовой детали и считается наработка для ВС. пересмотреть подход калякуляции для ВС

                    //labelAircraftTsnCsnLast.Text =
                    //                   GlobalObjects.CasEnvironment.Calculator.
                    //                    GetFlightLifelengthOnStartOfDay(inspectedComponent, _currentDirective.LastPerformance.RecordDate).ToString();
                    labelAircraftTsnCsnLast.Text = _currentDirective.LastPerformance.OnLifelength.ToString();
                }

                ///////////////////////////////////////////////////////////////////////////////////////////////
                labelFirstPerformanceValue.Text = "n/a";
                labelRptIntervalValue.Text      = "n/a";

                if (_currentDirective.Threshold.FirstPerformanceSinceNew != null &&
                    !_currentDirective.Threshold.FirstPerformanceSinceNew.IsNullOrZero())
                {
                    labelFirstPerformanceValue.Text = "s/n: " + _currentDirective.Threshold.FirstPerformanceSinceNew;
                }

                if (_currentDirective.Threshold.FirstPerformanceSinceEffectiveDate != null &&
                    !_currentDirective.Threshold.FirstPerformanceSinceEffectiveDate.IsNullOrZero())
                {
                    if (labelFirstPerformanceValue.Text != "n/a")
                    {
                        labelFirstPerformanceValue.Text += " or ";
                    }
                    else
                    {
                        labelFirstPerformanceValue.Text = "";
                    }
                    labelFirstPerformanceValue.Text += "s/e.d: " + _currentDirective.Threshold.FirstPerformanceSinceEffectiveDate;
                }

                if (_currentDirective.Threshold.RepeatInterval != null)
                {
                    labelRptIntervalValue.Text = _currentDirective.Threshold.RepeatInterval.IsNullOrZero()
                                                     ? "n/a"
                                                     : _currentDirective.Threshold.RepeatInterval.ToString();
                }
                ////////////////////////////////////////////////////////////////////////////////////////////////
                //labelRemarksValue.Text = _currentDirective.Remarks;


                if (_currentDirective.IsClosed)
                {
                    return;                            //если директива принудительно закрыта пользователем
                }
                //то вычисление следующего выполнения не нужно


                labelDateNext.Text = labelAircraftTsnCsnNext.Text = "n/a";
                if (_currentDirective.LastPerformance == null)
                {
                    if (_currentDirective.Threshold.FirstPerformanceSinceNew != null &&
                        !_currentDirective.Threshold.FirstPerformanceSinceNew.IsNullOrZero())
                    {
                        //если наработка исчисляется с момента выпуска
                        if (_currentDirective.Threshold.FirstPerformanceSinceNew.CalendarValue != null)
                        {
                            //если в первом выполнении заданы дни
                            //то выводится точная дата следующего выполнения
                            labelDateNext.Text =
                                Convert.GetDateFormat(inspectedComponent.ManufactureDate.
                                                      AddCalendarSpan(_currentDirective.Threshold.FirstPerformanceSinceNew.CalendarSpan)) +
                                " s/n";
                        }
                        else
                        {
                            //иначе, если (дополнительно) дата не определена
                            labelDateNext.Text = "n/a";
                        }
                        labelComponentTsnCsnNext.Text = "s/n: " + _currentDirective.Threshold.FirstPerformanceSinceNew;
                        //labelAircraftTsnCsnNext.Text = "s/n: " + currentDirective.Threshold.SinceNew.ToString();
                    }


                    if (_currentDirective.Threshold.FirstPerformanceSinceEffectiveDate != null &&
                        !_currentDirective.Threshold.FirstPerformanceSinceEffectiveDate.IsNullOrZero())
                    {
                        //если наработка исчисляется с эффективной даты

                        //Определение даты исполнения
                        if (_currentDirective.Threshold.FirstPerformanceSinceEffectiveDate.Days != null)
                        {
                            //если в первом выполнении заданы дни
                            //то выводится точная дата следующего выполнения
                            if (labelDateNext.Text != "n/a")
                            {
                                labelDateNext.Text += " or ";
                            }
                            else
                            {
                                labelDateNext.Text = "";
                            }


                            labelDateNext.Text +=
                                Convert.GetDateFormat(
                                    _currentDirective.Threshold.EffectiveDate.AddCalendarSpan(
                                        _currentDirective.Threshold.FirstPerformanceSinceEffectiveDate.CalendarSpan)) + " s/e.d.";
                        }
                        else
                        {
                            //иначе, дату определить нельзя
                            if (labelDateNext.Text == "")
                            {
                                labelDateNext.Text = "n/a";
                            }
                        }


                        //Определение наработки
                        if (_currentDirective.Threshold.EffectiveDate < DateTime.Today)
                        {
                            Lifelength sinceEffDate =
                                GlobalObjects.CasEnvironment.Calculator.
                                GetFlightLifelengthOnEndOfDay(inspectedComponent, _currentDirective.Threshold.EffectiveDate);
                            sinceEffDate.Add(_currentDirective.Threshold.EffectiveDate, _currentDirective.Threshold.FirstPerformanceSinceEffectiveDate);
                            sinceEffDate.Resemble(_currentDirective.Threshold.FirstPerformanceSinceEffectiveDate);

                            if (labelComponentTsnCsnNext.Text != "n/a")
                            {
                                labelComponentTsnCsnNext.Text += " or ";
                            }
                            else
                            {
                                labelComponentTsnCsnNext.Text = "";
                            }
                            labelComponentTsnCsnNext.Text += "s/e.d: " + sinceEffDate;
                        }
                    }
                }
                else
                {
                    if (_currentDirective.Threshold.PerformRepeatedly &&
                        _currentDirective.Threshold.RepeatInterval != null)
                    {
                        //повторяющаяся директива
                        //если есть последнне выполнение, то следующая дата расчитывается
                        //по повторяющемуся интервалу
                        if (_currentDirective.Threshold.RepeatInterval.CalendarValue != null)
                        {
                            //если в первом выполнении заданы дни
                            //то выводится точная дата следующего выполнения
                            labelDateNext.Text =
                                Convert.GetDateFormat(
                                    _currentDirective.LastPerformance.RecordDate.AddCalendarSpan(
                                        _currentDirective.Threshold.RepeatInterval.CalendarSpan));
                            labelDateNext.Text =
                                Convert.GetDateFormat(_currentDirective.NextPerformance.PerformanceDate.Value);
                        }
                        else
                        {
                            //иначе, точную дату выполнения расчитать нельзя
                            labelDateNext.Text            = "n/a";
                            labelComponentTsnCsnNext.Text = "n/a";
                        }

                        //Определение наработки
                        if (!_currentDirective.Threshold.RepeatInterval.IsNullOrZero())
                        {
                            Lifelength nextTsnCsn;
                            if (!_currentDirective.LastPerformance.OnLifelength.IsNullOrZero())
                            {
                                nextTsnCsn = new Lifelength(_currentDirective.LastPerformance.OnLifelength);
                            }
                            else
                            {
                                nextTsnCsn = _currentDirective.LastPerformance.OnLifelength;
                            }

                            Lifelength nextAircraftTsnCsn =
                                GlobalObjects.CasEnvironment.Calculator.
                                GetFlightLifelengthOnStartOfDay(inspectedComponent, _currentDirective.LastPerformance.RecordDate);

                            nextTsnCsn.Add(_currentDirective.LastPerformance.RecordDate, _currentDirective.Threshold.RepeatInterval);
                            nextTsnCsn.Resemble(_currentDirective.Threshold.RepeatInterval);
                            //labelComponentTsnCsnNext.Text = nextTsnCsn.ToString();
                            labelComponentTsnCsnNext.Text = _currentDirective.NextPerformance.PerformanceSource.ToString();

                            nextAircraftTsnCsn.Add(_currentDirective.LastPerformance.RecordDate, _currentDirective.Threshold.RepeatInterval);
                            nextAircraftTsnCsn.Resemble(_currentDirective.Threshold.RepeatInterval);
                            //labelAircraftTsnCsnNext.Text = nextAircraftTsnCsn.ToString();
                            labelAircraftTsnCsnNext.Text = _currentDirective.NextPerformance.PerformanceSource.ToString();

                            if (labelComponentTsnCsnNext.Text == "")
                            {
                                labelComponentTsnCsnNext.Text = "n/a";
                            }
                            if (labelAircraftTsnCsnNext.Text == "")
                            {
                                labelAircraftTsnCsnNext.Text = "n/a";
                            }
                        }
                        else
                        {
                            labelComponentTsnCsnNext.Text = "n/a";
                        }
                    }
                }
                #endregion
            }
            else
            {
                #region  асчет при наличии привязанных задач

                labelDateLast.Text            = "";
                labelAircraftTsnCsnLast.Text  = "";
                labelNextCompliance.Text      = "First Limitter";
                labelDateNext.Text            = "n/a";
                labelAircraftTsnCsnNext.Text  = "n/a";
                labelComponentTsnCsnNext.Text = "n/a";
                labelRemainsValue.Text        = "";
                //labelRemarksValue.Text = "";

                var firstLimitters   = new List <NextPerformance>();
                var lastPerformances = new List <DirectiveRecord>();

                foreach (var bdd in bindedItems)
                {
                    if (bdd is ComponentDirective)
                    {
                        var componentDirective = (ComponentDirective)bdd;
                        GlobalObjects.PerformanceCalculator.GetNextPerformance(componentDirective);

                        if (componentDirective.NextPerformances.Count > 0)
                        {
                            firstLimitters.Add(componentDirective.NextPerformances[0]);
                        }
                        if (componentDirective.LastPerformance != null)
                        {
                            lastPerformances.Add(componentDirective.LastPerformance);
                        }
                    }
                }

                var firstLimitter   = firstLimitters.OrderBy(np => np.PerformanceDate).FirstOrDefault();
                var lastPerformance = lastPerformances.OrderByDescending(p => p.RecordDate).FirstOrDefault() ??
                                      _currentDirective.LastPerformance;
                IDirective parentOfFirstLimitter = firstLimitter != null
                    ? firstLimitter.Parent
                    : lastPerformance != null ? lastPerformance.Parent : _currentDirective;

                if (firstLimitter != null && firstLimitter.Remains != null && firstLimitter.Condition != ConditionState.NotEstimated)
                {
                    if (firstLimitter.Remains.IsOverdue() && firstLimitter.Condition == ConditionState.Overdue)
                    {
                        labelRemains.Text           = "Overdue:";
                        imageLinkLabelStatus.Status = Statuses.NotSatisfactory;
                    }
                    else if (firstLimitter.Condition == ConditionState.Notify)
                    {
                        labelRemains.Text           = "Remains:";
                        imageLinkLabelStatus.Status = Statuses.Notify;
                    }
                    else if (firstLimitter.Condition == ConditionState.Satisfactory)
                    {
                        labelRemains.Text           = "Remains:";
                        imageLinkLabelStatus.Status = Statuses.Satisfactory;
                    }
                    else
                    {
                        labelRemains.Text           = "Remains:";
                        imageLinkLabelStatus.Status = Statuses.NotActive;
                    }
                    ComponentDirective componentDirective = (ComponentDirective)firstLimitter.Parent;
                    labelRemainsValue.Text    = firstLimitter.Remains.ToString();
                    imageLinkLabelStatus.Text = componentDirective.DirectiveType.ToString();
                    labelCostValue.Text       = componentDirective.Cost.ToString();
                    labelManHoursValue.Text   = componentDirective.ManHours.ToString();
                    labelKitValue.Text        = componentDirective.Kits.Count == 0 ? "N" : componentDirective.Kits.Count + "Kits";
                    labelNDTvalue.Text        = _currentDirective.NDTType.ShortName;
                    //labelRemarksValue.Text = componentDirective.Remarks;
                }
                else
                {
                    imageLinkLabelStatus.Text = _currentDirective.WorkType.ToString();
                    labelCostValue.Text       = _currentDirective.Cost.ToString();
                    labelManHoursValue.Text   = _currentDirective.ManHours.ToString();
                    labelKitValue.Text        = _currentDirective.Kits.Count == 0 ? "N" : _currentDirective.Kits.Count + "Kits";
                    labelNDTvalue.Text        = _currentDirective.NDTType.ShortName;
                    // labelRemarksValue.Text = _currentDirective.Remarks;
                }

                //labelHiddenRemarksValue.Text = "";
                //if (labelHiddenRemarksValue.Text == "")
                //    labelHiddenRemarksValue.Text = "No Important information"; // labelHiddenRemarks.Visible = false;

                if (lastPerformance != null)
                {
                    labelDateLast.Text = Convert.GetDateFormat(lastPerformance.RecordDate);

                    if (!lastPerformance.OnLifelength.IsNullOrZero())
                    {
                        labelComponentTsnCsnLast.Text = lastPerformance.OnLifelength.ToString();
                    }
                    else
                    {
                        labelComponentTsnCsnLast.Text = lastPerformance.OnLifelength.ToString();
                    }
                    //TODO:(Evgenii Babak)Тип inspectedDetail всегда будет Frame. При перерасчете будет проверен тип базового агрегата и если он равен Frame,
                    //то берется parentAircraft от базовой детали и считается наработка для ВС. пересмотреть подход калякуляции для ВС
                    labelAircraftTsnCsnLast.Text =
                        GlobalObjects.CasEnvironment.Calculator.
                        GetFlightLifelengthOnStartOfDay(inspectedComponent, lastPerformance.RecordDate).ToString();
                }

                ///////////////////////////////////////////////////////////////////////////////////////////////
                labelFirstPerformanceValue.Text = "n/a";
                labelRptIntervalValue.Text      = "n/a";

                if (parentOfFirstLimitter.Threshold.FirstPerformanceSinceNew != null &&
                    !parentOfFirstLimitter.Threshold.FirstPerformanceSinceNew.IsNullOrZero())
                {
                    labelFirstPerformanceValue.Text = "s/n: " + parentOfFirstLimitter.Threshold.FirstPerformanceSinceNew;
                }

                if (parentOfFirstLimitter.Threshold.FirstPerformanceSinceEffectiveDate != null &&
                    !parentOfFirstLimitter.Threshold.FirstPerformanceSinceEffectiveDate.IsNullOrZero())
                {
                    if (labelFirstPerformanceValue.Text != "n/a")
                    {
                        labelFirstPerformanceValue.Text += " or ";
                    }
                    else
                    {
                        labelFirstPerformanceValue.Text = "";
                    }
                    labelFirstPerformanceValue.Text += "s/e.d: " + parentOfFirstLimitter.Threshold.FirstPerformanceSinceEffectiveDate;
                }

                if (parentOfFirstLimitter.Threshold.RepeatInterval != null)
                {
                    labelRptIntervalValue.Text = parentOfFirstLimitter.Threshold.RepeatInterval.IsNullOrZero()
                                                     ? "n/a"
                                                     : parentOfFirstLimitter.Threshold.RepeatInterval.ToString();
                }
                ////////////////////////////////////////////////////////////////////////////////////////////////
                if (parentOfFirstLimitter.IsClosed)
                {
                    return;                                //если директива принудительно закрыта пользователем
                }
                //то вычисление следующего выполнения не нужно


                labelDateNext.Text = labelAircraftTsnCsnNext.Text = "n/a";
                if (parentOfFirstLimitter.LastPerformance == null)
                {
                    if (parentOfFirstLimitter.Threshold.FirstPerformanceSinceNew != null &&
                        !parentOfFirstLimitter.Threshold.FirstPerformanceSinceNew.IsNullOrZero())
                    {
                        //если наработка исчисляется с момента выпуска
                        if (parentOfFirstLimitter.Threshold.FirstPerformanceSinceNew.CalendarValue != null)
                        {
                            //если в первом выполнении заданы дни
                            //то выводится точная дата следующего выполнения
                            labelDateNext.Text =
                                Convert.GetDateFormat(inspectedComponent.ManufactureDate.
                                                      AddCalendarSpan(parentOfFirstLimitter.Threshold.FirstPerformanceSinceNew.CalendarSpan)) +
                                " s/n";
                        }
                        else
                        {
                            //иначе, если (дополнительно) дата не определена
                            labelDateNext.Text = "n/a";
                        }
                        labelComponentTsnCsnNext.Text = "s/n: " + parentOfFirstLimitter.Threshold.FirstPerformanceSinceNew;
                    }

                    if (parentOfFirstLimitter.Threshold.FirstPerformanceSinceEffectiveDate != null &&
                        !parentOfFirstLimitter.Threshold.FirstPerformanceSinceEffectiveDate.IsNullOrZero())
                    {
                        //если наработка исчисляется с эффективной даты

                        //Определение даты исполнения
                        if (parentOfFirstLimitter.Threshold.FirstPerformanceSinceEffectiveDate.Days != null)
                        {
                            //если в первом выполнении заданы дни
                            //то выводится точная дата следующего выполнения
                            if (labelDateNext.Text != "n/a")
                            {
                                labelDateNext.Text += " or ";
                            }
                            else
                            {
                                labelDateNext.Text = "";
                            }


                            labelDateNext.Text +=
                                Convert.GetDateFormat(parentOfFirstLimitter.Threshold.EffectiveDate.AddCalendarSpan(
                                                          parentOfFirstLimitter.Threshold.FirstPerformanceSinceEffectiveDate.CalendarSpan)) + " s/e.d.";
                        }
                        else
                        {
                            //иначе, дату определить нельзя
                            if (labelDateNext.Text == "")
                            {
                                labelDateNext.Text = "n/a";
                            }
                        }
                        //Определение наработки
                        if (parentOfFirstLimitter.Threshold.EffectiveDate < DateTime.Today)
                        {
                            Lifelength sinceEffDate =
                                GlobalObjects.CasEnvironment.Calculator.
                                GetFlightLifelengthOnEndOfDay(inspectedComponent, parentOfFirstLimitter.Threshold.EffectiveDate);
                            sinceEffDate.Add(parentOfFirstLimitter.Threshold.EffectiveDate, parentOfFirstLimitter.Threshold.FirstPerformanceSinceEffectiveDate);
                            sinceEffDate.Resemble(parentOfFirstLimitter.Threshold.FirstPerformanceSinceEffectiveDate);

                            if (labelComponentTsnCsnNext.Text != "n/a")
                            {
                                labelComponentTsnCsnNext.Text += " or ";
                            }
                            else
                            {
                                labelComponentTsnCsnNext.Text = "";
                            }
                            labelComponentTsnCsnNext.Text += "s/e.d: " + sinceEffDate;
                        }
                    }
                }
                else
                {
                    if (firstLimitter != null)
                    {
                        //повторяющаяся директива
                        //если есть последнне выполнение, то следующая дата расчитывается
                        //по повторяющемуся интервалу
                        if (parentOfFirstLimitter.Threshold.RepeatInterval.CalendarValue != null &&
                            firstLimitter.PerformanceDate != null)
                        {
                            //если в первом выполнении заданы дни
                            //то выводится точная дата следующего выполнения
                            labelDateNext.Text = Convert.GetDateFormat(firstLimitter.PerformanceDate.Value);
                        }
                        else
                        {
                            //иначе, точную дату выполнения расчитать нельзя
                            labelDateNext.Text            = "n/a";
                            labelComponentTsnCsnNext.Text = "n/a";
                        }

                        //Определение наработки
                        if (!parentOfFirstLimitter.Threshold.RepeatInterval.IsNullOrZero() &&
                            !firstLimitter.PerformanceSource.IsNullOrZero())
                        {
                            labelComponentTsnCsnNext.Text = firstLimitter.PerformanceSource.ToString();

                            //TODO:(Evgenii Babak)Тип inspectedDetail всегда будет Frame. При перерасчете будет проверен тип базового агрегата и если он равен Frame,
                            //то берется parentAircraft от базовой детали и считается наработка для ВС. пересмотреть подход калякуляции для ВС
                            Lifelength nextAircraftTsnCsn =
                                GlobalObjects.CasEnvironment.Calculator.
                                GetFlightLifelengthOnStartOfDay(inspectedComponent, lastPerformance.RecordDate);

                            nextAircraftTsnCsn.Add(lastPerformance.RecordDate, parentOfFirstLimitter.Threshold.RepeatInterval);
                            nextAircraftTsnCsn.Resemble(parentOfFirstLimitter.Threshold.RepeatInterval);
                            labelAircraftTsnCsnNext.Text = nextAircraftTsnCsn.ToString();

                            if (labelComponentTsnCsnNext.Text == "")
                            {
                                labelComponentTsnCsnNext.Text = "n/a";
                            }
                            if (labelAircraftTsnCsnNext.Text == "")
                            {
                                labelAircraftTsnCsnNext.Text = "n/a";
                            }
                        }
                        else
                        {
                            labelComponentTsnCsnNext.Text = "n/a";
                        }
                    }
                }
                #endregion
            }
        }