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

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

        }

        /// <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);
        }

        /// <summary>
        /// 엑셀파일 익스포트
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpGet("excel")]
        public IActionResult ExportExcel([FromQuery] PagingRequest req, string filename) {
            req.page = 1;
            req.limit = 0;
            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>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{siteId}/{id}/{historyId}")]
        public IActionResult Get(int siteId, int id, int historyId) {
            var data = _service.Gets(id, siteId);
            if (data.Count() == 0) {
                return NotFound("공기구정보를 찾을 수 없습니다.");
            }
            var item = data.Select(x => new {
                x.EquipmentId,
                x.EquipmentTypeId,
                FmsEquipmentCodeType = new {
                    x.FmsEquipmentCodeType.Name
                },
                x.WarehouseId,
                BusinessFieldId = x.FmsMaterialWarehouse.BusinessFieldId,
                FmsMaterialWarehouse = new {
                    x.FmsMaterialWarehouse.Name,
                },
                x.SiteId,
                CmSite = new {
                    x.Site.Name,
                },
                ImageFile = _storage.ParseFile(x.ImageFile),
                x.Name,
                x.Standard,
                x.Unit,
                x.SupplierName,
                x.SupplierPhoneNo,
                TotalStockCount = _context.SiteConfig.Single().UseEquipmentRent ? x.FmsEquipmentHistory.Where(x => x.EquipmentHistoryId == historyId).Select(x => x.TotalStockCount).FirstOrDefault()
                                                                                : x.FmsEquipmentHistory.Where(x => x.EquipmentId == id).OrderByDescending(x => x.EquipmentHistoryId).Select(x => x.TotalStockCount).FirstOrDefault(),
                CurrentStockCount = x.FmsEquipmentHistory.Where(x => x.EquipmentHistoryId == historyId).Select(x => x.CurrentStockCount).FirstOrDefault(),
            });
            return Ok(item.First());
        }

        /// <summary>
        /// 조회
        /// </summary>
        /// <param name="siteId"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{siteId}/{id}")]
        public IActionResult Get(int siteId, int id) {
            var data = _service.Gets(id, siteId);
            if (data.Count() == 0) {
                return NotFound("공기구정보를 찾을 수 없습니다.");
            }
            var item = data.Select(x => new {
                x.EquipmentId,
                x.EquipmentTypeId,
                FmsEquipmentCodeType = new {
                    x.FmsEquipmentCodeType.Name
                },
                x.WarehouseId,
                FmsMaterialWarehouse = new {
                    x.FmsMaterialWarehouse.Name
                },
                x.SiteId,
                CmSite = new {
                    x.Site.Name,
                },
                ImageFile = _storage.ParseFile(x.ImageFile),
                x.Name,
                x.Standard,
                x.Unit,
                x.SupplierName,
                x.SupplierPhoneNo,
                TotalStockCount = x.FmsEquipmentHistory.OrderByDescending(x => x.EquipmentHistoryId).Select(x => x.TotalStockCount).FirstOrDefault(),
                CurrentStockCount = x.FmsEquipmentHistory.OrderByDescending(x => x.EquipmentHistoryId).Select(x => x.CurrentStockCount).FirstOrDefault(),
            });

            return Ok(item.First());
        }

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

            return Ok();
        }

        /// <summary>
        /// 등록
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult Create([FromBody] FmsEquipment data) {
            ModelState.Remove("RegisterUserId");
            data.RegisterUserId = User.Identity.Name;
            if (ModelState.IsValid) {
                _service.Create(data);
            } else {
                return BadRequest(ModelState);
            }
            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<FmsEquipment> list = new List<FmsEquipment>();
            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 ? 10 : 9;
                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 business = excelUploadHelper.GetValue(worksheet, "업무분야(*)", i, true);
                        var type = excelUploadHelper.GetValue(worksheet, "분류(*)", i, true);
                        var name = excelUploadHelper.GetValue(worksheet, "이름(*)", i, true);
                        var unit = excelUploadHelper.GetValue(worksheet, "단위", i);
                        var standard = excelUploadHelper.GetValue(worksheet, "규격", i);
                        var warehouse = excelUploadHelper.GetValue(worksheet, "창고명칭(*)", i, true);
                        var storedCount = excelUploadHelper.GetValue(worksheet, "최초입고수량", i);
                        var supplierName = excelUploadHelper.GetValue(worksheet, "공급업체", i);
                        var supplierPhoneNo = excelUploadHelper.GetValue(worksheet, "업체연락처", i);

                        _logger.LogInformation("site " + site);
                        _logger.LogInformation("type " + type);
                        _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 typeId = _context.FmsEquipmentCodeType.Where(x => x.Name == type && x.IsUse == true).Select(x => x.EquipmentTypeId).SingleOrDefault();
                        var businessId = _context.CmBusinessField.Where(x => x.Name == business && x.IsUse == true).Select(x => x.BusinessFieldId).SingleOrDefault();
                        var warehouseId = _context.FmsMaterialWarehouse.Where(x => x.SiteId == siteId && x.Name == warehouse && x.BusinessFieldId == businessId && x.IsUse == true).Select(x => x.WarehouseId).SingleOrDefault();

                        if (isAdmin) excelUploadHelper.EntityIdCheck(siteId, "사옥", rowName);

                        _logger.LogError("########" + warehouse + "++__" + business);
                        excelUploadHelper.EntityIdCheck(typeId, "분류명", rowName);
                        excelUploadHelper.EntityIdCheck(businessId, "업무분야", rowName);
                        excelUploadHelper.EntityIdCheck(warehouseId, "창고명", rowName);
                        excelUploadHelper.NumericCheck(storedCount, "입고수량", rowName);


                        var equipment = new FmsEquipment {
                            SiteId = siteId,
                            EquipmentTypeId = typeId,
                            Name = name,
                            WarehouseId = warehouseId,
                            StoredCount = Util.ToInt(storedCount),
                            Unit = unit,
                            Standard = standard,
                            AddDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            RegisterUserId = User.Identity.Name,
                            SupplierName = supplierName,
                            SupplierPhoneNo = supplierPhoneNo,
                            ExcelRowNum = i
                        };
                        // 글자수 체크
                        TryValidateModel(equipment);

                        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 == equipment.SiteId
                                                        && x.EquipmentTypeId == equipment.EquipmentTypeId
                                                        && x.Name == equipment.Name
                                                        && x.Standard == equipment.Standard).Select(x => x.ExcelRowNum).SingleOrDefault();

                        if (overlapRowNum != 0) {
                            throw new ServiceException("파일 내 동일 정보가 존재합니다.[공기구분류-공기구명-규격]" + "(" + (overlapRowNum) + "번 행 - " + (i) + "번 행)");
                        }

                        if (_service.checkName(equipment, true) > 0) {
                            throw new ServiceException("기존 공기구와 동일 정보가 존재합니다.[공기구분류-공기구명-규격]" + rowName);
                        }

                        // 데이터 값 설정
                        list.Add(equipment);
                    }
                }
            }
            if (list.Count > 0) {
                _service.ImportExcel(list);

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


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

            return Ok();
        }

        // 셀렉트 공통
        private dynamic _ListSelect(IQueryable<FmsEquipment> query) {
            var list = query.Select(x => new {
                x.EquipmentId,
                x.SiteId,
                SiteName = x.Site.Name,
                x.EquipmentTypeId,
                EquipmentTypeName = x.FmsEquipmentCodeType.Name,
                x.Name,
                x.Standard,
                x.Unit,
                StoredCount = x.FmsEquipmentHistory.Where(x => x.EquipmentStateTypeId == 1).Sum(x => x.StoredCount),
                x.AddDate,
                x.SupplierName,
                x.SupplierPhoneNo,
                x.WarehouseId,
                WarehouseName = x.FmsMaterialWarehouse.Name,
                CurrentStockCount = x.FmsEquipmentHistory.OrderByDescending(x => x.EquipmentHistoryId).Select(x => x.CurrentStockCount).FirstOrDefault() ?? 0,
                TotalStockCount = x.FmsEquipmentHistory.OrderByDescending(x => x.EquipmentHistoryId).Select(x => x.TotalStockCount).FirstOrDefault() ?? 0,
                RentCount = x.FmsEquipmentHistory.Where(x => x.IsReturned == false).Sum(x => x.CurrentRentCount) ?? 0,
                LossCount = x.FmsEquipmentHistory.Sum(x => x.LossCount),
                x.UpdateDate,

            });
            return list;
        }

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

            // 기본 Entity 검색
            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));
            }

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

            return query;
        }

    }
}