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 FMSAdmin.Controllers {
    [Authorize]
    [ApiController]
    [ApiVersion("1")]
    [Route("api/[controller]")]
    public class WorkOrderController : Controller {
        private readonly ILogger<WorkOrderController> _logger;
        private readonly FMSContext _context;
        private readonly WorkOrderService _service;
        private readonly StorageHelper _storage;

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


        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet]
        public IActionResult List([FromQuery]PagingRequest req) {
            var query = _FilterAndSort(req);
            query = query.Where(
                x => (x.FmsWorkRequest.WorkProgressId == 3 || x.FmsWorkRequest.WorkProgressId == 7) // 작업대기 혹은 보류
            );
            var list = _ListSelect(query);

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

        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet]
        private dynamic _ListSelect(IQueryable<FmsWorkOrder> query) {

            var list = query.Select(x => new {
                x.SiteId,
                Site = x.Site.Name,
                x.WorkRequestId,
                x.FmsWorkRequest.WorkProgressId,
                WorkProgress = x.FmsWorkRequest.WorkProgress.Name,
                x.FmsWorkRequest.WorkTypeId,
                WorkType = x.FmsWorkRequest.WorkType.Name,
                x.BusinessFieldId,
                BusinessField = x.CmBusinessField.Name,
                x.Title,
                x.Content,
                x.OrderDate,
                x.StartWorkDate,
                x.OrderUserId,
                OrderUser = x.CmUser.Name
            });
            return list;
        }

        [HttpGet("[action]")]
        public IActionResult Get([FromQuery] string siteId, [FromQuery] string workRequestId) {
            var query = _service.GetAll()
                .Where(x => x.SiteId == Util.ToInt(siteId) && x.WorkRequestId == Util.ToInt(workRequestId));
            var item = query.Select(x => new {
                x.SiteId,
                CmSite = new {
                    x.Site.Name
                },
                x.WorkRequestId,
                x.FmsWorkRequest.WorkProgressId,
                WorkProgress = new {
                    x.FmsWorkRequest.WorkProgress.Name
                },
                x.FmsWorkRequest.WorkTypeId,
                WorkType = new {
                    x.FmsWorkRequest.WorkType.Name
                },
                WorkDetailType = new {
                    x.FmsWorkRequest.WorkDetailType.Name,
                    x.FmsWorkRequest.WorkDetailType.Code,
                },
                x.BusinessFieldId,
                BusinessField = new {
                    x.CmBusinessField.Name
                },
                x.Title,
                x.Content,
                RequestContent = x.FmsWorkRequest.Content,
                x.OrderDate,
                WorkDueDate = (x.FmsWorkRequest.FmsWorkSchedule == null ? x.FmsWorkRequest.StartWorkDate : x.FmsWorkRequest.FmsWorkSchedule.WorkDueDate),
                x.StartWorkDate,
                x.OrderUserId,
                OrderUser = new {
                    x.CmUser.Name
                },
                FmsWorkResult = new {
                    x.FmsWorkResult.SiteId,
                    x.FmsWorkResult.WorkRequestId,
                    x.FmsWorkResult.WorkerUserId,
                    x.FmsWorkResult.StartDate,
                    x.FmsWorkResult.EndDate,
                    x.FmsWorkResult.Content
                },
                FmsWorkOrderToFacility = x.FmsWorkOrderToFacility.Select(f => new {
                    f.SiteId,
                    f.WorkRequestId,
                    f.FacilityCode,
                    CmFacility = new {
                        f.CmFacility.Name,
                        f.CmFacility.BuildingId,
                        CmBuilding = new {
                            f.CmFacility.CmBuilding.Name,
                        },
                        f.CmFacility.FloorId,
                        CmFloor = new {
                            f.CmFacility.CmFloor.Name,
                        },
                        f.CmFacility.FirstClassId,
                        FirstClassName = new {
                            f.CmFacility.FmsFacilityCodeClass.Name,
                        },
                        f.CmFacility.SecondClassId,
                        SecondClassName = new {
                            f.CmFacility.FmsFacilityCodeClass1.Name,
                        },
                        f.CmFacility.ThirdClassId,
                        ThirdClassName = new {
                            f.CmFacility.FmsFacilityCodeClass2.Name,
                        },
                    },
                }).ToList(),
                FmsWorkRequestToAccident = x.FmsWorkRequest.FmsWorkRequestToAccident.Select(f => new {
                    f.SiteId,
                    f.WorkRequestId,
                    f.AccidentId,
                    FmsAccident = new {
                        f.FmsAccident.SiteId,
                        f.FmsAccident.AccidentId,
                        f.FmsAccident.Name,
                        f.FmsAccident.AccidentTypeId,
                        AccidentTypeName = f.FmsAccident.FmsAccidentCodeType.Name,
                        Dates = new {
                            StartDate = f.FmsAccident.StartDate == null ? null : ((DateTime)f.FmsAccident.StartDate).ToString("yyyy.MM.dd"),
                            EndDate = f.FmsAccident.EndDate == null ? null : ((DateTime)f.FmsAccident.EndDate).ToString("yyyy.MM.dd"),
                        },
                        f.FmsAccident.DepartmentId,
                        DepartmentName = f.FmsAccident.CmDepartment.Name,
                        f.FmsAccident.AccidentLocation,
                    },
                }).ToList(),
            }).FirstOrDefault();
            return Ok(item);
        }

        [HttpPost("[action]")]
        public IActionResult Process([FromBody]FmsWorkResult data) {
            _service.Process(data);
            return Ok();
        }

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

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

            if (req.siteId != null)
                query = query.Where(x => x.SiteId == req.siteId);


            // 업무분야 필드가 있는경우만 추가
            if (req.businessFieldId != null) {
                query = query.Where(x => x.SiteId == req.siteId);
                query = query.Where(x => x.BusinessFieldId == req.businessFieldId || x.CmBusinessField.Name == "공통");
            }

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

            return query;
        }

    }
}