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;

namespace FMSAdmin.Controllers {
    [Authorize]
    [ApiController]
    [ApiVersion("1")]
    [Route("api/[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) {
            var query = _FilterAndSort(req);

            var list = _ListSelect(query);

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



        // 검색 & 정렬 공통
        private IQueryable<FmsMonthlyReport> _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 == User.GetSiteId());
                query = query.Where(x => x.BusinessFieldId == req.businessFieldId || x.CmBusinessField.Name == "공통");
            }

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

            return query;
        }

        public dynamic _ListSelect(IQueryable<FmsMonthlyReport> query) {

            var list = query.Select(x => new {
                x.SiteId,
                SiteName = _context.CmSite.FirstOrDefault(site => site.SiteId == x.SiteId).Name,
                AddDate = x.AddDate.ToString("yyyy-MM-dd"),
                x.BusinessFieldId,
                x.Name,
                x.Contents,
                x.RegisterUserId,
                RegisterUserName = _context.CmUser.FirstOrDefault(user => user.UserId == x.RegisterUserId).Name,
                x.ApproveDate,
                RegisterDate = x.RegisterDate.Value.ToString("yyyy-MM-dd"),
                x.ApproverUserId,
                ApproverUserName = _context.CmUser.FirstOrDefault(user => user.UserId == x.ApproverUserId).Name,
            });

            return list;
        }


        [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 == addDate.Date
                && x.BusinessFieldId == Util.ToInt(businessFieldId)
            ).Select(x => new {
                x.SiteId,
                x.AddDate,
                x.BusinessFieldId,
                x.Name,
                x.Contents,
                x.SiteInfoDatas,
                x.Datas,
                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,
            }).FirstOrDefault();

            return Ok(item);
        }

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



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

        [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();
        }

    }
}