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.Text;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

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

        public enum WorkTypeId {
            PeriodicInspection = 1,
            ForensicExamination = 2,
            CivilComplaint = 3,
            SiAlarm = 4,
            Occasional = 5,
            Construct = 6,
            ForensicEducation = 7,
        }

        public enum WorkProgressId {
            WorkStatusPending = 3,
            WorkStatusInProgress = 4,
            WorkStatusComplete = 5,
            WorkStatusApproved = 6,
            WorkStatusDeferred = 7,
        }

        public enum AdjustmentTypeId {
            Regular = 0,
            Loss = 1,
            Return = 2
        }

        public MonthlyReportController(
            ILogger<MonthlyReportController> logger,
            FMSContext context,
            MonthlyReportService service,
            FMSAdmin.Services.SiteWeatherInfoService siteWeatherInfoService,
            StorageHelper storage
            ) {
            _logger = logger;
            _context = context;
            _service = service;
            _siteWeatherInfoService = siteWeatherInfoService;
            _storage = storage;
        }

        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet]
        public IActionResult List([FromQuery] PagingRequest req, [FromQuery] string siteId, bool businessAuth) {
            var query = _FilterAndSort(req);
            query = BusinessFieldHelper.Apply<FmsMonthlyReport>(_context, User, businessAuth, query);
            query = query.Where(x => x.SiteId == Util.ToInt(siteId));

            var list = query.Select(x => new {
                x.SiteId,
                x.AddDate,
                x.BusinessFieldId,
                x.Name,
                x.Contents,
                x.RegisterUserId,
                RegisterUserName = _context.CmUser.FirstOrDefault(user => user.UserId == x.RegisterUserId).Name,
                x.ApproveDate,
                x.RegisterDate,
                x.ApproverUserId,
                ApproverUserName = _context.CmUser.FirstOrDefault(user => user.UserId == x.ApproverUserId).Name,
            });

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

        [HttpGet("[action]")]
        public IActionResult Get([FromQuery] string siteId, [FromQuery] DateTime addDate, [FromQuery] string businessFieldId) {
            var query = _service.GetAll();

            var item = query.Where(
                x => x.SiteId == Util.ToInt(siteId)
                && x.AddDate.Year == addDate.Date.Year
                && x.AddDate.Month == addDate.Date.Month
                && x.BusinessFieldId == Util.ToInt(businessFieldId)
            ).Select(x => new {
                x.SiteId,
                AddDate = x.AddDate.ToString("yyyy-MM"),
                x.BusinessFieldId,
                x.Name,
                x.Contents,
                x.SiteInfoDatas,
                x.FacilityStandards,
                x.RentalStandards,
                ParkingManagement = new {
                    FileId = x.ParkingManagement.FileId,
                    Path = _storage.getFilePath(x.ParkingManagement),
                    Name = x.ParkingManagement.Name
                },
                RentalManagement = new {
                    FileId = x.RentalManagement.FileId,
                    Path = _storage.getFilePath(x.RentalManagement),
                    Name = x.RentalManagement.Name
                },
                MonthlyPriorityWork = new {
                    FileId = x.MonthlyPriorityWork.FileId,
                    Path = _storage.getFilePath(x.MonthlyPriorityWork),
                    Name = x.MonthlyPriorityWork.Name
                },
                ImprovementReport = new {
                    FileId = x.ImprovementReport.FileId,
                    Path = _storage.getFilePath(x.ImprovementReport),
                    Name = x.ImprovementReport.Name
                },
                NextMonthPriorityWork = new {
                    FileId = x.NextMonthPriorityWork.FileId,
                    Path = _storage.getFilePath(x.NextMonthPriorityWork),
                    Name = x.NextMonthPriorityWork.Name
                },
                Cost = new {
                    FileId = x.Cost.FileId,
                    Path = _storage.getFilePath(x.Cost),
                    Name = x.Cost.Name
                },
                SurroundingStatus = new {
                    FileId = x.SurroundingStatus.FileId,
                    Path = _storage.getFilePath(x.SurroundingStatus),
                    Name = x.SurroundingStatus.Name
                },
                x.HumanCountStatus,
                x.ManagementOfficeContact,
                x.RelatedInstitutionsContact,
                x.UserChangeStatus,
                x.TenantContact,
                x.RegisterUserId,
                x.RegisterDate,
                x.ApproveDate,
                x.ApproverUserId,
                ApproverUserName = _context.CmUser.FirstOrDefault(user => user.UserId == x.ApproverUserId).Name,
                x.ApproverUserId2,
                ApproverUserName2 = _context.CmUser.FirstOrDefault(user => user.UserId == x.ApproverUserId2).Name,
                x.ApproverUserId3,
                ApproverUserName3 = _context.CmUser.FirstOrDefault(user => user.UserId == x.ApproverUserId3).Name,
                x.ApproverUserId4,
                ApproverUserName4 = _context.CmUser.FirstOrDefault(user => user.UserId == x.ApproverUserId4).Name,
                x.ApproverUserId5,
                ApproverUserName5 = _context.CmUser.FirstOrDefault(user => user.UserId == x.ApproverUserId5).Name,
                x.FacilityTime,
                x.FacilityTimeGraph,
                x.EnergyUsage,
                x.EnergyUsageGraph,
                x.EnergyCost,
                x.EnergyCharge,
                x.EnergyChargeGraph,
                x.EnergyAnalysis,
            }).FirstOrDefault();


            var organizationChartStatus =
                    _context.CmOrganizationChartStatus.Where(
                        x => x.SiteId == Util.ToInt(siteId)
                        && x.Year == addDate.Date.Year
                        && x.Month == addDate.Date.Month
                    ).Select(x => new {
                        x.CmFile.FileId,
                        Path = _storage.getFilePath(x.CmFile),
                        x.CmFile.Name
                    }).FirstOrDefault();

            var rentalStatus =
                  _context.CmRentalStatus.Where(
                      x => x.SiteId == Util.ToInt(siteId)
                      && x.Year == addDate.Date.Year
                      && x.Month == addDate.Date.Month
                  ).Select(x => new {
                      x.CmFile.FileId,
                      Path = _storage.getFilePath(x.CmFile),
                      x.CmFile.Name
                  }).FirstOrDefault();

            _logger.LogInformation("========================== 법정검사 =======================");
            DataTable legalExamination = _service.GetLegalExamination(Util.ToInt(siteId), addDate);

            var layoutStatus =
                  _context.CmLayout.Where(
                      x => x.SiteId == Util.ToInt(siteId)
                      && x.Year == addDate.Date.Year
                      && x.Month == addDate.Date.Month
                  ).Select(x => new {
                      x.CmFile.FileId,
                      Path = _storage.getFilePath(x.CmFile),
                      x.CmFile.Name
                  }).FirstOrDefault();


            return Ok(new {
                report = item,
                OrganizationChartStatus = organizationChartStatus,
                RentalStatus = rentalStatus,
                LayoutStatus = layoutStatus,
                LegalExamination = legalExamination,
            });
        }

        [AllowAnonymous]
        [HttpGet("[action]")]
        public string GetJson(string siteId, DateTime? addDate, string tabName, string year, string month) {
            _logger.LogInformation(tabName);
            var query = _service.GetAll();

            if (addDate == null) {
                if (string.IsNullOrEmpty(year) || string.IsNullOrEmpty(month)) {
                    throw new Exception("날짜가 입력되지 않았습니다.");
                }
            }

            // Date or year,month 
            int currentYear = addDate != null ? addDate.Value.Year : Util.ToInt(year);
            int currentMonth = addDate != null ? addDate.Value.Month : Util.ToInt(month);
            DateTime currentDate = addDate != null ? addDate.Value : new DateTime(currentYear, currentMonth, 1);

            var item = query.Where(
                x => x.SiteId == Util.ToInt(siteId)
                && x.AddDate.Year == currentYear
                && x.AddDate.Month == currentMonth
            ).Select(x => new {
                CmSite = new {
                    x.Name
                },
                AddDate = x.AddDate.ToString("yyyy-MM"),
                x.Name,
                x.Contents,
                x.SiteInfoDatas,
                x.FacilityStandards,
                x.RentalStandards,
                x.HumanCountStatus,
                x.UserChangeStatus,
                x.ManagementOfficeContact,
                x.RelatedInstitutionsContact,
                x.TenantContact,
                x.ParkingManagement,
                x.RentalManagement,
                x.MonthlyPriorityWork,
                x.ImprovementReport,
                x.NextMonthPriorityWork,
                x.Cost,
                x.SurroundingStatus,
                x.FacilityTime,
                x.FacilityTimeGraph,
                x.EnergyUsage,
                x.EnergyUsageGraph,
                x.EnergyCost,
                x.EnergyCharge,
                x.EnergyChargeGraph,
                x.EnergyAnalysis,
                x.ApproveDate,
                x.ApproveDate2,
                x.ApproveDate3,
                x.ApproverUserId,
                x.ApproverUserId2,
                x.ApproverUserId3
            }).FirstOrDefault();
            string approve = "";
            if (item != null) {
                approve += "[" + getApproverInfo(item.ApproverUserId, item.ApproveDate);
                approve += getApproverInfo(item.ApproverUserId2, item.ApproveDate2);
                approve += getApproverInfo(item.ApproverUserId3, item.ApproveDate3);
                approve += "]";
            }

            string json = "";
            if (item != null) {
                if (tabName == "Building") {
                    json = $@"
                    {{ 
                        Building : {{  
                            SiteInfo: {item.SiteInfoDatas},
                            FacilityStandards: {item.FacilityStandards},
                            RentalStandards: {item.RentalStandards},
                            Approver : {approve}
                        }} 
                    }}";
                } else if (tabName == "UserInfo") {
                    var OrganizationChartStatus = _context.CmOrganizationChartStatus.Where(x =>
                                                    x.SiteId == Util.ToInt(siteId) &&
                                                    x.Year == currentYear &&
                                                    x.Month == currentMonth).Select(x => x.CmFile).SingleOrDefault();
                    json = $@"
                    {{ 
                        UserInfo : {{  
                            OrganizationChartStatus: {JsonConvert.SerializeObject(_storage.GetPdfImages(OrganizationChartStatus))},
                            HumanCountStatus : {item.HumanCountStatus},
                            ManagementOfficeContact: {item.ManagementOfficeContact},
                            RelatedInstitutionsContact : {item.RelatedInstitutionsContact},
                            UserChangeStatus: {item.UserChangeStatus},
                            Approver : {approve}
                        }} 
                    }}";
                } else if (tabName == "TenantInfo") {
                    var RentalStatus = _context.CmRentalStatus.Where(x =>
                                        x.SiteId == Util.ToInt(siteId) &&
                                        x.Year == currentYear &&
                                        x.Month == currentMonth).Select(x => x.CmFile).SingleOrDefault();
                    json = $@"
                    {{ 
                        Images :{JsonConvert.SerializeObject(_storage.GetPdfImages(RentalStatus))},
                        Approver : {approve}
                    }}";
                } else if (tabName == "TenantInfoFloor") {
                    var LayoutStatus = _context.CmLayout.Where(x =>
                                                      x.SiteId == Util.ToInt(siteId) &&
                                                      x.Year == currentYear &&
                                                      x.Month == currentMonth).Select(x => x.CmFile).SingleOrDefault();
                    json = $@"
                    {{ 
                        TenantInfoFloor : {{  
                            LayoutStatus: {JsonConvert.SerializeObject(_storage.GetPdfImages(LayoutStatus))},
                            TenantContact : {item.TenantContact},
                            Approver : {approve}
                        }} 
                    }}";
                } else if (tabName == "ParkingManagement") {
                    json = $@"
                    {{ 
                        Images : {JsonConvert.SerializeObject(_storage.GetPdfImages(item.ParkingManagement))},
                        Approver : {approve}
                    }}";
                } else if (tabName == "RentalManagement") {
                    json = $@"
                    {{ 
                        Images : {JsonConvert.SerializeObject(_storage.GetPdfImages(item.RentalManagement))},
                        Approver : {approve}
                    }}";
                } else if (tabName == "LegalExamination") {
                    DataTable legalExamination = _service.GetLegalExamination(Util.ToInt(siteId), currentDate);
                    json = $@"
                    {{ 
                        Images : {JsonConvert.SerializeObject(legalExamination)},
                        Approver : {approve}
                    }}";

                } else if (tabName == "MonthlyPriorityWork") {
                    json = $@"
                    {{ 
                        Images :{JsonConvert.SerializeObject(_storage.GetPdfImages(item.MonthlyPriorityWork))},
                        Approver : {approve}
                    }}";

                } else if (tabName == "ImprovementReport") {
                    json = $@"
                    {{ 
                        Images : {JsonConvert.SerializeObject(_storage.GetPdfImages(item.ImprovementReport))},
                        Approver : {approve}
                    }}";

                } else if (tabName == "NextMonthPriorityWork") {
                    json = $@"
                    {{ 
                        Images : {JsonConvert.SerializeObject(_storage.GetPdfImages(item.NextMonthPriorityWork))},
                        Approver : {approve}
                    }}";

                } else if (tabName == "Cost") {
                    json = $@"
                    {{ 
                        Images : {JsonConvert.SerializeObject(_storage.GetPdfImages(item.Cost))},
                        Approver : {approve}
                    }}";

                } else if (tabName == "SurroundingStatus") {
                    json = $@"
                    {{ 
                        Images : {JsonConvert.SerializeObject(_storage.GetPdfImages(item.SurroundingStatus))},
                        Approver : {approve}
                    }}";
                } else if (tabName == "FacilityTime") {
                    json = $@"
                    {{ 
                        FacilityTime : {{  
                            FacilityTime: {item.FacilityTime},
                            FacilityTimeGraph: {item.FacilityTimeGraph},
                            Approver : {approve}
                        }} 
                    }}";
                } else if (tabName == "EnergyUsageElect") {
                    string energyUsage = "", energyUsageGraph = "", energyCost = "";
                    JArray jarr1 = JArray.Parse(item.EnergyUsage);
                    foreach (var val in jarr1) {
                        if (val["FuelTypeId"].ToString() == "1") {
                            energyUsage += (energyUsage != "" ? "," : "") + val.ToString(Newtonsoft.Json.Formatting.None);
                        }
                    }
                    JArray jarr2 = JArray.Parse(item.EnergyUsageGraph);
                    foreach (var val in jarr2) {
                        if (val["FuelTypeId"].ToString() == "1") {
                            energyUsageGraph += (energyUsageGraph != "" ? "," : "") + val.ToString(Newtonsoft.Json.Formatting.None);
                        }
                    }
                    JArray jarr3 = JArray.Parse(item.EnergyCost);
                    foreach (var val in jarr3) {
                        if (val["FuelTypeId"].ToString() == "1") {
                            energyCost += (energyCost != "" ? "," : "") + val.ToString(Newtonsoft.Json.Formatting.None);
                        }
                    }
                    json = $@"
                    {{ 
                        EnergyUsageElect : {{  
                            EnergyUsage: [{energyUsage}],
                            EnergyUsageGraph: [{energyUsageGraph}],
                            EnergyCost: [{energyCost}],
                            Approver : {approve}
                        }} 
                    }}";
                } else if (tabName == "EnergyUsageGasWater") {
                    string energyUsage = "", energyUsageGraph = "", energyCost = "";
                    JArray jarr1 = JArray.Parse(item.EnergyUsage);
                    foreach (var val in jarr1) {
                        if (val["FuelTypeId"].ToString() != "1") {
                            energyUsage += (energyUsage != "" ? "," : "") + val.ToString(Newtonsoft.Json.Formatting.None);
                        }
                    }
                    JArray jarr2 = JArray.Parse(item.EnergyUsageGraph);
                    foreach (var val in jarr2) {
                        if (val["FuelTypeId"].ToString() != "1") {
                            energyUsageGraph += (energyUsageGraph != "" ? "," : "") + val.ToString(Newtonsoft.Json.Formatting.None);
                        }
                    }
                    JArray jarr3 = JArray.Parse(item.EnergyCost);
                    foreach (var val in jarr3) {
                        if (val["FuelTypeId"].ToString() != "1") {
                            energyCost += (energyCost != "" ? "," : "") + val.ToString(Newtonsoft.Json.Formatting.None);
                        }
                    }
                    json = $@"
                    {{ 
                        EnergyUsageGasWater : {{  
                            EnergyUsage: [{energyUsage}],
                            EnergyUsageGraph: [{energyUsageGraph}],
                            EnergyCost: [{energyCost}],
                            Approver : {approve}
                        }} 
                    }}";
                } else if (tabName == "EnergyChargeElect") {
                    string energyCharge = "", energyChargeGraph = "", energyAnalysis = "";
                    JArray jarr1 = JArray.Parse(item.EnergyCharge);
                    foreach (var val in jarr1) {
                        if (val["FuelTypeId"].ToString() == "1") {
                            energyCharge += (energyCharge != "" ? "," : "") + val.ToString(Newtonsoft.Json.Formatting.None);
                        }
                    }
                    JArray jarr2 = JArray.Parse(item.EnergyChargeGraph);
                    foreach (var val in jarr2) {
                        if (val["FuelTypeId"].ToString() == "1") {
                            energyChargeGraph += (energyChargeGraph != "" ? "," : "") + val.ToString(Newtonsoft.Json.Formatting.None);
                        }
                    }
                    JArray jarr3 = JArray.Parse(item.EnergyAnalysis);
                    foreach (var val in jarr3) {
                        if (val["FuelTypeId"].ToString() == "1") {
                            energyAnalysis += (energyAnalysis != "" ? "," : "") + val.ToString(Newtonsoft.Json.Formatting.None);
                        }
                    }
                    json = $@"
                    {{ 
                        EnergyChargeElect : {{  
                            EnergyCharge: [{energyCharge}],
                            EnergyChargeGraph: [{energyChargeGraph}],
                            EnergyAnalysis: [{energyAnalysis}],
                            Approver : {approve}
                        }} 
                    }}";
                } else if (tabName == "EnergyChargeGasWater") {
                    string energyCharge = "", energyChargeGraph = "", energyAnalysis = "";
                    JArray jarr1 = JArray.Parse(item.EnergyCharge);
                    foreach (var val in jarr1) {
                        if (val["FuelTypeId"].ToString() != "1") {
                            energyCharge += (energyCharge != "" ? "," : "") + val.ToString(Newtonsoft.Json.Formatting.None);
                        }
                    }
                    JArray jarr2 = JArray.Parse(item.EnergyChargeGraph);
                    foreach (var val in jarr2) {
                        if (val["FuelTypeId"].ToString() != "1") {
                            energyChargeGraph += (energyChargeGraph != "" ? "," : "") + val.ToString(Newtonsoft.Json.Formatting.None);
                        }
                    }
                    JArray jarr3 = JArray.Parse(item.EnergyAnalysis);
                    foreach (var val in jarr3) {
                        if (val["FuelTypeId"].ToString() != "1") {
                            energyAnalysis += (energyAnalysis != "" ? "," : "") + val.ToString(Newtonsoft.Json.Formatting.None);
                        }
                    }
                    json = $@"
                    {{ 
                        EnergyChargeGasWater : {{  
                            EnergyCharge: [{energyCharge}],
                            EnergyChargeGraph: [{energyChargeGraph}],
                            EnergyAnalysis: [{energyAnalysis}],
                            Approver : {approve}
                        }} 
                    }}";
                }
            } else {
                json = "{}";
                if (tabName == "TenantInfo") {
                    json = "{ Images :[], Approver : [] }";
                } else if (tabName == "ParkingManagement") {
                    json = "{ Images :[], Approver : [] }";
                } else if (tabName == "RentalManagement") {
                    json = "{ Images :[], Approver : [] }";
                } else if (tabName == "MonthlyPriorityWork") {
                    json = "{ Images :[], Approver : [] }";
                } else if (tabName == "ImprovementReport") {
                    json = "{ Images :[], Approver : [] }";
                } else if (tabName == "NextMonthPriorityWork") {
                    json = "{ Images :[], Approver : [] }";
                } else if (tabName == "Cost") {
                    json = "{ Images :[], Approver : [] }";
                } else if (tabName == "SurroundingStatus") {
                    json = "{ Images :[], Approver : [] }";
                }
            }
            return json;
        }


        public string getApproverInfo(string id, DateTime? date) {
            if (!Util.IsNullOrEmpty(id)) {
                var userInfo = _context.CmUser.Where(x => x.UserId == id).Select(x => new {
                    GroupNm = x.CmUserGroup.Name,
                    Date = date.Value.ToString("yyyy-MM-dd"),
                    image = x.CmFile1 != null ? _storage.GetFullUrl(x.CmFile1.Path) + _storage.getFilePath(x.CmFile1) : ""
                }).SingleOrDefault();
                return JsonConvert.SerializeObject(userInfo) + ",";
            } else return "";
        }

        private static string AreaParse(String areaVal) {
            string returnVal = "";
            float val;
            if (!Util.IsNullOrEmpty(areaVal) && float.TryParse(areaVal, out val)) {
                returnVal = val.ToString("#,##0.00") + "㎡ (" + (val / 3.3058).ToString("#,##0.00") + "평)";
            }
            return returnVal;
        }


        [HttpGet("[action]")]
        public IActionResult GetCurrentInfo([FromQuery] string siteId, [FromQuery] DateTime addDate, [FromQuery] string businessFieldId) {

            var today = addDate.Date;

            _logger.LogInformation("========================== 기본사항! =======================");
            var siteInfo = _context.CmSite.Where(
                x => x.SiteId == Util.ToInt(siteId)
            ).Select(x => new {
                x.SiteId,
                x.Name,
                x.PhoneNo,
                x.AddressZip1,
                x.CompletionDate,
                Address1 = x.Address1 + x.Adderss2,
                x.BuildingSize,
                GrossArea = AreaParse(x.GrossArea),
                BuildingArea = AreaParse(x.BuildingArea),
                x.FloorAreaRatio,
                x.BuildingCoverageRatio,
                x.MainUse,
                x.Standard,
                x.Url,
                ImageFile = _storage.ParseFile(x.ImageFile),
                x.DesignSupervision,
                x.ConstructionCompany,
                x.ConstructionPeriod,
                x.Structure,
                x.LobbyFloor,
                x.OfficeFloor,
                x.ToiletFloor,
                x.EVHall,
                x.ParkingLot,
                x.ParkingFacilities,
                x.OuterWall,
                LandArea = AreaParse(x.LandArea),
                LandscapingArea = AreaParse(x.LandscapingArea),
                x.BuildingFloors,
                x.BuildingHeight,
                x.ConversionRate,
                x.AuditoriumFacilities
            }).FirstOrDefault();

            _logger.LogInformation("========================== 조직도현황! =======================");
            var organizationChartStatus = _context.CmOrganizationChartStatus.Where(
                x => x.SiteId == Util.ToInt(siteId) &&
                x.Year == addDate.Year &&
                x.Month == addDate.Month
            ).Select(x => new {
                FileId = x.FileId,
                Path = _storage.getFilePath(x.CmFile),
                Name = x.CmFile.Name
            }).FirstOrDefault();

            _logger.LogInformation("========================== 입주사현황(임대현황)! =======================");
            var rentalStatus = _context.CmRentalStatus.Where(
                x => x.SiteId == Util.ToInt(siteId) &&
                x.Year == addDate.Year &&
                x.Month == addDate.Month
            ).Select(x => new {
                FileId = x.FileId,
                Path = _storage.getFilePath(x.CmFile),
                Name = x.CmFile.Name
            }).FirstOrDefault();


            _logger.LogInformation("========================== 층별사용현황(레이아웃)! =======================");
            var layoutStatus = _context.CmLayout.Where(
                x => x.SiteId == Util.ToInt(siteId) &&
                x.Year == addDate.Year &&
                x.Month == addDate.Month
            ).Select(x => new {
                FileId = x.FileId,
                Path = _storage.getFilePath(x.CmFile),
                Name = x.CmFile.Name
            }).FirstOrDefault();

            _logger.LogInformation("========================== 기온및설비관리(설비가동현황) =======================");
            DataTable facilityTime = _service.GetFacilityTime(Util.ToInt(siteId), today);

            //그래프
            DataTable facilityTimeGraph = _service.GetFacilityTimeGraph(Util.ToInt(siteId), today);

            _logger.LogInformation("========================== 에너지사용량(전기/가스/수도) =======================");
            // 에너지사용량 - 사용량
            DataTable energyUsage = _service.GetEnergyData(Util.ToInt(siteId), today, 1, false);
            // 에너지사용량 - 사용량 그래프
            DataTable energyUsageGraph = _service.GetEnergyData(Util.ToInt(siteId), today, 1, true);
            // 에너지사용량 - 단가변동
            DataTable energyCost = _service.GetEnergyData(Util.ToInt(siteId), today, 2, false);

            _logger.LogInformation("========================== 에너지요금분석(전기/가스/수도) =======================");
            // 에너지요금분석 - 요금분석
            DataTable energyCharge = _service.GetEnergyData(Util.ToInt(siteId), today, 3, false);
            // 에너지요금분석 - 요금분석 그래프
            DataTable energyChargeGraph = _service.GetEnergyData(Util.ToInt(siteId), today, 3, true);
            // 에너지요금분석 - 증감사유
            var energyAnalysis = _context.FmsEnergyAnalysis.Where(x => x.SiteId == Util.ToInt(siteId) && x.Year == addDate.Year && x.Month == addDate.Month)
            .Select(x => new {
                x.FuelTypeId,
                x.PriceTypeId,
                x.Content
            }).ToList();


            _logger.LogInformation("========================== 법정검사 =======================");
            DataTable legalExamination = _service.GetLegalExamination(Util.ToInt(siteId), addDate);



            _logger.LogInformation("========================== 지난달 월간보고서 데이터! =======================");
            var lastMonthDatas = _context.FmsMonthlyReport.Where(
              x => x.SiteId == Util.ToInt(siteId) &&
              x.AddDate.Year == addDate.AddMonths(-1).Year &&
              x.AddDate.Month == addDate.AddMonths(-1).Month
            ).Select(x => new {
                x.FacilityStandards,
                x.RentalStandards,
                x.HumanCountStatus,
                x.ManagementOfficeContact,
                x.RelatedInstitutionsContact,
                x.UserChangeStatus,
                x.TenantContact,
            }).FirstOrDefault();

            return Ok(new {
                SiteInfo = siteInfo,
                OrganizationChartStatus = organizationChartStatus,
                LastMonthDatas = lastMonthDatas,
                RentalStatus = rentalStatus,
                LayoutStatus = layoutStatus,
                FacilityTime = facilityTime,
                FacilityTimeGraph = facilityTimeGraph,
                LegalExamination = legalExamination,
                EnergyUsage = energyUsage,
                EnergyUsageGraph = energyUsageGraph,
                EnergyCost = energyCost,
                EnergyCharge = energyCharge,
                EnergyChargeGraph = energyChargeGraph,
                EnergyAnalysis = energyAnalysis,
            });
        }

        /// <summary>
        /// 저장
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public IActionResult Save([FromBody] FmsMonthlyReport data, [FromQuery] bool isCreate) {
            _logger.LogInformation($"Save isCreate({isCreate})");
            //_logger.LogInformation(data.Dump());

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

        [HttpPost("[action]")]
        public IActionResult Approve([FromQuery] string siteId, [FromQuery] string approverUserId, [FromQuery] DateTime addDate, [FromQuery] string businessFieldId) {
            _service.Approve(Util.ToInt(siteId), approverUserId, addDate, Util.ToInt(businessFieldId));
            return Ok();
        }

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

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

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

            return query;
        }

        [HttpDelete("[action]")]
        public IActionResult Delete([FromQuery] string siteId, [FromQuery] DateTime addDate, [FromQuery] string businessFieldId) {
            _service.Delete(Util.ToInt(siteId), addDate, Util.ToInt(businessFieldId));
            return Ok();
        }

    }
}