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

        public TenantController(
            ILogger<TenantController> logger,
            FMSContext context,
            TenantService 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.TenantId,
                x.Name,
                x.CompanyTypeId,
                CmCompanyType = new {
                    x.CmCompanyType.Name
                },
                x.RepresentativeName,
                x.RepresentativePhone,
                x.AreaSize,
                x.ExclusiveArea,
                x.BuildingId,
                CmBuilding = new {
                    x.CmBuilding.Name
                },
                x.FloorId,
                CmFloor = new {
                    x.CmFloor.Name
                },
                x.ChargeEmail,
                x.IsUse
            });
            var paging = PagingList.Pagination(list, req.page, req.limit);
            return Ok(paging);
        }

        [HttpGet("[action]")]
        public IActionResult Get([FromQuery] string siteId, [FromQuery] string tenantId) {
            var query = _service.GetAll()
                .Where(x => x.SiteId == Util.ToInt(siteId) && x.TenantId == Util.ToInt(tenantId));
            var item = query.Select(x => new {
                x.SiteId,
                x.TenantId,
                x.CompanyTypeId,
                CompanyTypeName = x.CmCompanyType.Name,
                x.BuildingId,
                BuildingName = x.CmBuilding.Name,
                x.FloorId,
                x.Name,
                x.RepresentativeName,
                x.RepresentativePhone,
                x.Fax,
                x.AreaSize,
                x.ExclusiveArea,
                x.ChargeName,
                x.ChargePhone,
                x.AddressZip,
                x.Address1,
                x.Address2,
                x.IsUse,
                x.ChargeEmail,
                x.Homepage,
                x.Comment
            }).FirstOrDefault();
            return Ok(item);
        }

        [HttpPost("[action]")]
        public IActionResult UpdateListData([FromBody] CmTenant data) {
            _logger.LogInformation("Save");
            //_logger.LogInformation(data.Dump());

            _service.UpdateListData(data);
            return Ok();
        }

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

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

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

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

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

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

            return query;
        }

    }
}