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 WorkHistoryController : Controller {
        private readonly ILogger<WorkHistoryController> _logger;
        private readonly FMSContext _context;
        private readonly WorkRequestService _service;
        private readonly StorageHelper _storage;

        public WorkHistoryController(
            ILogger<WorkHistoryController> logger,
            FMSContext context,
            WorkRequestService 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) {

            _logger.LogInformation("===========================");
            _logger.LogInformation(req.Dump());
            _logger.LogInformation("===========================");

            var query = _FilterAndSort(req);
            query = BusinessFieldHelper.Apply<FmsWorkRequest>(_context, User, businessAuth, query);
            query = query.Where(
                x => x.SiteId == Util.ToInt(siteId)
                && x.WorkProgressId > 1 // 작업계획 이후의 모든 프로세스
                && (x.FmsWorkSchedule == null || (x.FmsWorkSchedule != null && x.FmsWorkSchedule.IsUse == true))
            );
            var list = query.Select(x => new {
                x.SiteId,
                x.WorkRequestId,
                x.WorkTypeId,
                WorkType = new {
                    x.WorkType.Name
                },
                x.WorkDetailTypeId,
                WorkDetailType = new {
                    x.WorkDetailType.Code,
                    x.WorkDetailType.Name,
                },
                x.BusinessFieldId,
                BusinessField = new {
                    x.CmBusinessField.Name
                },
                x.WorkProgressId,
                WorkProgress = new {
                    x.WorkProgress.Name
                },
                x.Title,
                x.Content,
                x.RequestUserId,
                RequestUserName = x.CmUserNavigation.Name,
                x.RequestDate,
                x.StartWorkDate,
                x.RejectUserId,
                RejectUserName = x.CmUser.Name,
                x.RejectDate,
                x.RejectReason,
                x.InspectionAgencyId,
                InspectionAgencyName = x.CmPartner.Name,
                x.WorkScheduleId,
                x.WorkPartnerId,
                WorkPartnerName = x.WorkPartner.Name,
                x.WorkPrice,
                x.WorkItem,
                x.WorkEndDate,
                FmsWorkOrder = new {
                    x.FmsWorkOrder.OrderDate,
                    x.FmsWorkOrder.Content,
                },
                FmsWorkResult = new {
                    x.FmsWorkResult.StartDate,
                    x.FmsWorkResult.EndDate,
                    x.FmsWorkResult.ConfirmedDate,
                    x.FmsWorkResult.ConfirmedUserId,
                    x.FmsWorkResult.IsConfirmed,
                    x.FmsWorkResult.CauseClassId,
                    x.FmsWorkResult.Content,
                    x.FmsWorkResult.ConfirmDesc,
                    ConfirmUserName = x.FmsWorkResult.CmUser.Name,
                    WorkerUserName = x.FmsWorkResult.CmUserNavigation.Name,
                },
            });
            var paging = PagingList.Pagination(list, req.page, req.limit);
            return Ok(paging);
        }

        /// <summary>
        /// 작업이력 상세 조회
        /// </summary>
        [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,
                x.WorkRequestId,
                x.WorkTypeId,
                WorkType = new {
                    x.WorkType.Name
                },
                x.WorkDetailTypeId,
                WorkDetailType = new {
                    x.WorkDetailType.Code,
                    x.WorkDetailType.Name,
                },
                x.BusinessFieldId,
                BusinessField = new {
                    x.CmBusinessField.Name
                },
                x.WorkProgressId,
                WorkProgress = new {
                    x.WorkProgress.Name
                },
                x.Title,
                x.Content,
                x.RequestUserId,
                RequestUserName = x.CmUserNavigation.Name,
                x.RequestDate,
                x.StartWorkDate,
                x.RejectUserId,
                RejectUserName = x.CmUser.Name,
                x.RejectDate,
                x.RejectReason,
                x.InspectionAgencyId,
                InspectionAgencyName = x.CmPartner.Name,
                x.WorkScheduleId,
                x.WorkPartnerId,
                WorkPartnerName = x.WorkPartner.Name,
                x.WorkPrice,
                x.WorkItem,
                x.WorkEndDate,
                x.WorkUsers,
                CmFile = _storage.ParseFile(x.CmFile),
                FmsWorkOrder = new {
                    x.FmsWorkOrder.OrderDate,
                    x.FmsWorkOrder.Content,
                },
                FmsWorkResult = new {
                    x.FmsWorkResult.StartDate,
                    x.FmsWorkResult.EndDate,
                    x.FmsWorkResult.ConfirmedDate,
                    x.FmsWorkResult.ConfirmedUserId,
                    x.FmsWorkResult.IsConfirmed,
                    x.FmsWorkResult.CauseClassId,
                    x.FmsWorkResult.Content,
                    x.FmsWorkResult.ConfirmDesc,
                    ConfirmUserName = x.FmsWorkResult.CmUser.Name,
                    WorkerUserName = x.FmsWorkResult.CmUserNavigation.Name,
                },
                FmsWorkRequestToFacility = x.FmsWorkRequestToFacility.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,
                        FirstClass = new {
                            f.CmFacility.FmsFacilityCodeClass.Name,
                        },
                        f.CmFacility.SecondClassId,
                        SecondClass = new {
                            f.CmFacility.FmsFacilityCodeClass1.Name,
                        },
                        f.CmFacility.ThirdClassId,
                        ThirdClass = new {
                            f.CmFacility.FmsFacilityCodeClass2.Name,
                        },
                    },
                }).ToList(),
                FmsWorkRequestToAccident = x.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(),
                FmsWorkRequestToComplaint = x.FmsWorkRequestToComplaint.Select(f => new {
                    f.SiteId,
                    f.WorkRequestId,
                    f.ComplaintId,
                    FmsComplaints = new {
                        f.FmsComplaints.SiteId,
                        f.FmsComplaints.ComplaintId,
                        f.FmsComplaints.Name,
                        f.FmsComplaints.ComplaintTypeId,
                        ComplaintTypeName = f.FmsComplaints.FmsComplaintCodeType.Name,
                        Dates = new {
                            StartDate = f.FmsComplaints.StartDate == null ? null : ((DateTime)f.FmsComplaints.StartDate).ToString("yyyy.MM.dd"),
                            EndDate = f.FmsComplaints.EndDate == null ? null : ((DateTime)f.FmsComplaints.EndDate).ToString("yyyy.MM.dd"),
                        },
                        f.FmsComplaints.DepartmentId,
                        DepartmentName = f.FmsComplaints.CmDepartment.Name,
                        f.FmsComplaints.ComplaintLocation,
                    },
                }).ToList(),
            }).FirstOrDefault();
            return Ok(item);
        }

        // 검색 & 정렬 공통
        private IQueryable<FmsWorkRequest> _FilterAndSort(PagingRequest req) {

            var query = _service.GetAll();

            // 시설유형 검색조건 처리
            if (req != null && req.conditions != null) {
                var cond = req.conditions.Where(x => x.field == "FacilityTypeId").FirstOrDefault();
                if (cond != null && !string.IsNullOrEmpty(cond.op) && !string.IsNullOrEmpty(cond.value)) {
                    query = query.Where(
                        x => _context.FmsWorkRequestToFacility.Where(
                            y => y.SiteId == x.SiteId
                            && y.WorkRequestId == x.WorkRequestId
                            && y.CmFacility.FacilityTypeId == Util.ToInt(cond.value)
                        ).Count() > 0
                    );
                }
            }

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

            // 기본 Entity 정렬
            if (Util.V(req, x => x.sort.field) == "Custom") {
                query = query.OrderByDescending(x => x.FmsWorkResult.StartDate).ThenBy(x => x.Title);
            } else {
                query = query.Sort(req.sort);
            }

            return query;
        }

    }
}