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 Microsoft.AspNetCore.Mvc.ModelBinding;

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

        public WorkScheduleController(
            ILogger<WorkScheduleController> logger,
            FMSContext context,
            WorkScheduleService service,
            WorkRequestService requestService,
            StorageHelper storage
            ) {
            _logger = logger;
            _context = context;
            _service = service;
            _requestService = requestService;
            _storage = storage;
        }

        /// <summary>
        /// 정기점검 계획 목록
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult RegularListFromRequest([FromQuery] PagingRequest req, [FromQuery] string siteId, bool businessAuth) {
            return ListFromRequest(req, siteId, new int[] { 1 }, businessAuth);
        }

        /// <summary>
        /// 법정검사/법정교육 계획 목록
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult LegalListFromRequest([FromQuery] PagingRequest req, [FromQuery] string siteId, bool businessAuth) {
            return ListFromRequest(req, siteId, new int[] { 2, 7 }, businessAuth);
        }

        private IActionResult ListFromRequest(PagingRequest req, string siteId, int[] workTypeIds, bool businessAuth) {
            var query = _FilterAndSortFromRequest(req);
            query = query.Where(
                x => x.SiteId == Util.ToInt(siteId)
                && workTypeIds.Contains(x.WorkTypeId)
                && x.WorkProgressId == 1
            );
            query = BusinessFieldHelper.Apply<FmsWorkRequest>(_context, User, businessAuth, query);

            var list = query.Select(x => new {
                x.SiteId,
                x.WorkRequestId,
                x.WorkTypeId,
                WorkType = new {
                    x.WorkType.Name
                },
                x.BusinessFieldId,
                BusinessField = new {
                    x.CmBusinessField.Name
                },
                x.InspectionAgencyId,
                InspectionAgency = new {
                    x.CmPartner.Name
                },
                x.Title,
                x.StartWorkDate,
                x.RequestUserId,
                WorkPartnerName = x.WorkPartner.Name,
                x.WorkPrice,
                x.WorkItem,
                x.WorkEndDate,
                x.FmsWorkSchedule.WorkScheduleId,
                x.FmsWorkSchedule.CycleSize,
                x.FmsWorkSchedule.CycleUnitId,
                CycleUnitName = x.FmsWorkSchedule.FmsWorkCodeCycleUnit.Name,
                x.FmsWorkSchedule.HolidayWorkTypeId,
                HolidayWorkTypeName = x.FmsWorkSchedule.FmsWorkCodeHolidayWorkType.Name,
            });
            var paging = PagingList.Pagination(list, req.page, req.limit);
            return Ok(paging);
        }

        private IQueryable<FmsWorkRequest> _FilterAndSortFromRequest(PagingRequest req) {
            var query = _requestService.GetAll();

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

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

            return query;
        }

        [HttpGet("[action]")]
        public IActionResult RegularFromRequest([FromQuery] string siteId, [FromQuery] string workScheduleId) {
            return GetFromRequest(siteId, workScheduleId, 1);
        }

        [HttpGet("[action]")]
        public IActionResult LegalFromRequest([FromQuery] string siteId, [FromQuery] string workScheduleId) {
            return GetFromRequest(siteId, workScheduleId, 2);
        }

        private IActionResult GetFromRequest(string siteId, string workScheduleId, int workTypeId) {
            var query = _requestService.GetAll()
                .Where(x => x.SiteId == Util.ToInt(siteId) && x.WorkScheduleId == Util.ToInt(workScheduleId));
            var item = query.Select(x => new {
                x.SiteId,
                x.WorkScheduleId,
                x.WorkTypeId,
                WorkType = new {
                    x.WorkType.Name
                },
                x.BusinessFieldId,
                BusinessField = new {
                    x.CmBusinessField.Name
                },
                x.InspectionAgencyId,
                InspectionAgency = new {
                    x.CmPartner.Name
                },
                x.Title,
                x.StartWorkDate,
                x.RequestUserId,
                x.WorkPartnerId,
                WorkPartnerName = x.WorkPartner.Name,
                x.WorkPrice,
                x.WorkItem,
                x.WorkEndDate,
                CmFile = _storage.ParseFile(x.CmFile),
                FmsWorkRequestToFacility = x.FmsWorkRequestToFacility.Select(f => new {
                    f.SiteId,
                    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()
            }).FirstOrDefault();
            return Ok(item);
        }

        [HttpPost("[action]")]
        public IActionResult SaveExpectedRequest([FromBody] FmsWorkSchedule data) {
            _logger.LogInformation("SaveExpectedRequest");
            //_logger.LogInformation(data.Dump());

            ModelState.RemoveStartOf("FmsWorkScheduleToFacility");
            ModelState.RemoveStartOf("CmFile");

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








        /// <summary>
        /// 정기점검 계획 목록
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult RegularList([FromQuery] PagingRequest req, [FromQuery] string siteId, bool businessAuth) {
            return List(req, siteId, new int[] { 1 }, businessAuth);
        }

        /// <summary>
        /// 법정검사/법정교육 계획 목록
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult LegalList([FromQuery] PagingRequest req, [FromQuery] string siteId, bool businessAuth) {
            return List(req, siteId, new int[] { 2, 7 }, businessAuth);
        }

        private IActionResult List(PagingRequest req, string siteId, int[] workTypeIds, bool businessAuth) {
            var query = _FilterAndSort(req);
            query = query.Where(
                x => x.SiteId == Util.ToInt(siteId)
                && workTypeIds.Contains(x.WorkTypeId)
            );
            query = BusinessFieldHelper.Apply<FmsWorkSchedule>(_context, User, businessAuth, query);
            var list = query.Select(x => new {
                x.SiteId,
                x.WorkScheduleId,
                x.WorkTypeId,
                WorkType = new {
                    x.WorkType.Name
                },
                x.BusinessFieldId,
                BusinessField = new {
                    x.CmBusinessField.Name
                },
                x.InspectionAgencyId,
                InspectionAgency = new {
                    x.CmPartner.Name
                },
                x.Name,
                x.CycleSize,
                x.CycleUnitId,
                CycleUnit = new {
                    x.FmsWorkCodeCycleUnit.Name
                },
                x.HolidayWorkTypeId,
                HolidayWorkType = new {
                    x.FmsWorkCodeHolidayWorkType.Name
                },
                x.WorkDueDate,
                x.UpdateUserId,
                x.WorkPartnerName,
                x.WorkPrice,
                x.WorkItem,
                x.IsUse,
                x.IsAutoOrder,
            });
            var paging = PagingList.Pagination(list, req.page, req.limit);
            return Ok(paging);
        }

        [HttpGet("[action]")]
        public IActionResult Regular([FromQuery] string siteId, [FromQuery] string workScheduleId) {
            return Get(siteId, workScheduleId, 1);
        }

        [HttpGet("[action]")]
        public IActionResult Legal([FromQuery] string siteId, [FromQuery] string workScheduleId) {
            return Get(siteId, workScheduleId, 2);
        }

        private IActionResult Get(string siteId, string workScheduleId, int workTypeId) {
            var query = _service.GetAll()
                .Where(x => x.SiteId == Util.ToInt(siteId) && x.WorkScheduleId == Util.ToInt(workScheduleId));
            var item = query.Select(x => new {
                x.SiteId,
                x.WorkScheduleId,
                x.WorkTypeId,
                WorkType = new {
                    x.WorkType.Name
                },
                x.BusinessFieldId,
                BusinessField = new {
                    x.CmBusinessField.Name
                },
                x.InspectionAgencyId,
                InspectionAgency = new {
                    x.CmPartner.Name
                },
                x.Name,
                x.CycleSize,
                x.CycleUnitId,
                CycleUnit = new {
                    x.FmsWorkCodeCycleUnit.Name
                },
                x.HolidayWorkTypeId,
                HolidayWorkType = new {
                    x.FmsWorkCodeHolidayWorkType.Name
                },
                x.WorkDueDate,
                x.UpdateUserId,
                x.WorkPartnerName,
                x.WorkPrice,
                x.WorkItem,
                x.IsUse,
                x.IsAutoOrder,
                FmsWorkScheduleToFacility = x.FmsWorkScheduleToFacility.Select(f => new {
                    f.SiteId,
                    f.WorkScheduleId,
                    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()
            }).FirstOrDefault();
            return Ok(item);
        }

        [HttpPost("[action]")]
        public IActionResult Save([FromBody] FmsWorkSchedule data) {
            _logger.LogInformation("Save");
            //_logger.LogInformation(data.Dump());

            ModelState.RemoveStartOf("FmsWorkScheduleToFacility");

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

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

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

        [HttpGet("[action]")]
        public IActionResult GetUpdateScheduleWarningMessage([FromQuery] string siteId, [FromQuery] string workScheduleId) {
            return Ok(_service.GetUpdateScheduleWarningMessage(Util.ToInt(siteId), Util.ToInt(workScheduleId)));
        }

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

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

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

            return query;
        }

    }
}