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

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

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

        /// <summary>
        /// 작업진행목록 / 작업완료목록 조회
        /// </summary>
        [HttpGet]
        public IActionResult List([FromQuery] PagingRequest req, [FromQuery] string siteId, [FromQuery] string workProgressId, bool businessAuth) {
            int nWorkProgressId = 0;
            int.TryParse(workProgressId, out nWorkProgressId);
            if (nWorkProgressId != 0 && nWorkProgressId != 4 && nWorkProgressId != 5) {
                throw new ServiceException("입력 파라메터가 잘못되었습니다.(WorkProgress:0/4/5)");
            }

            var query = _FilterAndSort(req);
            query = BusinessFieldHelper.Apply<FmsWorkResult>(_context, User, businessAuth, query, "FmsWorkOrder");
            query = query.Where(
                x => x.SiteId == Util.ToInt(siteId)
            );
            if (nWorkProgressId == 4) {
                // 작업진행 목록에서는 작업진행(4), 작업보류(7) 데이터를 조회
                query = query.Where(x => (x.FmsWorkRequest.WorkProgressId == 4 || x.FmsWorkRequest.WorkProgressId == 7));
            }
            if (nWorkProgressId == 5) {
                // 작업완료 목록에서는 작업완료(5) 데이터를 조회
                query = query.Where(x => x.FmsWorkRequest.WorkProgressId == 5);
            }
            if (nWorkProgressId == 0) {
                // 작업진행/작업완료 통합에 의해 작업진행(4), 작업완료(5), 작업보류 데이터조회 되도록
                query = query.Where(x => (new int[] { 4, 5, 7 }).Contains(x.FmsWorkRequest.WorkProgressId));
            }
            var list = query.Select(x => new {
                x.SiteId,
                x.WorkRequestId,
                x.FmsWorkRequest.WorkProgressId,
                WorkProgress = new {
                    x.FmsWorkRequest.WorkProgress.Name
                },
                x.FmsWorkRequest.WorkTypeId,
                WorkType = new {
                    x.FmsWorkRequest.WorkType.Name
                },
                x.FmsWorkOrder.BusinessFieldId,
                BusinessField = new {
                    x.FmsWorkOrder.CmBusinessField.Name
                },
                x.FmsWorkOrder.Title,
                x.Content,
                OrderContent = x.FmsWorkOrder.Content,
                RequestContent = x.FmsWorkRequest.Content,
                x.StartDate,
                x.EndDate,
                x.FmsWorkOrder.OrderDate,
                x.FmsWorkOrder.StartWorkDate,
                x.FmsWorkOrder.OrderUserId,
                OrderUser = new {
                    x.FmsWorkOrder.CmUser.Name
                },
                x.WorkerUserId,
                WorkerUser = new {
                    x.CmUserNavigation.Name
                },
                x.IsConfirmed,
                x.ConfirmedUserId,
                ConfirmedUser = new {
                    x.CmUser.Name
                },
                WorkPartnerName = x.FmsWorkRequest.WorkPartner.Name,
                x.FmsWorkRequest.WorkPrice,
                x.FmsWorkRequest.WorkItem,
                x.FmsWorkRequest.WorkEndDate,
                HasCheckItem = x.FmsWorkResultCheckItem.Any()
            });
            var paging = PagingList.Pagination(list, req.page, req.limit);
            return Ok(paging);
        }

        /// <summary>
        /// 작업진행달력
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult CalendarList([FromQuery] PagingRequest req, [FromQuery] string siteId, [FromQuery] int year, [FromQuery] int month, bool businessAuth) {
            DateTime target = new DateTime(year, month, 1);
            DateTime start = target.AddMonths(-1);
            DateTime end = target.AddMonths(2).AddDays(-1);

            var query = _FilterAndSort(req);
            query = BusinessFieldHelper.Apply<FmsWorkResult>(_context, User, businessAuth, query, "FmsWorkOrder");
            query = query.Where(
                x => x.SiteId == Util.ToInt(siteId)
                && (new int[] { 4, 7 }).Contains(x.FmsWorkRequest.WorkProgressId)
                && x.StartDate <= end
                && x.EndDate >= start
            );
            var list = query.Select(x => new {
                x.SiteId,
                x.WorkRequestId,
                x.FmsWorkRequest.WorkProgressId,
                WorkProgress = new {
                    x.FmsWorkRequest.WorkProgress.Name
                },
                x.FmsWorkRequest.WorkTypeId,
                WorkTypeName = x.FmsWorkRequest.WorkType.Name,
                x.FmsWorkOrder.BusinessFieldId,
                BusinessField = new {
                    x.FmsWorkOrder.CmBusinessField.Name
                },
                x.FmsWorkOrder.Title,
                x.Content,
                OrderContent = x.FmsWorkOrder.Content,
                RequestContent = x.FmsWorkRequest.Content,
                x.StartDate,
                x.EndDate,
                x.FmsWorkOrder.OrderDate,
                x.FmsWorkOrder.StartWorkDate,
                x.FmsWorkOrder.OrderUserId,
                OrderUser = new {
                    x.FmsWorkOrder.CmUser.Name
                },
                x.WorkerUserId,
                WorkerUser = new {
                    x.CmUserNavigation.Name
                },
                x.IsConfirmed,
                x.ConfirmedUserId,
                ConfirmedUser = new {
                    x.CmUser.Name
                },
            });
            return Ok(list);
        }

        /// <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.FmsWorkRequest.WorkScheduleId,
                x.FmsWorkRequest.WorkProgressId,
                x.FmsWorkRequest.WorkDetailTypeId,
                WorkDetailType = new {
                    x.FmsWorkRequest.WorkDetailType.Code,
                    x.FmsWorkRequest.WorkDetailType.Name,
                },
                WorkProgress = new {
                    x.FmsWorkRequest.WorkProgress.Name
                },
                x.FmsWorkRequest.WorkTypeId,
                WorkType = new {
                    x.FmsWorkRequest.WorkType.Name
                },
                x.FmsWorkOrder.BusinessFieldId,
                BusinessField = new {
                    x.FmsWorkOrder.CmBusinessField.Name
                },
                x.FmsWorkOrder.Title,
                x.Content,
                FmsWorkOrder = new {
                    x.FmsWorkOrder.Content,
                },
                FmsWorkRequest = new {
                    x.FmsWorkRequest.Content,
                },
                x.StartDate,
                x.EndDate,
                x.FmsWorkOrder.OrderDate,
                x.FmsWorkOrder.StartWorkDate,
                WorkDueDate = (x.FmsWorkRequest.FmsWorkSchedule == null ? x.FmsWorkRequest.StartWorkDate : x.FmsWorkRequest.FmsWorkSchedule.WorkDueDate),
                x.FmsWorkOrder.OrderUserId,
                OrderUser = new {
                    x.FmsWorkOrder.CmUser.Name
                },
                x.WorkerUserId,
                WorkerUser = new {
                    x.CmUserNavigation.Name
                },
                x.IsConfirmed,
                x.ConfirmedUserId,
                ConfirmedUser = new {
                    x.CmUser.Name
                },
                x.ConfirmDesc,
                x.FmsWorkRequest.WorkPartnerId,
                WorkPartnerName = x.FmsWorkRequest.WorkPartner.Name,
                x.FmsWorkRequest.WorkPrice,
                x.FmsWorkRequest.WorkItem,
                x.FmsWorkRequest.WorkEndDate,
                CmFile = _storage.ParseFile(x.FmsWorkRequest.CmFile),
                HasCheckItem = x.FmsWorkResultCheckItem.Any(),
                FmsWorkResultToFacility = x.FmsWorkResultToFacility.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.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(),
                FmsWorkRequestToComplaint = x.FmsWorkRequest.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);
        }

        /// <summary>
        /// 작업내 사용 자재목록 조회
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult Materials([FromQuery] PagingRequest req, [FromQuery] string siteId, [FromQuery] string workRequestId) {
            var query = _context.FmsWorkResultCheckItemMaterial as IQueryable<FmsWorkResultCheckItemMaterial>;
            query = query.Filter(req.conditions);
            query = query.Sort(req.sort);
            query = query.Where(
                x => x.SiteId == Util.ToInt(siteId)
                && x.WorkRequestId == Util.ToInt(workRequestId)
            );
            var list = query.Select(x => new {
                x.FmsMaterial.Name,
                x.FmsMaterial.Standard,
                x.MaterialCount,
            });
            return Ok(list);
        }

        /// <summary>
        /// 작업이력 조회
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult CheckItems([FromQuery] PagingRequest req, [FromQuery] string siteId, [FromQuery] string workRequestId) {
            var query = _context.FmsWorkResultCheckItem as IQueryable<FmsWorkResultCheckItem>;
            query = query.Filter(req.conditions);
            query = query.Sort(req.sort);
            query = query.Where(
                x => x.SiteId == Util.ToInt(siteId)
                && x.WorkRequestId == Util.ToInt(workRequestId)
            );
            var list = query.Select(x => new {
                x.SiteId,
                x.WorkRequestId,
                x.CheckItemId,
                x.CheckDate,
                x.TextResult,
                x.BoolResult,
                CmFile1 = _storage.ParseFile(x.CmFile1),
                CmFile2 = _storage.ParseFile(x.CmFile2),
            });
            return Ok(list);
        }

        /// <summary>
        /// 작업이력 항목 조회 (이력 내 사용 자재목록 포함하여 조회)
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult GetCheckItem([FromQuery] string siteId, [FromQuery] string workRequestId, [FromQuery] string checkItemId) {
            var query = _context.FmsWorkResultCheckItem.AsExpandable() as IQueryable<FmsWorkResultCheckItem>;
            query = query.Where(
                x => x.SiteId == Util.ToInt(siteId)
                && x.WorkRequestId == Util.ToInt(workRequestId)
                && x.CheckItemId == Util.ToInt(checkItemId)
            );
            var item = query.Select(x => new {
                x.SiteId,
                x.WorkRequestId,
                x.CheckItemId,
                x.CheckDate,
                x.TextResult,
                x.BoolResult,
                CmFile1 = _storage.ParseFile(x.CmFile1),
                CmFile2 = _storage.ParseFile(x.CmFile2),
                WorkProgressId = x.FmsWorkResult.FmsWorkRequest.WorkProgressId,
                FmsWorkResultCheckItemMaterial = x.FmsWorkResultCheckItemMaterial.Select(f => new {
                    f.CheckItemId,
                    f.CheckItemMaterialId,
                    f.MaterialId,
                    f.MaterialCode,
                    f.MaterialCount,
                    f.Name,
                    FmsMaterial = new {
                        f.FmsMaterial.MaterialId,
                        f.FmsMaterial.MaterialCode,
                        f.FmsMaterial.Name,
                        f.FmsMaterial.Standard,
                        f.FmsMaterial.Unit,
                    },
                    StockCount = FmsMaterial.GetStockCount.Invoke(f.FmsMaterial),
                    StockAmount = FmsMaterial.GetStockAmount.Invoke(f.FmsMaterial),
                }).ToList()
            }).FirstOrDefault();
            return Ok(item);
        }

        /// <summary>
        /// 작업이력 저장 (완료처리 및 보류처리 포함)
        /// </summary>
        [HttpPost("[action]")]
        public IActionResult SaveCheckItem([FromBody] FmsWorkResultCheckItem data) {
            _logger.LogInformation("Save");
            //_logger.LogInformation(data.Dump());

            ModelState.RemoveStartOf("CmFile1");
            ModelState.RemoveStartOf("CmFile2");
            ModelState.RemoveStartOf("FmsWorkResultCheckItemMaterial");
            if (ModelState.IsValid) {
                _service.SaveCheckItem(data, User.Identity.Name);
            } else {
                return BadRequest(ModelState);
            }
            return Ok();
        }

        /// <summary>
        /// 작업진행(보류해제)
        /// </summary>
        [HttpPost("[action]")]
        public IActionResult Continue([FromBody] FmsWorkResult data) {
            _service.Continue(data);
            return Ok();
        }

        /// <summary>
        /// 작업완료
        /// </summary>
        [HttpPost("[action]")]
        public IActionResult Complete([FromBody] FmsWorkResult data) {
            _service.CompleteWithAdditionalData(data);
            return Ok();
        }

        /// <summary>
        /// 작업보류
        /// </summary>
        [HttpPost("[action]")]
        public IActionResult Hold([FromBody] FmsWorkRequest data) {
            _service.Hold(data);
            return Ok();
        }

        /// <summary>
        /// 승인
        /// </summary>
        [HttpPost("[action]")]
        public IActionResult Confirm([FromBody] FmsWorkResult data, [FromQuery] DateTime? date) {
            _service.Confirm(data, date);
            return Ok();
        }

        /// <summary>
        /// 차기작업 확정일자 및 현작업 종료일자 조회
        /// { WorkDueDate, EndDate }
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult GetAvailDueDate([FromQuery] string siteId, [FromQuery] string workRequestId) {
            return Ok(_service.GetAvailDueDate(Util.ToInt(siteId), Util.ToInt(workRequestId)));
        }

        [HttpDelete("{siteId}/{workRequestId}")]
        public IActionResult Delete(int siteId, int workRequestId) {
            _service.Delete(siteId, workRequestId);
            return Ok();
        }

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

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

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

            return query;
        }

    }
}