using System;
using System.Linq;
using System.Threading.Tasks;

using FMSAdmin.Data;
using FMSAdmin.Models;
using FMSAdmin.Entities;
using FMSAdmin.Services;

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using FMSAdmin.Helpers;
using System.Data;
using System.IO;
using OfficeOpenXml;

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

        public WorkScheduleController(
            ILogger<WorkScheduleController> logger,
            FMSContext context,
            FMSApp.Services.WorkScheduleService service,
            StorageHelper storage

            ) {
            _logger = logger;
            _context = context;
            _service = service;
            _storage = storage;
        }


        /// <summary>
        /// 정기점검 계획 목록
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult RegularList([FromQuery] PagingRequest req) {
            return List(req, 1);
        }
        /// <summary>
        /// 정기점검 계획 목록 Excel
        /// </summary>
        [AllowAnonymous]
        [HttpGet("[action]")]
        public IActionResult RegularExcel([FromQuery] PagingRequest req, string filename) {
            return ExportExcel(req, 1, filename);
        }
        /// <summary>
        /// 법정점검 계획 목록
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult LegalList([FromQuery] PagingRequest req) {
            return List(req, 2);
        }
        /// <summary>
        /// 법정점검 계획 목록 Excel
        /// </summary>
        [AllowAnonymous]
        [HttpGet("[action]")]
        public IActionResult LegalExcel([FromQuery] PagingRequest req, string filename) {
            return ExportExcel(req, 2, filename);
        }


        private IQueryable<FmsWorkSchedule> _WorkTypeFilter([FromQuery] PagingRequest req, int workType) {
            var query = _FilterAndSort(req);
            // 업무분야 필드가 있는경우만 추가
            if (workType == 2) {
                query = query.Where(x => x.WorkTypeId == 2 || x.WorkTypeId == 7);
            } else {
                query = query.Where(x => x.WorkTypeId == workType);
            }
            return query;
        }

        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet]
        public IActionResult List([FromQuery] PagingRequest req, int workType) {

            var query = _WorkTypeFilter(req, workType);
            var list = _ListSelect(query);

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

        private dynamic _ListSelect(IQueryable<FmsWorkSchedule> query) {

            var list = query.Select(x => new {
                x.SiteId,
                SiteName = x.CmSite.Name,
                x.WorkScheduleId,
                x.BusinessFieldId,
                BusinessField = x.CmBusinessField.Name,
                x.WorkTypeId,
                WorkType = x.WorkType.Name,
                x.Name,
                WorkDueDate = x.WorkDueDate.ToShortDateString(),
                x.HolidayWorkTypeId,
                HolidayWorkType = x.FmsWorkCodeHolidayWorkType.Name,
                x.CycleSize,
                x.CycleUnitId,
                CycleUnit = x.FmsWorkCodeCycleUnit.Name,
                IsAutoOrder = (x.IsAutoOrder ? "Y" : "N"),
                IsUse = (x.IsUse ? "Y" : "N"),

                x.InspectionAgencyId,
                InspectionAgency = x.CmPartner.Name,
                x.UpdateUserId,
            });

            return list;
        }


        /// <summary>
        /// 엑셀파일 익스포트
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpGet("excel")]
        public IActionResult ExportExcel([FromQuery] PagingRequest req, int workType, string filename) {
            req.page = 1;
            req.limit = 0;
            var query = _WorkTypeFilter(req, workType);
            var list = _ListSelect(query);

            var stream = new MemoryStream();
            using (var package = new ExcelPackage(stream)) {
                var workSheet = package.Workbook.Worksheets.Add("Sheet1");

                workSheet.Cells.LoadFromCollection(list, true);

                if (req.columns != null && req.columns.Length > 0) {
                    workSheet.AddStyle(req.columns, req.sort?.order?.ToLower() == "asc", filename);
                }
                package.Save();
            }
            stream.Position = 0;
            string excelName = $"excel-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xlsx";
            return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", excelName);
        }

        [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,
                UserName = new {
                    x.CmUser.Name
                },
                x.IsUse,
                x.IsAutoOrder,
                x.Content,
                FmsWorkScheduleToFacility = x.FmsWorkScheduleToFacility.Select(f => new {
                    f.SiteId,
                    f.WorkScheduleId,
                    f.FacilityCode,
                    //CmFacility = new {
                    FacilityName = 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 = f.CmFacility.FmsFacilityCodeClass.Name,
                    f.CmFacility.SecondClassId,
                    SecondClassName = f.CmFacility.FmsFacilityCodeClass1.Name,
                    f.CmFacility.ThirdClassId,
                    ThirdClassName = 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("CmFile");
            if (ModelState.IsValid) {
                _service.SaveExpectedRequest(data);
            } else {
                return BadRequest(ModelState);
            }
            return Ok();
        }

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



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

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

            // if (req.businessFieldId != null) {
            //     query = query.Where(x => x.BusinessFieldId == req.businessFieldId || x.CmBusinessField.Name == "공통");
            // }

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

            if (req.siteId != null) {
                query = query.Where(x => x.SiteId == Util.ToInt(req.siteId));
            }

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

            return query;
        }


        [HttpGet("[action]")]
        public IActionResult GetScheduleWarning(int siteId, int workScheduleId) {
            var retStr = _service.GetUpdateScheduleWarningMessage(siteId, workScheduleId);
            return Ok(retStr);
        }

    }
}