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

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

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

namespace FMSAdmin.Controllers {
    [Authorize]
    [ApiController]
    [ApiVersion("1")]
    [Route("api/[controller]")]
    public class AlarmMonitoringPointHistoryController : Controller {
        private readonly ILogger<AlarmMonitoringPointHistoryController> _logger;
        private readonly FMSContext _context;
        private readonly AlarmPointService _service;

        public AlarmMonitoringPointHistoryController(
            ILogger<AlarmMonitoringPointHistoryController> logger,
            FMSContext context,
            AlarmPointService service
            ) {
            _logger = logger;
            _context = context;
            _service = service;
        }

        /// <summary>
        /// 리스트
        /// </summary>
        /// <param name="req"></param>
        /// <param name="siteId"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult List([FromQuery] PagingRequest req) {
            var query = _FilterAndSort(req);

            var list = _ListSelect(query);

            var paging = PagingList.Pagination(list, req.page, req.limit);
            return Ok(paging);
        }

        /// <summary>
        /// 엑셀파일 익스포트
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpGet("excel")]
        public IActionResult ExportExcel([FromQuery] PagingRequest req, string filename) {
            req.page = 1;
            req.limit = 0;
            var query = _FilterAndSort(req);

            var list = _ListSelect(query);

            var stream = new MemoryStream();
            using (var package = new ExcelPackage(stream)) {
                var workSheet = package.Workbook.Worksheets.Add("Sheet1");

                workSheet.Cells.LoadFromCollection(list, true);

                if (req.columns != null && req.columns.Length > 0) {
                    workSheet.AddStyle(req.columns, req.sort?.order?.ToLower() == "asc", filename);
                }
                package.Save();
            }
            stream.Position = 0;
            string excelName = $"excel-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xlsx";
            return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", excelName);
        }

        // 셀렉트 공통
        private dynamic _ListSelect(IQueryable<BemsMonitoringPointHistory15min> query) {
            var list = query.Select(x => new {
                x.SiteId,
                CreatedDateTime = x.CreatedDateTime.ToString("yyyy/MM/dd H:mm"),
                SiteName = x.Site.Name,
                x.FacilityTypeId,
                FacilityTypeName = x.FacilityType.Name,
                x.FacilityCode,
                FacilityName = x.BemsMonitoringPoint.CmFacility.Name,
                x.PropertyId,
                MonitoringPointName = x.BemsMonitoringPoint.Name,
                x.CurrentValue,

            });

            return list;
        }

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

            query = query.Filter(req.conditions);
            if (req.siteId != null) {
                query = query.Where(x => x.SiteId == Util.ToInt(req.siteId));
            }
            if (req.siteIds != null && req.siteIds.Length > 0) {
                query = query.Where(x => req.siteIds.Contains(x.SiteId));
            }
            query = query.Sort(req.sort);

            return query;
        }

    }

}

