using System;
using System.Threading.Tasks;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using Microsoft.AspNetCore.Hosting;
namespace AsbCloudWebApi.Controllers
{
///
/// Контроллер отчетов по буровым скважинам
///
[Route("api/well")]
[ApiController]
public class ReportController : ControllerBase
{
private readonly IAsbCloudDbContext db;
private readonly IReportService reportService;
private readonly IWellService wellService;
private readonly IWebHostEnvironment appEnvironment;
public ReportController(IAsbCloudDbContext db, IReportService reportService, IWellService wellService, IWebHostEnvironment appEnvironment)
{
this.db = db;
this.reportService = reportService;
this.wellService = wellService;
this.appEnvironment = appEnvironment;
}
///
/// Создает отчет по скважине с указанными параметрами
///
/// id скважины
/// дата начала интервала
/// дата окончания интервала
/// шаг интервала
/// формат отчета (0-PDF, 1-LASS)
/// id фоновой задачи формирования отчета
[HttpPost]
[Route("{wellId}/report")]
[ProducesResponseType(typeof(string), (int)System.Net.HttpStatusCode.OK)]
// ЭТОТ МЕТОД ПОКА НЕ РЕАЛИЗОВАН
public async Task CreateReportAsync(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();
return await Task.Run(() =>
{
// создаем отчет. Это заготовка, пока еще не перенесена в сервис.
var taskId = Task.CurrentId;
if (taskId is null)
throw new NullReferenceException("Не удалось получить id задачи");
return Ok(taskId.ToString());
});
}
///
/// Возвращает файл-отчет с диска на сервере
///
/// 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();
var options = reportService.GetReportFileProperties(reportName, appEnvironment.ContentRootPath);
return File(options.Filestream, options.ContentType, options.FileName);
}
catch (FileNotFoundException ex)
{
return NotFound("Файл не найден");
}
}
///
/// Возвращает прогнозируемое количество страниц будущего отчета
///
/// 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);
}
}
}