using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using FMSAdmin.Data;
using FMSAdmin.Entities;
using FMSAdmin.Helpers;
using FMSAdmin.Models;
using FMSAdmin.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using OfficeOpenXml;

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

        public ZoneController(
            ILogger<ZoneController> logger,
            FMSContext context,
            ZoneService service
        ) {
            _logger = logger;
            _context = context;
            _service = service;
        }

        /// <summary>
        /// 검색 & 정렬
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        private IQueryable<CmZone> _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));
            }
            if (req.siteIds != null && req.siteIds.Length > 0) {
                query = query.Where(x => req.siteIds.Contains(x.SiteId));
            }

            // 고정정렬 (사옥 준공순)
            var sortQuery = query.OrderBy(x => x.CmSite.SortOrderNo);

            // 추가 정렬
            sortQuery = sortQuery.ThenSort(req.sort);

            return sortQuery;

        }


        /// <summary>
        /// 셀렉트 공통
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        private dynamic _ListSelect(IQueryable<CmZone> query) {
            var list = query.Select(x => new {
                x.SiteId,
                x.BuildingId,
                x.FloorId,
                x.ZoneId,
                SiteName = x.CmSite.Name,
                BuildingName = x.CmBuilding.Name,
                FloorName = x.CmFloor.Name,
                x.Name,
                SortNum = x.CmFloor.CmFloorCode.SortNum,
            });
            return list;
        }
        /// <summary>
        /// 목록
        /// </summary>
        /// <param name="req"></param>
        /// <param name="siteId"></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>
        [HttpGet("{siteId}/{id}")]
        public IActionResult Get(int siteId, int id) {
            var data = _service.Get(id, siteId);
            if (data.Count() == 0) {
                return NotFound("사이트 정보를 찾을 수 없습니다.");
            }
            var list = data.Select(x => new {
                x.ZoneId,
                x.Name,
                x.SiteId,
                x.BuildingId,
                x.FloorId,
                CmSite = new {
                    x.CmSite.Name,
                },
                CmBuilding = new {
                    x.CmBuilding.Name
                },
                CmFloor = new {
                    x.CmFloor.Name
                },
            });
            return Ok(list.First());
        }

        /// <summary>
        /// 수정
        /// </summary>
        [HttpPost("{siteId}/{id}")]
        public IActionResult Edit(int siteId, int id, [FromBody] CmZone data) {
            _logger.LogInformation("Edit");
            _logger.LogInformation("id:" + id);
            _logger.LogInformation("siteId:" + siteId);
            //_logger.LogInformation(data.Dump());
            if (id != data.ZoneId) {
                return BadRequest("잘못된 접근입니다.>>");
            }

            if (ModelState.IsValid) {
                _service.Edit(id, siteId, data);
            } else {
                return BadRequest(ModelState);
            }

            return Ok();
        }

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

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

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

        [HttpPost]
        [Route("[action]")]
        public IActionResult ImportExcelAdmin(IFormFile excelFile) {
            return (ImportExcel(excelFile, true));
        }

        /// <summary>
        /// 엑셀파일 임포트
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public IActionResult ImportExcel(IFormFile excelFile, bool isAdmin = false) {
            IList<CmZone> list = new List<CmZone>();
            var userInfo = _context.CmUser.Where(x => x.UserId == User.Identity.Name).SingleOrDefault();

            using (ExcelPackage excelPackage = new ExcelPackage(excelFile.OpenReadStream())) {
                var worksheet = excelPackage.Workbook.Worksheets[0];
                int colCnt = isAdmin ? 4 : 3;
                ExcelUploadHepler excelUploadHelper = new ExcelUploadHepler();
                //헤더세팅
                excelUploadHelper.GenerateColumns(worksheet, 1, colCnt);

                for (int i = worksheet.Dimension.Start.Row + 1; i <= worksheet.Dimension.End.Row; i++) {
                    if (!excelUploadHelper.IsRowEmpty(worksheet, i, colCnt)) {
                        var site = isAdmin ? excelUploadHelper.GetValue(worksheet, "사옥(*)", i, true) : "";
                        var building = excelUploadHelper.GetValue(worksheet, "빌딩명(*)", i, true);
                        var floor = excelUploadHelper.GetValue(worksheet, "층명칭(*)", i, true);
                        var name = excelUploadHelper.GetValue(worksheet, "구역명칭(*)", i, true);

                        _logger.LogInformation("site " + site);
                        _logger.LogInformation("type " + building);
                        _logger.LogInformation("codnamee " + name);

                        var rowName = "(" + (i) + "번 행)";

                        var siteId = isAdmin ? _context.CmSite.Where(x => x.Name == site && x.IsUse == true).Select(x => x.SiteId).SingleOrDefault() : userInfo.SiteId;
                        var buildingId = _context.CmBuilding.Where(x => x.SiteId == siteId && x.Name == building && x.IsUse == true).Select(x => x.BuildingId).SingleOrDefault();
                        var floorId = _context.CmFloor.Where(x => x.SiteId == siteId && x.BuildingId == buildingId && x.Name == floor).Select(x => x.FloorId).SingleOrDefault();
                        if (isAdmin) excelUploadHelper.EntityIdCheck(siteId, "사옥", rowName);
                        excelUploadHelper.EntityIdCheck(buildingId, "빌딩명", rowName);
                        excelUploadHelper.EntityIdCheck(floorId, "층명칭", rowName);

                        var zone = new CmZone {
                            SiteId = siteId,
                            BuildingId = buildingId,
                            FloorId = floorId,
                            Name = name,
                            ExcelRowNum = i
                        };


                        //StringLength 체크 
                        TryValidateModel(zone);

                        if (!ModelState.IsValid) throw new ServiceException(string.Join(" ",
                                        ModelState.Values
                                        .SelectMany(x => x.Errors)
                                        .Select(x => x.ErrorMessage)) + rowName);

                        //중복체크
                        var overlapRowNum = list.Where(x => x.SiteId == zone.SiteId
                                                    && x.BuildingId == zone.BuildingId
                                                    && x.FloorId == zone.FloorId
                                                    && x.Name == zone.Name).Select(x => x.ExcelRowNum).SingleOrDefault();

                        if (overlapRowNum != 0)
                            throw new ServiceException("파일 내 동일 정보가 존재합니다.[빌딩명-층명칭-구역명칭]" + "(" + (overlapRowNum) + "번 행 - " + (i) + "번 행)");


                        if (_service.checkName(zone, true) > 0) {
                            throw new ServiceException("기존 구역정보와 동일 정보가 존재합니다.[빌딩명-층명칭-구역명칭]" + rowName);
                        }
                        // 데이터 값 설정
                        list.Add(zone);
                    }
                }
            }
            if (list.Count > 0) {

                _service.ImportExcel(list);

                return Ok($"엑셀업로드를 성공하였습니다. {list.Count}건의 데이터가 등록되었습니다.");
            } else {
                throw new ServiceException("등록할 데이터가 없습니다.");
            }
        }


    }
}