using System;
using System.IO;
using System.Linq;
using FMSAdmin.Data;
using FMSAdmin.Entities;
using FMSAdmin.Helpers;
using FMSAdmin.Models;
using FMSAdmin.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using OfficeOpenXml;

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

        private readonly MonthWorkService _serviceMonthWork;

        public WeekWorkController(
            ILogger<WeekWorkController> logger,
            FMSContext context,
            WeekWorkService service,
            MonthWorkService serviceMonthWork
        ) {
            _logger = logger;
            _context = context;
            _service = service;
            _serviceMonthWork = serviceMonthWork;
        }

        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult ListCalendar(int siteId, int? year = null, int? month = null) {
            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 query = _service.GetWeek(siteId, startDate, endDate);
            var list = query.Select(x => new {
                Id = x.WeekKeyWorkId,
                SiteId = x.SiteId,
                Title = x.WorkName,
                Date = x.WorkDate.ToString("yyyy-MM-dd")
            }).ToList();

            var workName = _serviceMonthWork.GetKeyWork(siteId, selectMonth.Month);
            var result = new {
                Year = selectMonth.Year,
                Month = selectMonth.Month,
                Theme = workName,
                StartDate = startDate.ToString("yyyy-MM-dd"),
                EndDate = endDate.ToString("yyyy-MM-dd"),
                KeyWorkList = list,
            };

            return Ok(result);
        }

        /// <summary>
        /// 조회
        /// </summary>
        [HttpGet("{siteId}/{workDate}")]
        public IActionResult Get(int siteId, string workDate) {
            var data = _service.Get(siteId, workDate);
            if (data.Count() == 0) {
                return NotFound("중점업무 정보를 찾을 수 없습니다.");
            }
            var list = data.Select(x => new {
                x.WeekKeyWorkId,
                x.SiteId,
                CmSite = new {
                    x.CmSite.Name,
                },
                x.Year,
                x.Month,
                x.Week,
                x.WorkDate,
                x.WorkName,
            });
            return Ok(list.First());
        }

        /// <summary>
        /// 수정
        /// </summary>
        [HttpPost("{siteId}/{workDate}")]
        public IActionResult Edit(int siteId, string workDate, [FromBody] FmsWeekKeyWork data) {
            if (ModelState.IsValid) {
                _service.Edit(siteId, workDate, data);
            } else {
                return BadRequest(ModelState);
            }

            return Ok();
        }

        /// <summary>
        /// 등록
        /// </summary>
        [HttpPut]
        public IActionResult Create([FromBody] FmsWeekKeyWork data) {

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

        /// <summary>
        /// 삭제
        /// </summary>
        [HttpDelete("{siteId}/{workDate}")]
        public IActionResult Delete(int siteId, string workDate) {
            _service.Delete(siteId, workDate);
            return Ok();
        }
    }
}