using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Requests;
using PARR.API.Contracts.V1.Requests.Queries;
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.API.Services.Interfaces;
using PARR.Core.Repositories.Interfaces;
using PARR.Domain.Common.Roles;

namespace PARR.API.Controllers.V1.Statistics
{
    /// <summary>
    /// Статистика загрузки регламентными работами по ЗО
    /// </summary>
    [Authorize(Roles = ParrRoles.EsppRobot.RoleOrAdmin)]
    public class StatResponseAreaWorkLoadController : BaseApiController
    {
        private readonly ITemplateRepository templateService;
        //private readonly IResponseAreaService responseAreaService;
        private readonly IMapper mapper;
        //private readonly IWorkLoadService workLoadService;

        public StatResponseAreaWorkLoadController(
            ITemplateRepository templateService,
            //IResponseAreaService responseAreaService,
            IMapper mapper
            //IWorkLoadService workLoadService
            )
        {
            this.templateService = templateService;
            //this.responseAreaService = responseAreaService;
            this.mapper = mapper;
            //this.workLoadService = workLoadService;
        }


        ///// <summary>
        ///// Статистика загрузки РР по всем ЗО 
        ///// </summary>
        ///// <returns></returns>
        //[HttpGet(ApiRoutes.StatResponseAreaWorkLoad.GetAll)]
        //public async Task<IActionResult> GetAll([FromQuery] WorkloadBaseQuery requestQuery)
        //{
        //    var response = await GetStatisticsAsync(requestQuery);

        //    return Ok(new Response<List<StatResponseAreaWorkLoadResponse>>(response, true));
        //}


        ///// <summary>
        ///// Статистика загрузки РР по списку ЗО
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost(ApiRoutes.StatResponseAreaWorkLoad.GetByResponseAreas)]
        //public async Task<IActionResult> GetByResponseAreas([FromBody] StatResponseAreaWorkloadRequest request)
        //{
        //    var response = await GetStatisticsAsync(request.Filter, request.ResponseAreas);

        //    return Ok(new Response<List<StatResponseAreaWorkLoadResponse>>(response, true));
        //}


        //private async Task<List<StatResponseAreaWorkLoadResponse>> GetStatisticsAsync(WorkloadBaseQuery requestQuery, List<int>? responseAreas = null)
        //{
        //    var daysList = workLoadService.GetDatesForPeriod(requestQuery);

        //    IQueryable<DAL.Models.Template> query = templateService.Get()
        //        .Include(t => t.Host).ThenInclude(t => t.WorkGroup);

        //    query = workLoadService.FilterTemplatesQuery(query, requestQuery);

        //    if (responseAreas != null && responseAreas.Count() > 0)
        //        query = query.Where(t => responseAreas.Any(x => x == t.Host.WorkGroup.ResponseAreaCode));

        //    //var groupedQuery = query.GroupBy(t => new { t.NextRun.DateTime.Date, t.Host!.WorkGroup!.ResponseAreaCode })
        //    var groupedQuery = query.GroupBy(t => new { t.NextRun.AddHours(requestQuery.TimeZoneOffsetHours).DateTime.Date, t.Host!.WorkGroup!.ResponseAreaCode })
        //        .Select(t => new
        //        {
        //            ResponseAreaCode = t.Key.ResponseAreaCode,
        //            Date = t.Key.Date,
        //            TemplateCount = t.Count()

        //        });

        //    var queryResult = await groupedQuery.ToListAsync();

        //    var responseAreaQuery = responseAreaService.Get();

        //    if (responseAreas != null && responseAreas.Count() > 0)
        //        responseAreaQuery = responseAreaQuery.Where(t => responseAreas.Any(x => x == t.Code));

        //    var allResponseArea = await responseAreaQuery.ToListAsync();

        //    //if (!allResponseArea.Any())
        //    //    return NoContent();

        //    var response = new List<StatResponseAreaWorkLoadResponse>();

        //    allResponseArea.ForEach(respArea =>
        //    {
        //        var workLoads = daysList.Select(t => new StatWorkLoadDataResponse
        //        {
        //            Date = t,
        //            TemplateCount = queryResult.FirstOrDefault(x => x.ResponseAreaCode == respArea.Code && DateOnly.FromDateTime(x.Date) == t)?.TemplateCount ?? 0
        //        }).OrderBy(t => t.Date).ToList();

        //        response.Add(
        //            new StatResponseAreaWorkLoadResponse
        //            {
        //                ResponseArea = mapper.Map<ResponseAreaResponse>(respArea),
        //                WorkLoad = workLoads
        //            });
        //    });

        //    response = response.OrderBy(t => t.ResponseArea.Code).ToList();

        //    return response;
        //}

    }
}
