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

        public ManualController(
            ILogger<ManualController> logger,
            FMSContext context,
            ManualService 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);
            if (!string.IsNullOrEmpty(siteId)) {
                query = query.Where(x => x.SiteId == Util.ToInt(siteId));
            }
            var list = query.Select(x => new {
                x.SiteId,
                x.ManualId,
                x.ManualNo,
                x.ManualTypeId,    // 매뉴얼분류
                FmsManualType = new { //매뉴얼분류명
                    x.FmsManualType.Name
                },
                x.ManualGroupId,
                FmsManualGroup = new {
                    x.FmsManualGroup.Name
                },
                x.Name,
                x.Description,
            });
            var paging = PagingList.Pagination(list, req.page, req.limit);
            return Ok(paging);
        }

        [HttpGet("[action]")]
        public IActionResult Get([FromQuery] string siteId, [FromQuery] string ManualId) {
            var query = _service.GetAll()
                .Where(x => x.SiteId == Util.ToInt(siteId) && x.ManualId == Util.ToInt(ManualId));
            var item = query.Select(x => new {
                x.SiteId,
                x.ManualId,
                x.ManualNo,
                x.ManualTypeId,
                ManualTypeName = x.FmsManualType.Name,
                x.ManualGroupId,
                ManualGroupName = x.FmsManualGroup.Name,
                x.Name,
                x.Description,
            }).FirstOrDefault();
            return Ok(item);
        }

        /// <summary>
        /// 저장
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public IActionResult Save([FromBody] FmsManual data) {
            _logger.LogInformation("Save");
            //_logger.LogInformation(data.Dump());

            if (ModelState.IsValid) {
                data.CreateUserId = User.Identity.Name;
                _service.Save(data);
            } else {
                return BadRequest(ModelState);
            }
            return Ok();
        }

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

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

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

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

            return query;
        }

    }
}