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;

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

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

        [HttpGet]
        public IActionResult List([FromQuery]PagingRequest req, [FromQuery] string siteId, bool businessAuth) {
            var query = _FilterAndSort(req);

            query = BusinessFieldHelper.Apply<FmsWorkOrderToFacility>(_context, User, businessAuth, query, "FmsWorkOrder.FmsWorkRequest");
            query = query.Where(
                x => x.SiteId == Util.ToInt(siteId)
                && x.FmsWorkOrder.FmsWorkRequest.WorkProgressId == 6
            );

            var list = query.Select(x => new {
                x.SiteId,
                x.WorkRequestId,
                x.FacilityCode,
                x.CmFacility.FirstClassId,
                FirstClassName = x.CmFacility.FmsFacilityCodeClass.Name,
                x.CmFacility.SecondClassId,
                SecondClassName = x.CmFacility.FmsFacilityCodeClass1.Name,
                x.CmFacility.ThirdClassId,
                ThirdClassName = x.CmFacility.FmsFacilityCodeClass2.Name,
                x.CmFacility.Name,
                x.CmFacility.BuildingId,
                x.CmFacility.FloorId,
                FacilityTypeName = x.CmFacility.BemsFacilityType.Name,
                x.FmsWorkOrder.FmsWorkRequest.WorkTypeId,
                x.FmsWorkOrder.FmsWorkRequest.BusinessFieldId,
                x.FmsWorkOrder.Title,
                x.FmsWorkOrder.OrderDate,
                x.FmsWorkOrder.StartWorkDate,
                x.FmsWorkOrder.FmsWorkResult.StartDate,
                x.FmsWorkOrder.FmsWorkResult.EndDate,
                x.FmsWorkOrder.FmsWorkResult.ConfirmedUserId,
                x.FmsWorkOrder.FmsWorkResult.ConfirmedDate,
                x.FmsWorkOrder.FmsWorkRequest.WorkProgressId,
                RequestStartWorkDate = x.FmsWorkOrder.FmsWorkRequest.StartWorkDate,
                BusinessFieldName = x.FmsWorkOrder.FmsWorkRequest.CmBusinessField.Name,
                OrderUserName = x.FmsWorkOrder.CmUser.Name,
                WorkTypeName = x.FmsWorkOrder.FmsWorkRequest.WorkType.Name,
                OrderBusinessFieldName = x.FmsWorkOrder.CmBusinessField.Name,
                WorkProgressName = x.FmsWorkOrder.FmsWorkRequest.WorkProgress.Name,
                ConfirmedUserName = x.FmsWorkOrder.FmsWorkResult.CmUser.Name,
                WorkerUserName = x.FmsWorkOrder.FmsWorkResult.CmUserNavigation.Name,
                x.FmsWorkOrder.Content
            });
            var paging = PagingList.Pagination(list, req.page, req.limit);

            return Ok(paging);
        }


        [HttpGet("[action]")]
        public IActionResult Get([FromQuery] string siteId, [FromQuery] string workRequestId, [FromQuery] string facilityCode) {
            var query = _context.FmsWorkOrderToFacility as IQueryable<FmsWorkOrderToFacility>;

            query = query.Where(
                x => x.SiteId == Util.ToInt(siteId)
                && x.FacilityCode == Util.ToInt(facilityCode)
                && x.WorkRequestId == Util.ToInt(workRequestId)
            );

            var item = query.Select(x => new {
                x.SiteId,
                x.WorkRequestId,
                x.FacilityCode,
                x.CmFacility.FirstClassId,
                FirstClassName = x.CmFacility.FmsFacilityCodeClass.Name,
                x.CmFacility.SecondClassId,
                SecondClassName = x.CmFacility.FmsFacilityCodeClass1.Name,
                x.CmFacility.ThirdClassId,
                ThirdClassName = x.CmFacility.FmsFacilityCodeClass2.Name,
                x.CmFacility.Name,
                x.CmFacility.BuildingId,
                x.CmFacility.FloorId,
                FacilityTypeName = x.CmFacility.BemsFacilityType.Name,
                x.FmsWorkOrder.FmsWorkRequest.WorkTypeId,
                x.FmsWorkOrder.FmsWorkRequest.BusinessFieldId,
                x.FmsWorkOrder.Title,
                x.FmsWorkOrder.OrderDate,
                x.FmsWorkOrder.StartWorkDate,
                x.FmsWorkOrder.FmsWorkResult.StartDate,
                x.FmsWorkOrder.FmsWorkResult.EndDate,
                x.FmsWorkOrder.FmsWorkResult.ConfirmedUserId,
                x.FmsWorkOrder.FmsWorkResult.ConfirmedDate,
                x.FmsWorkOrder.FmsWorkRequest.WorkProgressId,
                RequestStartWorkDate = x.FmsWorkOrder.FmsWorkRequest.StartWorkDate,
                BusinessFieldName = x.FmsWorkOrder.FmsWorkRequest.CmBusinessField.Name,
                OrderUserName = x.FmsWorkOrder.CmUser.Name,
                WorkTypeName = x.FmsWorkOrder.FmsWorkRequest.WorkType.Name,
                OrderBusinessFieldName = x.FmsWorkOrder.CmBusinessField.Name,
                WorkProgressName = x.FmsWorkOrder.FmsWorkRequest.WorkProgress.Name,
                ConfirmedUserName = x.FmsWorkOrder.FmsWorkResult.CmUser.Name,
                WorkerUserName = x.FmsWorkOrder.FmsWorkResult.CmUserNavigation.Name,
                x.FmsWorkOrder.Content,
            }).FirstOrDefault();

            return Ok(item);
        }

        // 검색 & 정렬 공통
        private IQueryable<FmsWorkOrderToFacility> _FilterAndSort(PagingRequest req) {
            var query = _context.FmsWorkOrderToFacility as IQueryable<FmsWorkOrderToFacility>;

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

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

            return query;
        }

    }
}