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

using System.Collections.Generic;

using FMSAdmin.Data;
using FMSAdmin.Models;
using FMSAdmin.Entities;
using FMSApp.Services;
using FMSAdmin.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 FMSAdmin.Controllers {
    [Authorize]
    [ApiController]
    [ApiVersion("1")]
    [Route("api/[controller]")]
    public class WorkRequestController : Controller {
        private readonly ILogger<WorkRequestController> _logger;
        private readonly FMSContext _context;
        private readonly WorkRequestService _service;
        private readonly HolidayService _service_2;
        private readonly MonthWorkService _monthWorkService;
        private readonly StorageHelper _storage;

        public WorkRequestController(
            ILogger<WorkRequestController> logger,
            FMSContext context,
            WorkRequestService service,
            HolidayService service_2,
            MonthWorkService monthWorkService,
            StorageHelper storage
            ) {
            _logger = logger;
            _context = context;
            _service = service;
            _service_2 = service_2;
            _storage = storage;
            _monthWorkService = monthWorkService;
        }

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

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

        /// <summary>
        /// 법정검사, 교육 계획 목록 Excel
        /// </summary>
        [AllowAnonymous]
        [HttpGet("[action]")]
        public IActionResult LegalExcel([FromQuery] PagingRequest req, string filename) {
            return ExportExcel(req, new int[] { 2, 7 }, filename);
        }

        /// <summary>
        /// 수시점검 계획 목록
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult AnyList([FromQuery] PagingRequest req) {
            return List(req, new int[] { 5 });
        }
        /// <summary>
        /// 수시점검 계획 목록 Excel
        /// </summary>
        [AllowAnonymous]
        [HttpGet("[action]")]
        public IActionResult AnyExcel([FromQuery] PagingRequest req, string filename) {
            return ExportExcel(req, new int[] { 5 }, filename);
        }

        /// <summary>
        /// 공사작업 계획 목록
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult ConstructionList([FromQuery] PagingRequest req) {
            return List(req, new int[] { 6 });
        }

        /// <summary>
        /// 공사작업 계획 목록Excel
        /// </summary>
        [AllowAnonymous]
        [HttpGet("[action]")]
        public IActionResult ConstructionExcel([FromQuery] PagingRequest req, string filename) {
            return ExportExcel(req, new int[] { 6 }, filename);
        }


        [HttpGet("{siteId}")]
        public IActionResult Calendar([FromQuery] PagingRequest req, [FromQuery] string siteId, string type, bool businessAuth) {
            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))
                //&& ((x.FmsWorkSchedule != null && x.FmsWorkSchedule.IsUse == true) || !(new int[] { 1, 2, 7 }).Contains(x.WorkTypeId))
            );

            // if (!string.IsNullOrEmpty(workTypeId)) {
            //     query = query.Where(
            //         x => x.WorkTypeId == Util.ToInt(workTypeId)
            //     );
            // }

            if (type == "S") {
                var list = query.Select(x => new {
                    x.SiteId,
                    x.WorkRequestId,
                    id = x.SiteId.ToString() + "-" + x.WorkRequestId.ToString(),
                    groupId = x.WorkTypeId,
                    WorkType = new {
                        x.WorkType.Name
                    },
                    title = x.Title,
                    color = "",
                    start = x.StartWorkDate.ToString("yyyy-MM-dd"),
                    end = x.StartWorkDate.ToString("yyyy-MM-dd"),

                });
                return Ok(list);
            } else if (type == "H") {
                var data = _service_2.GetAll(Util.ToInt(siteId));
                var sYear = DateTime.Today.Year.ToString();

                var list = data.Select(x => new {
                    id = "H-" + x.SiteId + "-" + x.HolidayMonth.ToString() + "-" + x.HolidayDay.ToString(),
                    type = "H",
                    groupId = "H",
                    x.SiteId,
                    //x.HolidayMonth,
                    //x.HolidayDay,
                    //x.IsLunar,
                    start = sYear + '-' + x.HolidayMonth.ToString().PadLeft(2, '0') + '-' + x.HolidayDay.ToString().PadLeft(2, '0'),
                    end = sYear + '-' + x.HolidayMonth.ToString().PadLeft(2, '0') + '-' + x.HolidayDay.ToString().PadLeft(2, '0'),
                    title = x.Name,
                    durationEditable = true,
                    borderColor = "#396",
                });
                return Ok(list);
            } else if (type == "C") {
                var data = _service_2.CustomGetAll(Util.ToInt(siteId));
                var sYear = DateTime.Today.Year.ToString();

                var list = data.Select(x => new {
                    id = "C-" + x.SiteId + "-" + x.HolidayDate.ToString("yyyyMMdd"),
                    type = "C",
                    groupId = "C",
                    x.SiteId,
                    start = x.HolidayDate.ToString("yyyy-MM-dd"),
                    end = x.HolidayDate.ToString("yyyy-MM-dd"),
                    title = x.Name,
                    color = "#FFE400",
                    borderColor = "#396",
                });

                return Ok(list);
            } else {
                var data = _service_2.WeekendGetAll(Util.ToInt(siteId));
                var sYear = DateTime.Today.Year.ToString();

                var list = data.Select(x => new {
                    id = "W-" + x.SiteId,
                    x.SiteId,
                    x.Saturday,
                    x.Sunday,
                    color = "red",
                    borderColor = "#396",
                });

                return Ok(list);
            }





        }

        /// <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);
        }

        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet]
        private dynamic _ListSelect(IQueryable<FmsWorkRequest> query) {

            var list = query.Select(x => new {
                x.SiteId,
                Site = x.Site.Name,
                x.BusinessFieldId,
                BusinessField = x.CmBusinessField.Name,
                x.WorkTypeId,
                WorkType = x.WorkType.Name,
                x.WorkDetailTypeId,
                WorkDetailType = x.WorkDetailType.Name,
                x.WorkRequestId,
                x.Title,
                StartWorkDate = x.StartWorkDate.ToString("yyyy-MM-dd"),
                EndWorkDate = x.WorkEndDate != null ? x.WorkEndDate.Value.ToString("yyyy-MM-dd") : "",
                CmUserNavigation = x.CmUserNavigation.Name,
                x.WorkScheduleId,
                x.WorkProgressId,
                WorkProgress = x.WorkProgress.Name,
                x.Content,
                x.RequestUserId,
                x.RequestDate,
                x.RejectUserId,
                x.RejectDate,
                x.RejectReason,
                x.InspectionAgencyId,
                InspectionAgency = x.CmPartner.Name,
                WorkPartnerName = x.WorkPartner.Name,
                x.WorkPrice,
                WorkCodeHolidayWorkType = x.FmsWorkSchedule.FmsWorkCodeHolidayWorkType.Name,
                Cycle = x.FmsWorkSchedule.CycleSize.ToString() + x.FmsWorkSchedule.FmsWorkCodeCycleUnit.Name

            });
            return list;
        }

        [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,
                CmSite = new {
                    x.Site.Name,
                },

                x.WorkRequestId,
                x.WorkTypeId,
                WorkType = new {
                    x.WorkType.Name
                },
                x.WorkDetailTypeId,
                WorkDetailType = new {
                    x.WorkDetailType.Name,
                    x.WorkDetailType.Code,
                },
                x.BusinessFieldId,
                BusinessField = new {
                    x.CmBusinessField.Name
                },
                x.WorkScheduleId,
                x.WorkProgressId,
                WorkProgress = new {
                    x.WorkProgress.Name
                },
                x.Title,
                x.Content,
                x.RequestUserId,
                RequestUserName = new { x.CmUser.Name },
                UserName = new {
                    x.CmUserNavigation.Name,
                },

                x.RequestDate,
                x.StartWorkDate,
                x.RejectUserId,
                x.RejectDate,
                x.RejectReason,
                x.InspectionAgencyId,
                InspectionAgency = new {
                    x.CmPartner.Name
                },

                WorkPartner = new {
                    x.WorkPartner.Name,
                    x.WorkPartner.PartnerId
                },
                WorkCodeHolidayWorkType = x.FmsWorkSchedule.FmsWorkCodeHolidayWorkType.Name,
                Cycle = x.FmsWorkSchedule.CycleSize.ToString() + x.FmsWorkSchedule.FmsWorkCodeCycleUnit.Name,
                x.WorkPrice,
                x.WorkItem,
                x.WorkEndDate,
                CmFile = _storage.ParseFile(x.CmFile),
                FmsWorkOrder = new {
                    x.FmsWorkOrder.SiteId,
                    x.FmsWorkOrder.WorkRequestId,
                    x.FmsWorkOrder.OrderUserId,
                    x.FmsWorkOrder.Content
                },
                FmsWorkRequestToFacility = x.FmsWorkRequestToFacility.Select(f => new {
                    f.SiteId,
                    f.WorkRequestId,
                    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(),
                FmsWorkRequestToAccident = x.FmsWorkRequestToAccident.Select(f => new {
                    f.SiteId,
                    f.WorkRequestId,
                    f.AccidentId,
                    Name = f.FmsAccident.Name,
                    f.FmsAccident.AccidentTypeId,
                    AccidentTypeName = f.FmsAccident.FmsAccidentCodeType.Name,
                    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,
                    Name = f.FmsComplaints.Name,
                    f.FmsComplaints.CompanyId,

                    ComplaintTypeName = f.FmsComplaints.FmsComplaintCodeType.Name,
                    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("CmFile");
            // ModelState.RemoveStartOf("FmsWorkRequestToFacility");
            // ModelState.RemoveStartOf("FmsWorkRequestToAccident");
            // ModelState.RemoveStartOf("FmsWorkRequestToComplaint");
            // ModelState.RemoveStartOf("FmsWorkOrder");
            // ModelState.RemoveStartOf("WorkDetailType");

            if (ModelState.IsValid) {
                _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) {
            _service.Reject(data, useSchedule, confirmDate);
            return Ok();
        }

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


        // 사고 ACCIDENT 코드 확인
        [HttpGet("[action]")]
        public IActionResult CodeGet([FromQuery] int code) {
            var list = _context.FmsWorkCodeDetailType.Where(x => x.WorkDetailTypeId == code).Select(x => new { x.Code }).FirstOrDefault();
            return Ok(list);

        }

        private IQueryable<FmsWorkRequest> _WorkTypeFilter([FromQuery] PagingRequest req, int[] workType) {
            var query = _FilterAndSort(req);
            //if (workType != null) {
            query = query.Where(x => x.WorkProgressId == 1);

            if (workType.Length > 0)
                query = query.Where(x => workType.Contains(x.WorkTypeId));


            // } else {
            //     query = query.Where(
            //         x => x.WorkProgressId == 1 // 작업계획
            //         //&& (x.FmsWorkSchedule != null && x.FmsWorkSchedule.IsUse == true && (x.WorkTypeId == 1 || x.WorkTypeId == 2 || x.WorkTypeId == 5 || x.WorkTypeId == 6))
            //         //&& ((x.FmsWorkSchedule != null && x.FmsWorkSchedule.IsUse == true) || x.WorkTypeId > 2)
            //         && (x.FmsWorkSchedule == null || (x.FmsWorkSchedule != null && x.FmsWorkSchedule.IsUse == true))
            //     );
            // }
            return query;
        }

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


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

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

            if (req.siteIds != null && req.siteIds.Length > 0) {
                query = query.Where(x => req.siteIds.Contains(x.SiteId));
            }


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



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

            //정렬(최근 작업시작일자, 업무명, 사옥 준공)
            if (req.sort != null) {
                if (req.sort.field == "Custom") {
                    query = query.OrderByDescending(x => x.StartWorkDate).ThenBy(x => x.Title).ThenBy(x => x.Site.SortOrderNo);
                } else {
                    query = query.Sort(req.sort);
                }
            }

            return query;
        }
        /// <summary>
        /// 엑셀파일 익스포트
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        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 WorkCalendar(int siteId, int? year, int? month) {
            //var siteId = User.GetSiteId();

            DateTime selectMonth;
            if (year == null || month == null) {
                selectMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            } else {
                selectMonth = new DateTime(year.Value, month.Value, 1);
            }
            var startDate = selectMonth.AddDays(-7);
            var endDate = selectMonth.AddDays(37);

            // 작업예정
            var requestList = _GetRequestEventList(siteId, startDate, endDate);

            // 작업완료
            //var resultList = _GetResultEventList(siteId, startDate, endDate);

            if (siteId == 0) siteId = 100;
            // 휴일
            var holidayList = _GetHolidayList(siteId, selectMonth.Year, selectMonth.Month, startDate, endDate);

            // 주말
            var weekend = _context.CmHolidayWeekend.Where(
                x => x.SiteId == siteId
                && x.IsUse == true
            ).FirstOrDefault();

            // 집중업무
            var workName = _monthWorkService.GetKeyWork(siteId, selectMonth.Month);

            if (weekend != null) {
            }

            var result = new {
                Year = selectMonth.Year,
                Month = selectMonth.Month,
                Theme = workName,
                StartDate = startDate.ToString("yyyy-MM-dd"),
                EndDate = endDate.ToString("yyyy-MM-dd"),
                RequestList = requestList,
                //ResultList = resultList,
                HolidayList = holidayList,
                Saturday = weekend?.Saturday ?? false,
                Sunday = weekend?.Sunday ?? false,
            };

            return Ok(result);
        }


        private IQueryable<CalendarEvent> _GetRequestEventList(int? siteId, DateTime startDate, DateTime endDate) {
            var events = _context.FmsWorkRequest.Select(x => x);
            if (siteId != null && siteId != 0) {
                events = events.Where(x => x.SiteId == siteId.Value);
            }

            var query = from x in events
                        where x.FmsWorkResult == null
                        where x.StartWorkDate.Date >= startDate.Date && x.StartWorkDate.Date <= endDate.Date
                        && x.WorkProgressId == 1 // 작업계획
                        && (x.FmsWorkSchedule == null || (x.FmsWorkSchedule != null && x.FmsWorkSchedule.IsUse == true))
                        select x;

            var list = query.Select(x => new CalendarEvent {
                Title = x.Title,
                Start = x.StartWorkDate.ToString("yyyy-MM-dd"),
                End = x.StartWorkDate.ToString("yyyy-MM-dd"),
                WorkType = x.WorkType.Name,
                Id = x.SiteId.ToString() + "-" + x.WorkRequestId.ToString(),
                GroupId = x.WorkTypeId,
                Type = "예정",
                WorkRequestId = x.WorkRequestId,
            });

            return list;
        }

        private IQueryable<CalendarEvent> _GetResultEventList(int? siteId, DateTime startDate, DateTime endDate) {
            var events = _context.FmsWorkResult.Select(x => x);
            if (siteId != null) {
                events = events.Where(x => x.SiteId == siteId.Value);
            }



            var query = from x in events
                        where x.StartDate.Date >= startDate.Date && x.StartDate <= endDate.Date
                        select x;

            var list = query.Select(x => new CalendarEvent {
                Title = x.FmsWorkRequest.Title,
                Start = x.StartDate.ToString("yyyy-MM-dd"),
                End = x.EndDate.ToString("yyyy-MM-dd"),
                WorkType = x.FmsWorkRequest.WorkType.Name,
                Type = "진행",
                WorkRequestId = x.WorkRequestId,
            });

            return list;
        }

        private IList<CalendarBackground> _GetHolidayList(int siteId, int year, int month, DateTime startDate, DateTime endDate) {
            var list = new List<CalendarBackground>();

            var holidays = _context.CmHoliday.Where(
                x => x.SiteId == siteId
                && x.IsUse == true
            );

            foreach (var item in holidays) {
                if (item.IsLunar) {
                    var solar = LunarSolarConverter.LunarToSolar(new Lunar() {
                        lunarYear = year,
                        lunarMonth = item.HolidayMonth,
                        lunarDay = item.HolidayDay
                    });
                    list.Add(new CalendarBackground {
                        Title = item.Name + "(음력)",
                        Date = new DateTime(solar.solarYear, solar.solarMonth, solar.solarDay).ToString("yyyy-MM-dd"),
                        Type = "공휴일",
                    });
                } else {
                    list.Add(new CalendarBackground {
                        Title = item.Name,
                        Date = new DateTime(year, item.HolidayMonth, item.HolidayDay).ToString("yyyy-MM-dd"),
                        Type = "공휴일",
                    });
                }
            }

            var query = from x in _context.CmHolidayCustom
                        where x.SiteId == siteId
                        where x.HolidayDate.Date >= startDate.Date && x.HolidayDate >= endDate.Date
                        select x;

            var customs = query.Select(x => new CalendarBackground {
                Title = x.Name,
                Date = x.HolidayDate.ToString("yyyy-MM-dd"),
                Type = "휴일",
            });

            return list;
        }

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

        //작업승인 달력 상세(리스트)
        [HttpGet("[action]")]
        public IActionResult CustomList([FromQuery] PagingRequest req, DateTime dates) {

            DateTime selectMonth;
            selectMonth = new DateTime(dates.Year, dates.Month, dates.Day);
            var startDate = selectMonth;
            var endDate = selectMonth.AddDays(1).AddSeconds(-1);

            var list = _service.GetAll()
                       .Where(x => x.StartWorkDate.Date >= startDate.Date && x.StartWorkDate.Date <= endDate.Date)
                       //query.Where(x=>x.FmsWorkResult == null );

                       .Select(x => new { Title = "[" + x.Site.Name + "]" + x.Title, x.SiteId, x.WorkRequestId, x.WorkTypeId, WorkScheduleId = x.FmsWorkSchedule.WorkScheduleId });

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


        //작업승인 달력 상세(리스트)
        [HttpGet("[action]")]
        public IActionResult CustomListSite([FromQuery] PagingRequest req, int siteId, DateTime dates) {

            DateTime selectMonth;
            selectMonth = new DateTime(dates.Year, dates.Month, dates.Day);
            var startDate = selectMonth;
            var endDate = selectMonth.AddDays(1).AddSeconds(-1);

            var list = _service.GetAll()
                       .Where(x => x.SiteId == siteId && x.StartWorkDate.Date >= startDate.Date && x.StartWorkDate.Date <= endDate.Date)
                       .Select(x => new {
                           x.Title,
                           x.SiteId,
                           x.WorkRequestId,
                           x.WorkTypeId,
                           WorkScheduleId = x.FmsWorkSchedule.WorkScheduleId,
                           x.WorkProgressId,
                           WorkProgressName = x.WorkProgress.Name
                       });

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



    }
}