using Infrastructure.Data; using Infrastructure.Extensions; using Application.Domain.Entities; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.ComponentModel.DataAnnotations; using System.Linq; namespace Platform.Apis.Controllers { [ApiVersion("1.0")] [Route("api/v{version:apiVersion}/[controller]/[action]")] [ApiController] public class ProductController : ControllerBase { private readonly IRepository _productRepo; private readonly IRepository _nodeRepo; private readonly IRepository _deviceRepo; public ProductController(IRepository productRepo, IRepository nodeRepo, IRepository deviceRepo) { this._productRepo = productRepo; this._nodeRepo = nodeRepo; this._deviceRepo = deviceRepo; } [HttpPost] public ActionResult GetProducts() { try { var organId = User.GetOrganId().Value; var model = this._nodeRepo.ReadOnlyTable() .Where(o => o.Building.OrganId == organId) .SelectMany(o => o.Devices) .Select(o=>o.IoTProduct) .GroupBy(o => new { o.Id, o.Name, o.Number, o.Image, }) .Select(o => new { o.Key.Id, o.Key.Name, o.Key.Number, o.Key.Image, Count = o.Count() }).ToList(); return Ok(model); } catch (Exception ex) { ex.PrintStack(); return Problem(ex.Message); } } [HttpPost] public ActionResult GetProduct([Required(ErrorMessage = nameof(RequiredAttribute))] string number) { try { var organId = User.GetOrganId().Value; var model = this._productRepo.ReadOnlyTable().Where(o => o.Number == number).FirstOrDefault(); model.IoTDevices = this._nodeRepo.ReadOnlyTable() .Where(o => o.Building.OrganId == organId) .SelectMany(o => o.Devices) .Include(o => o.IoTGateway) .Include(o => o.Data) .ToList() .Where(o => o.IoTProductId == model.Id) .ToList(); return Ok(model); } catch (Exception ex) { ex.PrintStack(); return Problem(ex.Message); } } //[HttpPost] //public IActionResult GetSummary(string organNumber) //{ // try // { // var products = this._buildingIoTGatewayRepo.ReadOnlyTable() // .WhereIf(!string.IsNullOrEmpty(organNumber), o => o.Building.Organ.Number == organNumber) // .SelectMany(o => o.IoTGateway.Devices) // .GroupBy(o => o.Product.Name) // .Select(o => new // { // Name = o.Key, // Online = o.Sum(c => c.IsOnline ? 1 : 0), // Offline = o.Sum(c => c.IsOnline ? 0 : 1), // }) // .ToList() // .Select(o => new // { // o.Name, // o.Online, // o.Offline, // Total = o.Online + o.Offline // }); // return Ok(new // { // Total = products.Sum(o => o.Total), // Online = products.Sum(o => o.Online), // Offline = products.Sum(o => o.Offline), // Products = products // }); // } // catch (Exception ex) // { // ex.PrintStack(); // return Problem(ex.Message); // } //} } }