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;

namespace FMSApp.Controllers {
    [Authorize]
    [ApiController]
    [ApiVersion("1")]
    [Route("api/app/[controller]")]
    public class AnnouncementController : Controller {
        private readonly ILogger<AnnouncementController> _logger;
        private readonly FMSContext _context;
        private readonly AnnouncementService _service;
        private readonly SiteService _siteService;
        private readonly StorageHelper _storage;

        public AnnouncementController(
            ILogger<AnnouncementController> logger,
            FMSContext context,
            AnnouncementService service,
            SiteService siteService,
            StorageHelper storage
            ) {
            _logger = logger;
            _context = context;
            _service = service;
            _siteService = siteService;
            _storage = storage;
        }

        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet]
        public IActionResult List([FromQuery] PagingRequest req, [FromQuery] string siteId, bool businessAuth) {
            _logger.LogInformation("req" + req.Dump());
            var user = _context.CmUser.FirstOrDefault(x => x.UserId == User.Identity.Name);
            var query = _FilterAndSort(req);
            if (!string.IsNullOrEmpty(siteId)) {
                query = query.Where(x => x.SiteId == Util.ToInt(siteId) || x.IsAllView == true);
            }
            //query = query.Where(x => x.AddDate < DateTime.Now.AddDays(1).Date && x.UpdateDate >= DateTime.Now.Date);
            if (businessAuth && user != null && user.BusinessFieldId != null) {
                var businessCommon = _context.CmBusinessField.FirstOrDefault(x => x.Name == "공통");
                query = query.Where(x => (new int[] { businessCommon.BusinessFieldId, user.BusinessFieldId.Value }).Contains(x.BusinessFieldId) || x.IsAllView == true);
            }

            var list = query.Select(x => new {
                x.SiteId,
                Name = Util.ToBool(x.CmUser.IsSysop) ? "운영자" : (Util.ToBool(x.IsAllView) ? "본사지침" : x.CmSite.Name),
                x.Title,
                x.AnnouncementId,
                // CmSite = new {
                //     Name = x.CmSite.Name// _siteService.Get(x.SiteId).FirstOrDefault().Name
                // },
                CmUser = new {
                    Name = x.CmUser.Name
                },
                CmBusinessField = new {
                    x.CmBusinessField.Name,
                },
                Date = new {
                    AddDate = x.AddDate.ToString("yyyy.MM.dd")
                },
                IsAllView = Util.ToBool(x.IsAllView),
                IsSysop = x.CmUser.IsSysop,
                x.ReadCount,
            });
            var paging = PagingList.Pagination(list, req.page, req.limit);
            return Ok(paging);
        }

        [HttpGet("[action]")]
        public IActionResult Get([FromQuery] string siteId, [FromQuery] string annId) {
            var query = _service.GetAll()
                .Where(x => x.AnnouncementId == Util.ToInt(annId));

            //조회수 증가
            var announcement = query.FirstOrDefault();
            if (announcement != null && User.Identity.Name != announcement.RegisterUserId) {
                _service.AddCount(Util.ToInt(annId));
            }

            var item = query.Select(x => new {
                x.SiteId,
                x.Title,
                x.Contents,
                x.CmUser.Name,
                x.AddDate,
                x.UpdateDate,
                x.BusinessFieldId,
                BusinessFieldName = x.CmBusinessField.Name,
                x.RegisterUserId,
                CmFile = _storage.ParseFile(x.CmFile),
                CmBusinessField = new {
                    BusinessFieldId = x.CmBusinessField.BusinessFieldId,
                    Name = x.CmBusinessField.Name
                },
                CmUser = new {
                    UserId = x.CmUser.UserId
                },
                x.AnnouncementId,
                x.IsUse,
                IsAllView = Util.ToBool(x.IsAllView),
                x.ReadCount,
            }).FirstOrDefault();

            return Ok(item);
        }

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

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

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

            return query;
        }

        /// <summary>
        /// 저장
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public IActionResult Save([FromBody] CmAnnouncement data) {

            _logger.LogInformation("Save");
            //_logger.LogInformation(data.Dump());
            if (ModelState.IsValid) {
                _service.Save(data);
            } else {
                return BadRequest(ModelState);
            }
            return Ok();
        }

        [HttpDelete("{siteId}/{annId}")]
        public IActionResult Delete(int siteId, int annId) {
            _service.Delete(siteId, annId);
            return Ok();
        }

    }
}