using System;
using System.Linq;
using System.Threading.Tasks;

using FMSAdmin.Data;
using FMSAdmin.Models;
using FMSAdmin.Entities;
using FMSApp.Services;

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using FMSAdmin.Helpers;
using System.Data;
using System.IO;
using OfficeOpenXml;
using System.Collections;
using System.Collections.Generic;

namespace FMSApp.Controllers {
    [Authorize]
    [ApiController]
    [ApiVersion("1")]
    [Route("api/app/[controller]")]
    public class FacilityTimeController : Controller {
        private readonly ILogger<FacilityTimeController> _logger;
        private readonly FMSContext _context;
        private readonly FacilityTimeService _service;
        private readonly StorageHelper _storage;

        public FacilityTimeController(
            ILogger<FacilityTimeController> logger,
            FMSContext context,
            FacilityTimeService service,
            StorageHelper storage
            ) {
            _logger = logger;
            _context = context;
            _service = service;
            _storage = storage;
        }

        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet]
        public IActionResult List([FromQuery]PagingRequest req, [FromQuery] string siteId, [FromQuery] string facilityTypeId, [FromQuery] string propertyId, [FromQuery] string sDate, [FromQuery] string eDate) {
            DateTime startDate = DateTime.Parse(sDate);
            DateTime endDate = DateTime.Parse(eDate);

            var query = _FilterAndSort(req);

            if (!string.IsNullOrEmpty(siteId)) {
                query = query.Where(x => x.SiteId == Util.ToInt(siteId));
            }
            if (!string.IsNullOrEmpty(facilityTypeId)) {
                query = query.Where(x => x.FacilityTypeId == Util.ToInt(facilityTypeId));
            }
            if (!string.IsNullOrEmpty(propertyId)) {
                query = query.Where(x => x.PropertyId == Util.ToInt(propertyId));
            }
            query = query.Where(x => x.CreatedDateTime >= startDate)
                         .Where(x => x.CreatedDateTime <= endDate);

            var list = query.GroupBy(x => new { x.FacilityCode, x.CmFacility.Name })
                             .Select(x => new { FacilityCode = x.Key.FacilityCode, Name = x.Key.Name, Value = x.Sum(v => v.DailyValue) }).ToList();
            if (list.Count() > 0) {
                return Ok(new {
                    total = list.Count(),
                    page = 1,
                    limit = 0,
                    list = list,
                    maxValue = list.Select(x => x.Value).Max()
                });
            } else {
                IList emptyArr = new List<string>();
                return Ok(new {
                    total = 0,
                    page = 1,
                    limit = 0,
                    list = emptyArr,
                    maxValue = 0
                });
            }
            // var paging = PagingList.Pagination(list, req.page, req.limit);
            // return Ok(paging);
        }
        [HttpGet("[action]")]
        public IActionResult Detail([FromQuery]PagingRequest req, [FromQuery] string siteId, [FromQuery] string facilityTypeId, [FromQuery] string propertyId, [FromQuery] string facilityCode, [FromQuery] string sDate, [FromQuery] string eDate) {
            DateTime startDate = DateTime.Parse(sDate);
            DateTime endDate = DateTime.Parse(eDate);

            var query = _FilterAndSort(req);

            if (!string.IsNullOrEmpty(siteId)) {
                query = query.Where(x => x.SiteId == Util.ToInt(siteId));
            }
            if (!string.IsNullOrEmpty(facilityTypeId)) {
                query = query.Where(x => x.FacilityTypeId == Util.ToInt(facilityTypeId));
            }
            if (!string.IsNullOrEmpty(propertyId)) {
                query = query.Where(x => x.PropertyId == Util.ToInt(propertyId));
            }
            if (!string.IsNullOrEmpty(facilityCode)) {
                query = query.Where(x => x.FacilityCode == Util.ToInt(facilityCode));
            }

            query = query.Where(x => x.CreatedDateTime >= startDate)
                         .Where(x => x.CreatedDateTime <= endDate);

            var list = query.Select(x => new {
                Date = new {
                    Date = x.CreatedDateTime.ToString("yyyy.MM.dd")
                },
                Facility = new {
                    Name = x.CmFacility.Name
                },
                Value = x.DailyValue,
            }).ToList();
            string aa = list.Select(x => x.Facility.Name).FirstOrDefault();
            if (list.Count() > 0) {
                return Ok(new {
                    total = list.Count(),
                    page = 1,
                    limit = 0,
                    name = list.Select(x => x.Facility.Name).FirstOrDefault(),
                    maxValue = list.Select(x => x.Value).Max(),
                    list = list


                });
            } else {
                IList emptyArr = new List<string>();
                return Ok(new {
                    total = 0,
                    page = 1,
                    limit = 0,
                    name = "",
                    maxValue = 0,
                    list = emptyArr
                });
            }
            // var paging = PagingList.Pagination(list, req.page, req.limit);
            // return Ok(paging);
        }





        // 검색 & 정렬 공통
        private IQueryable<BemsMonitoringPointHistoryDaily> _FilterAndSort(PagingRequest req) {
            var query = _service.GetAll();

            // 기본 Entity 검색
            query = query.Filter(req.conditions);

            // 기본 Entity 정렬
            query = query.Sort(req.sort);

            return query;
        }

    }
}