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 MonthWorkController : Controller {
        private readonly ILogger<MonthWorkController> _logger;
        private readonly FMSContext _context;
        private MonthWorkService _service;

        public MonthWorkController(
            ILogger<MonthWorkController> logger,
            FMSContext context,
            MonthWorkService service
        ) {
            _logger = logger;
            _context = context;
            _service = service;
        }

        /// <summary>
        /// /// 검색 & 정렬
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        private IQueryable<FmsMonthKeyWork> _FilterAndSort(PagingRequest req) {
            var query = _service.GetAll();

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

            // 고정정렬 (사옥 준공순)
            var sortQuery = query.OrderBy(x => x.CmSite.SortOrderNo);

            // 추가 정렬
            sortQuery = sortQuery.ThenSort(req.sort);

            return sortQuery;
        }


        /// <summary>
        /// 셀렉트 공통
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        private dynamic _ListSelect(IQueryable<FmsMonthKeyWork> query) {
            var list = query.Select(x => new {
                x.MonthKeyWorkId,
                x.SiteId,
                SiteName = x.CmSite.Name,
                x.Month,
                x.WorkName,
            });
            return list;
        }
        /// <summary>
        /// 목록
        /// </summary>
        /// <param name="req"></param>
        /// <param name="siteId"></param>
        /// <returns></returns>
        [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);
        }

        // 엑셀 다운로드
        [AllowAnonymous]
        [HttpGet("excel")]
        public IActionResult ExportExcel([FromQuery] PagingRequest req, string filename) {
            var query = _FilterAndSort(req);
            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);
        }

        /// <summary>
        /// 조회
        /// </summary>
        [HttpGet("{siteId}/{month}")]
        public IActionResult Get(int siteId, int month) {
            var data = _service.Get(siteId, month);
            if (data.Count() == 0) {
                return NotFound("사이트 정보를 찾을 수 없습니다.");
            }
            var list = data.Select(x => new {
                x.MonthKeyWorkId,
                x.SiteId,
                CmSite = new {
                    x.CmSite.Name,
                },
                x.Month,
                x.WorkName,
            });
            return Ok(list.First());
        }

        /// <summary>
        /// 수정
        /// </summary>
        [HttpPost("{siteId}/{month}")]
        public IActionResult Edit(int siteId, int month, [FromBody] FmsMonthKeyWork data) {

            if (ModelState.IsValid) {
                _service.Edit(siteId, month, data);
            } else {
                return BadRequest(ModelState);
            }

            return Ok();
        }

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

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

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

    }
}