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 GuidelineController : Controller {
        private readonly ILogger<GuidelineController> _logger;
        private readonly FMSContext _context;
        private readonly GuidelineService _service;
        private readonly StorageHelper _storage;

        public GuidelineController(
            ILogger<GuidelineController> logger,
            FMSContext context,
            GuidelineService service,
            StorageHelper storage
            ) {
            _logger = logger;
            _context = context;
            _service = service;
            _storage = storage;
        }

        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet]
        public IActionResult List([FromQuery] PagingRequest req, [FromQuery] string siteId) {
            var query = _FilterAndSort(req);

            var list = _ListSelect(query);

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

        /// <summary>
        /// 조회
        /// </summary>
        [HttpGet("{siteId}/{id}/{isCount}")]
        public IActionResult Get(int siteId, int id, int isCount) {
            var data = _service.Gets(id, siteId);
            if (data.Count() == 0) {
                return NotFound("공지사항 정보를 찾을 수 없습니다.");
            }

            //조회수 증가
            if (isCount == 1) {
                _service.AddCount(id, siteId);
            }

            var item = data.Select(x => new {
                x.GuidelineId,
                x.SiteId,
                CmSite = new {
                    x.CmSite.Name,
                },
                x.BusinessFieldId,
                CmBusinessField = new {
                    x.CmBusinessField.Name,
                },
                x.Title,
                x.Contents,
                RegisterUser = x.CmUser.Name,
                x.FileId,
                CmFile = _storage.ParseFile(x.CmFile),
                x.AddDate,
                x.UpdateDate,
                x.IsUse,
                x.ReadCount,
                IsSysop = x.CmUser.IsSysop,
                IsAllView = Util.ToBool(x.IsAllView),
                IsAllViewName = (Util.ToBool(x.IsAllView)) ? "본사지침" : "",
            });


            return Ok(item.First());
        }

        /// <summary>
        /// 엑셀파일 익스포트
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpGet("excel")]
        public IActionResult ExportExcel([FromQuery] PagingRequest req, string filename) {
            req.page = 1;
            req.limit = 0;
            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>
        [HttpPost("{siteId}/{id}")]
        public IActionResult Edit(int siteId, int id, [FromBody] CmGuideline data) {
            if (id != data.GuidelineId) {
                return BadRequest("잘못된 접근입니다.");
            }

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

            return Ok();
        }

        /// <summary>
        /// 등록
        /// </summary>
        [HttpPut]
        public IActionResult Create([FromBody] CmGuideline data) {
            _logger.LogInformation("Create");
            //_logger.LogInformation(data.Dump());

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

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

            return Ok();
        }

        // 셀렉트 공통
        private dynamic _ListSelect(IQueryable<CmGuideline> query) {
            var list = query.Select(x => new {
                x.GuidelineId,
                x.SiteId,
                SiteName = x.CmSite.Name,
                x.BusinessFieldId,
                BusinessFieldName = x.CmBusinessField.Name,
                IsAllView = x.IsAllView.GetValueOrDefault() ? "Y" : "N",
                x.Title,
                RegisterUser = x.CmUser.Name,
                AddDate = x.AddDate.ToString("yyyy/MM/dd"),
                UpdateDate = x.UpdateDate.ToString("yyyy/MM/dd"),
                x.IsUse,
                IsSysop = x.CmUser.IsSysop,
                FilePath = _storage.getFilePath(x.CmFile),
                FileName = x.CmFile.Name
            });
            return list;
        }

        // 검색 & 정렬 공통
        private IQueryable<CmGuideline> _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) || x.IsAllView == true);
            }
            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 == "공통");
            }

            var sortQuery = query.OrderByDescending(x => x.CmSite.IsAdmin);
            sortQuery = sortQuery.ThenBy(x => x.CmSite.SortOrderNo);
            sortQuery = sortQuery.ThenSort(req.sort);


            return query;
        }
    }
}