using AsbCloudApp.Data; using AsbCloudApp.Services; using AsbCloudDb.Model; using Mapster; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services { #nullable enable public class ScheduleService : CrudServiceBase, IScheduleService { private readonly IWellService wellService; public ScheduleService(IAsbCloudDbContext context, IWellService wellService) : base(context) { Includes.Add(nameof(Schedule.Driller)); this.wellService = wellService; } public async Task> GetByIdWellAsync(int idWell, CancellationToken token = default) { var entities = await GetQueryWithIncludes() .Where(s => s.IdWell == idWell) .ToListAsync(token); var dtos = entities.Select(Convert); return dtos; } public async Task GetDrillerAsync(int idWell, DateTime workTime, CancellationToken token = default) { var hoursOffset = wellService.GetTimezone(idWell).Hours; var date = workTime.ToUtcDateTimeOffset(hoursOffset); var entities = await GetQueryWithIncludes() .Where(s => s.IdWell==idWell && s.DrillStart <= date && s.DrillEnd >= date) .ToListAsync(token); if (!entities.Any()) return null; var remoteDate = date.ToRemoteDateTime(hoursOffset); var time = new TimeOnly(remoteDate.Hour, remoteDate.Minute, remoteDate.Second); var entity = entities.FirstOrDefault(s => (s.ShiftStart > s.ShiftEnd) ^ (time >= s.ShiftStart && time < s.ShiftEnd) ); return entity?.Driller.Adapt(); } public override Schedule Convert(ScheduleDto dto) { var hoursOffset = wellService.GetTimezone(dto.IdWell).Hours; var entity = base.Convert(dto); entity.DrillStart = dto.DrillStart.ToUtcDateTimeOffset(hoursOffset); entity.DrillEnd = dto.DrillEnd.ToUtcDateTimeOffset(hoursOffset); return entity; } public override ScheduleDto Convert(Schedule entity) { var hoursOffset = wellService.GetTimezone(entity.IdWell).Hours; var dto = base.Convert(entity); dto.DrillStart = entity.DrillStart.ToRemoteDateTime(hoursOffset); dto.DrillEnd = entity.DrillEnd.ToRemoteDateTime(hoursOffset); return dto; } } #nullable disable }