using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Responses;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Contracts.V1.Responses.Statistics;
using PARR.API.Controllers.V1.Base;
using PARR.Constants;
using PARR.DAL.Services.Interfaces;
namespace PARR.API.Controllers.V1.Statistics
{
///
/// Статистика выполняения заданий роботами, по полю RobotConfigurations.RobotStatusCode
///
[Authorize(Roles = ParrRoles.Administrator.Role)]
public class StatRobotStatusController : BaseApiController
{
private readonly IRobotService robotService;
private readonly IRobotConfigurationService robotConfigurationService;
private readonly IRobotStatusService robotStatusService;
private readonly IMapper mapper;
public StatRobotStatusController(
IRobotService robotService,
IRobotConfigurationService robotConfigurationService,
IRobotStatusService robotStatusService,
IMapper mapper
)
{
this.robotService = robotService;
this.robotConfigurationService = robotConfigurationService;
this.robotStatusService = robotStatusService;
this.mapper = mapper;
}
///
/// Статистика работы роботов
///
///
[HttpGet(ApiRoutes.StatRobotStatus.Get)]
public async Task Get()
{
var confStat = await robotConfigurationService.Get()
.AsNoTracking()
.GroupBy(t => new { t.RobotCode, t.RobotStatusCode })
.Select(t => new { RobotCode = t.Key.RobotCode, RobotStatusCode = t.Key.RobotStatusCode, Count = t.Count() })
.ToListAsync();
var robots = await robotService.Get().AsNoTracking().ToListAsync();
var robotStatuses = await robotStatusService.Get().AsNoTracking().ToListAsync();
var response = new List();
foreach (var robot in robots)
{
var item = new StatRobotStatusResponse { Robot = mapper.Map(robot) };
robotStatuses.ForEach(stat =>
{
item.Statistics.Add(new StatRobotStatusItemResponse
{
Status = mapper.Map(stat),
Count = confStat.FirstOrDefault(t => t.RobotStatusCode == stat.Code && t.RobotCode == robot.Code)?.Count ?? 0
});
});
item.Statistics = item.Statistics.OrderBy(t => t.Status?.Code).ToList();
response.Add(item);
}
response = response.OrderBy(t => t.Robot?.Code).ToList();
return Ok(new Response>(response, true));
}
}
}