using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using AsbCloudApp.Data; using AsbCloudApp.Repositories; using AsbCloudApp.Requests; using AsbCloudApp.Services; using AsbCloudDb.Model; using Mapster; namespace AsbCloudInfrastructure.Services; public class WellboreService : IWellboreService { private readonly IWellService wellService; private readonly IWellOperationRepository wellOperationRepository; public WellboreService(IWellService wellService, IWellOperationRepository wellOperationRepository) { this.wellService = wellService; this.wellOperationRepository = wellOperationRepository; } public async Task GetWellboreAsync(int idWell, int idSection, CancellationToken cancellationToken) { var request = new WellboreRequest { Ids = new (int, int?)[] { (idWell, idSection) }, Take = 1, }; var data = await GetWellboresAsync(request, cancellationToken); return data.FirstOrDefault(); } public async Task> GetWellboresAsync(WellboreRequest request, CancellationToken token) { var wellbores = new List(request.Ids.Count()); var skip = request.Skip ?? 0; var take = request.Take ?? 10; var sections = wellOperationRepository.GetSectionTypes() .ToDictionary(w => w.Id, w => w); var ids = request.Ids.GroupBy(i => i.idWell, i => i.idSection); var idsWells = request.Ids.Select(i => i.idWell); var allSections = await wellOperationRepository.GetSectionsAsync(idsWells, token); foreach (var id in ids) { var well = await wellService.GetOrDefaultAsync(id.Key, token); if (well is null) continue; var wellTimezoneOffset = TimeSpan.FromHours(well.Timezone.Hours); var wellFactSections = allSections .Where(section => section.IdWell == id.Key) .Where(section => section.IdType == WellOperation.IdOperationTypeFact); var idsSections = id .Where(i => i.HasValue) .Select(i => i!.Value); if (idsSections.Any()) wellFactSections = wellFactSections .Where(section => idsSections.Contains(section.IdWellSectionType)); var wellWellbores = wellFactSections.Select(section => new WellboreDto { Id = section.IdWellSectionType, Name = sections[section.IdWellSectionType].Caption, Well = well.Adapt(), DateStart = section.DateStart.ToOffset(wellTimezoneOffset), DateEnd = section.DateEnd.ToOffset(wellTimezoneOffset), DepthStart = section.DepthStart, DepthEnd = section.DepthEnd, }); wellbores.AddRange(wellWellbores); } return wellbores .OrderBy(w => w.Well.Id).ThenBy(w => w.Id) .Skip(skip).Take(take); } }