using System;
using System.Linq;
using System.Threading.Tasks;

using FMSAdmin.Data;
using FMSAdmin.Models;
using FMSAdmin.Entities;
using FMSAdmin.Services;

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using FMSAdmin.Helpers;
using System.Data;
using System.IO;
using OfficeOpenXml;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Collections;


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

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


        /// <summary>
        /// 검색 & 정렬
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        private IQueryable<CmSite> _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));
            }

            query = query.Sort(req.sort);

            return query;
        }

        // 셀렉트 공통
        private dynamic _ListSelect(IQueryable<CmSite> query) {
            var list = query.Select(x => new {
                x.SiteId,
                x.Name,
                x.Address1,
                x.PhoneNo,
                x.IsControlSchedule,
                x.CompletionDate,
                x.BuildingSize,
                GrossArea = AreaParse(x.GrossArea),
                BuildingArea = AreaParse(x.BuildingArea),
                x.FloorAreaRatio,
                x.BuildingCoverageRatio,
                IsUse = x.IsUse.GetValueOrDefault() ? "Y" : "N",
                x.SortOrderNo
            });
            return list;
        }

        private static string AreaParse(String areaVal) {
            string returnVal = "";
            float val;
            if (!Util.IsNullOrEmpty(areaVal) && float.TryParse(areaVal, out val)) {
                returnVal = val.ToString("#,##0.00") + "㎡ (" + (val / 3.3058).ToString("#,##0.00") + "평)";
            }
            return returnVal;
        }

        /// <summary>
        /// 목록
        /// </summary>
        /// <param name="req"></param>
        /// <param name="siteId"></param>
        /// <param name="type"></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>
        /// <param name="siteId"></param>
        /// <returns></returns>
        [HttpGet("{siteId}")]
        public IActionResult Get(int siteId) {
            var siteInfo = _service.Get(siteId);
            if (siteInfo.Count() == 0) {
                return NotFound("사이트 정보를 찾을 수 없습니다.");
            }
            var list = siteInfo.Select(x => new {
                x.SiteId,
                x.Name,
                x.PhoneNo,
                x.AddressZip1,
                x.CompletionDate, //준공연도
                x.Address1,
                x.Adderss2,
                x.BuildingSize, //건축규모
                GrossArea = x.GrossArea,
                BuildingArea = x.BuildingArea,
                x.FloorAreaRatio, //용적율
                x.BuildingCoverageRatio, //건폐율
                x.MainUse, //주용도
                x.MainUseIndex,
                x.IsControlSchedule, //제어스케줄
                x.ScheduleCheckHour, //스케쥴알림시간
                x.Standard, //용도별 표준값
                x.Hdd, // HDD 기준온도
                x.Cdd, // CDD 기준 온도
                x.Url, //홈페이지
                x.Comment, //비고
                ImageFile = _storage.ParseFile(x.ImageFile),
                x.ApiSido,
                x.ApiSigun,
                x.ImageMapX,
                x.ImageMapY,
                x.IsUse,
                x.DesignSupervision,
                x.ConstructionCompany,
                x.ConstructionPeriod,
                x.Structure,
                x.LobbyFloor,
                x.OfficeFloor,
                x.ToiletFloor,
                x.EVHall,
                x.ParkingLot,
                x.ParkingFacilities,
                x.OuterWall,
                LandArea = x.LandArea,
                LandscapingArea = x.LandscapingArea,
                x.BuildingFloors,
                x.BuildingHeight,
                x.ConversionRate,
                x.AuditoriumFacilities
            });
            return Ok(list.First());
        }

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

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

        /// <summary>
        /// 수정
        /// </summary>
        /// <param name="siteId"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("{siteId}")]
        public IActionResult Edit(int siteId, [FromBody] CmSite data) {
            _logger.LogInformation("Edit");
            if (siteId != data.SiteId) {
                return BadRequest("잘못된 접근입니다.");
            }
            if (ModelState.IsValid) {
                _service.Edit(siteId, data);
            } else {
                return BadRequest(ModelState);
            }

            return Ok();
        }

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

    }

}