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.Text;
using System.Collections.Generic;

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

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

        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet]
        public IActionResult List([FromQuery] PagingRequest req, [FromQuery] string siteId, bool businessAuth) {
            var query = _FilterAndSort(req);
            query = query.Where(x => x.SiteId == Util.ToInt(siteId));
            query = BusinessFieldHelper.Apply<BemsReportHistory>(_context, User, businessAuth, query, "BemsReportFormat");

            var list = query.Select(x => new {
                x.SiteId,
                x.Seq,
                x.CreateDate,
                x.ReportName,
                x.ReportFormatId,
                x.BemsReportFormat.BusinessFieldId,
                x.FormatName,
                x.Writer,
                x.Confirm1,
                x.Confirm2,
                x.FileName,
            });

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

        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult Get([FromQuery] string siteId, [FromQuery] string seq, [FromQuery] DateTime datetime, [FromQuery] string reportFormatId) {
            var history = _context.BemsReportHistory.Where(
                x => x.SiteId == Util.ToInt(siteId)
                && x.Seq == Util.ToInt(seq)
            ).FirstOrDefault();

            var builder = new StringBuilder();
            if (history != null) {
                foreach (var content in history.BemsReportHistoryContent.OrderBy(x => x.ContentId)) {
                    builder.Append(content.Content);
                }
            }

            return Ok(new {
                history.SiteId,
                history.Seq,
                history.CreateDate,
                history.ReportName,
                history.ReportFormatId,
                history.FormatName,
                history.Writer,
                ApproverUserStamp1 = history.ApproverUser1 != null ? _storage.ParseFile(history.ApproverUser1.CmFile1) : null,
                ApproverUserStamp2 = history.ApproverUser2 != null ? _storage.ParseFile(history.ApproverUser2.CmFile1) : null,
                history.Confirm1,
                history.Confirm2,
                ApproveDate1 = history.ApproveDate1 != null ? history.ApproveDate1.Value.ToString("yyyy-MM-dd") : "",
                ApproveDate2 = history.ApproveDate2 != null ? history.ApproveDate2.Value.ToString("yyyy-MM-dd") : "",
                history.FileName,
                BusinessFieldName = Util.V(history, x => x.BemsReportFormat.CmBusinessField.Name),
                Content = builder.ToString(),
                CmFile = _storage.ParseFile(history.CmFile),
            });
        }

        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult FacilityList([FromQuery] string siteId, [FromQuery] string seq) {
            var history = _context.BemsReportHistory.Where(
                x => x.SiteId == Util.ToInt(siteId)
                && x.Seq == Util.ToInt(seq)
            ).FirstOrDefault();

            if (history == null) return Ok(new List<CmFacility>());

            var list = _context.BemsReportFormatToFacility.Where(
                x => x.SiteId == history.SiteId
                && x.ReportFormatId == history.ReportFormatId
            ).Select(x => new {
                x.CmFacility.SiteId,
                x.CmFacility.FacilityCode,
                x.CmFacility.Name,
                x.CmFacility.Manufacturer,
                x.CmFacility.FacilityCapacity,
                BuildingName = x.CmFacility.CmBuilding.Name,
                FloorName = x.CmFacility.CmFloor.Name,
                FirstClassName = x.CmFacility.FmsFacilityCodeClass.Name,
                SecondClassName = x.CmFacility.FmsFacilityCodeClass1.Name,
                ThirdClassName = x.CmFacility.FmsFacilityCodeClass2.Name,
            }).ToList();

            return Ok(list);
        }

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

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

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

            return query;
        }

    }
}