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

        public FacilityController(
            ILogger<FacilityController> logger,
            FMSContext context,
            FacilityService 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.FacilityCode,
                CmSite = new {
                    x.CmSite.Name,
                },
                CmBuilding = new {
                    x.CmBuilding.BuildingId,
                    x.CmBuilding.Name,
                },
                CmFloor = new {
                    x.CmFloor.FloorId,
                    x.CmFloor.Name,
                },
                CmZone = new {
                    x.CmZone.ZoneId,
                    x.CmZone.Name,
                },
                x.FirstClassId,
                FirstClass = new {
                    x.FmsFacilityCodeClass.Name,
                },
                x.SecondClassId,
                SecondClass = new {
                    x.FmsFacilityCodeClass1.Name,
                },
                x.ThirdClassId,
                ThirdClass = new {
                    x.FmsFacilityCodeClass2.Name,
                },
                x.Name,
                x.Manufacturer,
                x.FacilityCapacity,
                x.IsUse,
            });
            var paging = PagingList.Pagination(list, req.page, req.limit);
            return Ok(paging);
        }

        [HttpGet("[action]")]
        public IActionResult Get([FromQuery] string siteId, [FromQuery] string facilityCode) {
            _logger.LogInformation("siteId : " + siteId + ", facilityCode : " + facilityCode);
            var query = _service.GetAll().Where(x => x.SiteId == Util.ToInt(siteId)
                                            && x.FacilityCode == Util.ToInt(facilityCode));
            var item = query.Select(x => new {
                x.SiteId,
                x.FileId,
                CmFile = _storage.ParseFile(x.CmFile),
                x.FacilityCode,
                x.FacilityTypeId,
                x.FirstClassId,
                x.SecondClassId,
                x.ThirdClassId,
                x.DeviceType,
                x.Name,
                x.Nickname,
                x.FacilityUsage,
                x.Manufacturer,
                x.ManufactureDate,
                x.IsUse,
                x.FacilityCapacity,
                x.Rfid,
                x.RatedPowerConsumption,
                x.RatedCop,
                x.ManufactureSerial,
                x.ManufactureModel,
                x.Supplier,
                x.SupplierPhoneNo,
                x.BuildingId,
                x.FloorId,
                x.ZoneId,
                x.InstallDate,
                x.OperationStartDate,
                x.MainContactorUserId,
                MainContactor = new {
                    x.MainContactor.Name,
                },
                x.SubContactorUserId,
                SubContactor = new {
                    x.SubContactor.Name,
                },
                x.FacilityCost,
                x.FacilityCount,
                x.FuelTypeId,
                x.ContractType,
                ContractTypeName = _context.FmsContractType.FirstOrDefault(c => c.ContractTypeId == x.ContractType).Name,
                x.Note,
                x.Multiple,
            }).FirstOrDefault();

            return Ok(item);
        }

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

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

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

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

            query = query.Where(x => !(new int[] { 99, 100, 101, 102, 103 }).Contains(x.FacilityTypeId));

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

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

            return query;
        }

    }
}