using System;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudWebApi.SignalR;
using Microsoft.AspNetCore.SignalR;
namespace AsbCloudWebApi.Controllers
{
///
/// Контроллер отчетов по буровым скважинам
///
[Route("api/well")]
[ApiController]
public class ReportController : ControllerBase
{
private readonly IReportService reportService;
private readonly IWellService wellService;
private readonly IHubContext reportsHubContext;
public ReportController(IReportService reportService, IWellService wellService, IHubContext reportsHubContext)
{
this.reportService = reportService;
this.wellService = wellService;
this.reportsHubContext = reportsHubContext;
}
private void HandleReportProgress (float progress, string operation, int id) =>
reportsHubContext.Clients.Group($"Report{id}").SendAsync(nameof(IReportHubClient.GetReportProgress), progress);
///
/// Создает отчет по скважине с указанными параметрами
///
/// id скважины
/// шаг интервала
/// формат отчета (0-PDF, 1-LASS)
/// дата начала интервала
/// дата окончания интервала
/// id фоновой задачи формирования отчета
[HttpPost]
[Route("{wellId}/report")]
[ProducesResponseType(typeof(string), (int)System.Net.HttpStatusCode.OK)]
public IActionResult CreateReport(int wellId, int stepSeconds, int format,
DateTime begin = default, DateTime end = default)
{
int? idCustomer = User.GetCustomerId();
if (idCustomer is null)
return BadRequest();
if (!wellService.CheckWellOwnership((int)idCustomer, wellId))
return Forbid();
var id = reportService.CreateReport(wellId, stepSeconds, format, begin, end, HandleReportProgress);
return Ok(id);
}
///
/// Возвращает файл-отчет с диска на сервере
///
/// id скважины
/// имя запрашиваемого файла (отчета)
/// файловый поток с отчетом
[HttpGet]
[Route("{wellId}/report")]
[ProducesResponseType(typeof(FileStreamResult), (int)System.Net.HttpStatusCode.OK)]
public IActionResult GetReport([FromRoute] int wellId, [FromQuery] string reportName)
{
try
{
int? idCustomer = User.GetCustomerId();
if (idCustomer is null)
return BadRequest();
if (!wellService.CheckWellOwnership((int)idCustomer, wellId))
return Forbid();
// TODO: словарь content typoв
return PhysicalFile(Path.Combine(reportService.RootPath, $"{wellId}", reportName), "application/pdf", reportName);
}
catch (FileNotFoundException ex)
{
return NotFound($"Файл не найден. Текст ошибки: {ex.Message}");
}
}
///
/// Возвращает прогнозируемое количество страниц будущего отчета
///
/// id скважины
/// дата начала интервала
/// дата окончания интервала
/// шаг интервала
/// формат отчета (0-PDF, 1-LASS)
/// прогнозируемое кол-во страниц отчета
[HttpGet]
[Route("{wellId}/reportSize")]
[ProducesResponseType(typeof(string), (int)System.Net.HttpStatusCode.OK)]
public IActionResult GetReportSize(int wellId, int stepSeconds, int format, DateTime begin = default, DateTime end = default)
{
int? idCustomer = User.GetCustomerId();
if (idCustomer is null)
return BadRequest();
if (!wellService.CheckWellOwnership((int)idCustomer, wellId))
return Forbid();
int reportSize = reportService.GetReportPagesCount(wellId, begin, end, stepSeconds, format);
return Ok(reportSize);
}
///
/// Возвращает даты самого старого и самого свежего отчетов в БД
///
/// id скважины
/// Даты самого старого и самого свежего отчетов в БД
[HttpGet]
[Route("{wellId}/reportsDatesRange")]
[ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)]
public IActionResult GetReportsDateRange(int wellId)
{
int? idCustomer = User.GetCustomerId();
if (idCustomer is null)
return BadRequest();
if (!wellService.CheckWellOwnership((int)idCustomer, wellId))
return Forbid();
DatesRangeDto wellReportsDatesRange = reportService.GetReportsDatesRange(wellId);
return Ok(wellReportsDatesRange);
}
}
}