DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/DataService.cs
2021-08-09 15:41:42 +05:00

113 lines
3.8 KiB
C#

using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache;
using Mapster;
using System;
using System.Collections.Generic;
using System.Linq;
namespace AsbCloudInfrastructure.Services
{
public class DataService : IDataService
{
private readonly IAsbCloudDbContext db;
private readonly ITelemetryService telemetryService;
private readonly IAnalyticsService analyticsService;
private readonly CacheTable<Telemetry> cacheTelemetry;
private readonly CacheTable<Well> cacheWells;
public DataService(IAsbCloudDbContext db, ITelemetryService telemetryService,
IAnalyticsService analyticsService, CacheDb cacheDb)
{
this.db = db;
this.telemetryService = telemetryService;
this.analyticsService = analyticsService;
cacheTelemetry = cacheDb.GetCachedTable<Telemetry>((AsbCloudDbContext)db);
cacheWells = cacheDb.GetCachedTable<Well>((AsbCloudDbContext)db);
}
public IEnumerable<DataSaubBaseDto> Get(int idWell, DateTime dateBegin = default, double intervalSec = 600d, int approxPointsCount = 1024)
{
var well = cacheWells.FirstOrDefault(w => w.Id == idWell);
if (well is null)
return default;
var telemetry = cacheTelemetry.FirstOrDefault(t => t.Id == well.IdTelemetry);
if (telemetry is null)
return default;
if (dateBegin == default)
dateBegin = DateTime.Now.AddSeconds(-intervalSec);
var datEnd = dateBegin.AddSeconds(intervalSec);
var query = from data in db.DataSaubBases
where data.IdTelemetry == telemetry.Id
&& data.Date >= dateBegin && data.Date < datEnd
select data;
var fullDataCount = query.Count();
if (fullDataCount == 0)
return default;
if (fullDataCount > 1.75 * approxPointsCount)
{
var m = (int)Math.Round(1d * fullDataCount / approxPointsCount);
if (m > 1)
query = query.Where(d => d.Id % m == 0);
}
var entities = query.ToList();
var dtos = entities.Adapt<DataSaubBaseDto>();
return dtos;
}
public void UpdateData(string uid, IEnumerable<DataSaubBaseDto> dtos)
{
if (dtos == default || !dtos.Any())
return;
var telemetryId = telemetryService.GetOrCreateTemetryIdByUid(uid);
var dtoMinDate = dtos.Min(d => d.Date);
var dtoMaxDate = dtos.Max(d => d.Date);
var oldDataSaubBase = (from d in db.DataSaubBases
where d.IdTelemetry == telemetryId
&& d.Date > dtoMinDate
&& d.Date < dtoMaxDate
select d).ToList();
if (oldDataSaubBase.Any())
db.DataSaubBases.RemoveRange(oldDataSaubBase);
foreach (var dto in dtos)
{
var dataSaub = dto.Adapt<DataSaubBase>();
dataSaub.IdTelemetry = telemetryId;
db.DataSaubBases.Add(dataSaub);
dto.IdTelemetry = telemetryId;
analyticsService.SaveAnalytics(dto);
}
db.SaveChanges();
}
public DatesRangeDto GetDataDatesRange(int idWell)
{
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell);
if (telemetryId is null)
return null;
var (From, To) = db.GetDatesRange<DataSaubBase>((int)telemetryId);
return new DatesRangeDto { From = From, To = To };
}
}
}