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 FMSApp.Repositories;

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

        public WorkRequestController(
            ILogger<WorkRequestController> logger,
            FMSContext context,
            WorkRequestService service,
            StorageHelper storage,
            WorkConfigRepository workConfig
            ) {
            _logger = logger;
            _context = context;
            _service = service;
            _storage = storage;
            _workConfig = workConfig;
        }

        private IActionResult RequestList(PagingRequest req, string siteId, string workTypeId, bool businessAuth, int[] workProgressIds = null) {
            var query = _FilterAndSort(req);
            query = BusinessFieldHelper.Apply<FmsWorkRequest>(_context, User, businessAuth, query);
            query = query.Where(
                x => x.SiteId == Util.ToInt(siteId)
                && (x.FmsWorkSchedule == null || (x.FmsWorkSchedule != null && x.FmsWorkSchedule.IsUse == true))
                //&& ((x.FmsWorkSchedule != null && x.FmsWorkSchedule.IsUse == true) || !(new int[] { 1, 2, 7 }).Contains(x.WorkTypeId))
            );
            if (workProgressIds == null || workProgressIds.Length == 0) {
                query = query.Where(x => x.WorkProgressId == 1);
            } else {
                query = query.Where(x => workProgressIds.Contains(x.WorkProgressId));
            }
            if (!string.IsNullOrEmpty(workTypeId)) {
                query = query.Where(
                    x => x.WorkTypeId == Util.ToInt(workTypeId)
                );
            }
            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.WorkScheduleId,
                x.WorkProgressId,
                WorkProgress = new {
                    x.WorkProgress.Name
                },
                x.Title,
                x.Content,
                x.RequestUserId,
                CmUserNavigation = new {
                    x.CmUserNavigation.Name
                },
                x.RequestDate,
                x.StartWorkDate,
                x.RejectUserId,
                x.RejectDate,
                x.RejectReason,
                x.InspectionAgencyId,
                InspectionAgency = new {
                    x.CmPartner.Name
                },
                x.WorkPartnerId,
                WorkPartnerName = x.WorkPartner.Name,
                x.WorkPrice,
                x.WorkItem,
                x.WorkEndDate
            });
            var paging = PagingList.Pagination(list, req.page, req.limit);
            return Ok(paging);
        }

        /// <summary>
        /// 수시작업계획 목록
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult AnyList([FromQuery] PagingRequest req, [FromQuery] string siteId, bool businessAuth) {
            return RequestList(req, siteId, "5", businessAuth, new int[] { 1 });  // 계획
        }

        /// <summary>
        /// 공사작업계획 목록
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult ConstructList([FromQuery] PagingRequest req, [FromQuery] string siteId, bool businessAuth) {
            return RequestList(req, siteId, "6", businessAuth, new int[] { 1 });  // 계획
        }

        /// <summary>
        /// 실행계획 목록
        /// </summary>
        [HttpGet]
        public IActionResult List([FromQuery] PagingRequest req, [FromQuery] string siteId, string workTypeId, bool businessAuth) {
            return RequestList(req, siteId, workTypeId, businessAuth, new int[] { 1 }); // 계획
        }

        /// <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.WorkScheduleId,
                x.WorkProgressId,
                WorkProgress = new {
                    x.WorkProgress.Name
                },
                x.Title,
                x.Content,
                x.RequestUserId,
                CmUserNavigation = new {
                    x.CmUserNavigation.Name,
                },
                x.RequestDate,
                x.StartWorkDate,
                x.RejectUserId,
                x.RejectDate,
                x.RejectReason,
                x.InspectionAgencyId,
                InspectionAgency = new {
                    x.CmPartner.Name
                },
                x.WorkPartnerId,
                WorkPartnerName = x.WorkPartner.Name,
                x.WorkPrice,
                x.WorkItem,
                x.WorkEndDate,
                CmFile = _storage.ParseFile(x.CmFile),
                x.FmsWorkSchedule.CycleSize,
                x.FmsWorkSchedule.CycleUnitId,
                CycleUnitName = x.FmsWorkSchedule.FmsWorkCodeCycleUnit.Name ?? "",
                x.FmsWorkSchedule.HolidayWorkTypeId,
                HolidayWorkTypeName = x.FmsWorkSchedule.FmsWorkCodeHolidayWorkType.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,
                        AccidentTypeName = 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>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public IActionResult Save([FromBody] FmsWorkRequest data) {
            _logger.LogInformation("Save");
            //_logger.LogInformation(data.Dump());

            ModelState.RemoveStartOf("FmsWorkRequestToFacility");
            ModelState.RemoveStartOf("FmsWorkRequestToAccident");
            ModelState.RemoveStartOf("FmsWorkRequestToComplaint");

            if (ModelState.IsValid) {
                //_service.Save(data);
                _service.SaveBeforeAddHistory(data);
            } else {
                return BadRequest(ModelState);
            }
            return Ok();
        }

        /// <summary>
        /// 사고 내역 저장
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public IActionResult SaveAccidents([FromBody] FmsWorkRequest data) {
            ModelState.Remove("Title");
            ModelState.RemoveStartOf("FmsWorkRequestToFacility");
            ModelState.RemoveStartOf("FmsWorkRequestToAccident");
            ModelState.RemoveStartOf("FmsWorkRequestToComplaint");

            if (ModelState.IsValid) {
                _service.SaveAccidents(data);
            } else {
                return BadRequest(ModelState);
            }
            return Ok();
        }

        /// <summary>
        /// 민원 내역 저장
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public IActionResult SaveComplaints([FromBody] FmsWorkRequest data) {
            ModelState.Remove("Title");
            ModelState.RemoveStartOf("FmsWorkRequestToFacility");
            ModelState.RemoveStartOf("FmsWorkRequestToAccident");
            ModelState.RemoveStartOf("FmsWorkRequestToComplaint");

            if (ModelState.IsValid) {
                _service.SaveComplaints(data);
            } else {
                return BadRequest(ModelState);
            }
            return Ok();
        }

        [HttpPost("[action]")]
        public IActionResult Reject([FromBody] FmsWorkRequest data, [FromQuery] bool useSchedule, [FromQuery] DateTime? confirmDate) {
            _logger.LogInformation($"###########################################################################");
            _logger.LogInformation($"useSchedule: {useSchedule}, confirmDate: {confirmDate}");
            _service.Reject(data, useSchedule, confirmDate);
            return Ok();
        }

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

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

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

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

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

            return query;
        }

    }
}