using AutoMapper;
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;

namespace PARR.API.Controllers.V1.Statistics
{
    /// <summary>
    /// Статистика загрузки регламентными работами по рабочим группам
    /// </summary>
    public class StatWorkGroupWorkLoadController : BaseApiController
    {
        private readonly ITemplateRepository templateService;
        //private readonly IWorkLoadService workLoadService;
        //private readonly IWorkGroupService workGroupService;
        private readonly IMapper mapper;
        private readonly ILogger<StatWorkGroupWorkLoadController> logger;

        public StatWorkGroupWorkLoadController(
            ITemplateRepository templateService,
            //IWorkLoadService workLoadService,
            //IWorkGroupService workGroupService,
            IMapper mapper,
            ILogger<StatWorkGroupWorkLoadController> logger
            )
        {
            this.templateService = templateService;
            //this.workLoadService = workLoadService;
            //this.workGroupService = workGroupService;
            this.mapper = mapper;
            this.logger = logger;
        }

        /*
        /// <summary>
        /// Статистика загрузки регламентными работами рабочих групп по ЗО
        /// </summary>
        /// <param name="responseAreaCode"></param>
        /// <param name="requestQuery"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatWorkGroupWorkLoad.Get)]
        public async Task<IActionResult> Get([FromRoute] int responseAreaCode, [FromQuery] WorkloadBaseQuery requestQuery)
        {
            var response = await GetStatisticsAsync(responseAreaCode, requestQuery);

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

        
        /// <summary>
        /// Статистика загрузки РГ по списку РГ
        /// </summary>
        /// <returns></returns>
        [HttpPost(ApiRoutes.StatWorkGroupWorkLoad.GetByWorkGroups)]
        public async Task<IActionResult> GetByWorkGroups([FromBody] StatWorkGroupsWorkLoadRequest request)
        {
            var response = await GetStatisticsAsync(null, request.Filter, request.WorkGroups);

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


        private async Task<List<StatWorkGroupWorkLoadResponse>> GetStatisticsAsync(int? responseAreaCode, WorkloadBaseQuery requestQuery, List<Guid>? workGroups = null)
        {
            //защита от дурака, чтоб не выгрузить всю БД
            if (responseAreaCode == null && (workGroups == null || workGroups.Count() == 0))
            {
                logger.LogWarning($"Пытались выполнить запрос получения статситики с нулевыми параметрами {nameof(responseAreaCode)}, {nameof(workGroups)}. Controller {nameof(StatWorkGroupWorkLoadController)}");
                return new List<StatWorkGroupWorkLoadResponse>();
            }


            var daysList = workLoadService.GetDatesForPeriod(requestQuery);

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

            query = workLoadService.FilterTemplatesQuery(query, requestQuery);

            if (responseAreaCode.HasValue)
                query = query.Where(t => t.Host!.WorkGroup!.ResponseAreaCode == responseAreaCode.Value);

            if (workGroups != null && workGroups.Count() > 0)
                query = query.Where(t => workGroups.Any(x => x == t.Host!.WorkGroupId.Value));


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

            var queryResult = await groupedQuery.ToListAsync();


            IQueryable<DAL.Models.WorkGroup> workGroupsQuery = workGroupService.Get()
                                            .Include(t => t.ResponseArea);

            if (responseAreaCode.HasValue)
                workGroupsQuery = workGroupsQuery.Where(t => t.ResponseAreaCode == responseAreaCode);

            if (workGroups != null && workGroups.Count() > 0)
                workGroupsQuery = workGroupsQuery.Where(t => workGroups.Any(x => x == t.Id));


            var allWorkGroups = await workGroupsQuery.ToListAsync();

            var response = new List<StatWorkGroupWorkLoadResponse>();

            allWorkGroups.ForEach(wg =>
            {
                var workLoads = daysList.Select(t => new StatWorkLoadDataResponse
                {
                    Date = t,
                    TemplateCount = queryResult.FirstOrDefault(x => x.WorkGroupId == wg.Id && DateOnly.FromDateTime(x.Date) == t)?.TemplateCount ?? 0
                }).OrderBy(t => t.Date).ToList();

                response.Add(new StatWorkGroupWorkLoadResponse
                {
                    WorkGroup = mapper.Map<WorkGroupResponse>(wg),
                    WorkLoad = workLoads
                });
            });

            response = response.OrderBy(t => t.WorkGroup.Name).ToList();

            return response;
        }
        */
    }
}
