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

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

        /// <summary>
        /// 리스트
        /// </summary>
        [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("yMMddHHmmssfff")}.xlsx";
            return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", excelName);
        }

        /// <summary>
        /// 엑셀파일 임포트
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public IActionResult ImportExcel(IFormFile file) {
            IList<Hashtable> list = new List<Hashtable>();
            using (ExcelPackage excelPackage = new ExcelPackage(file.OpenReadStream())) {
                var worksheet = excelPackage.Workbook.Worksheets[0];
                for (int i = worksheet.Dimension.Start.Row; i <= worksheet.Dimension.End.Row; i++) {

                    var name = worksheet.Cells[i, 1].Value;
                    var rfid = worksheet.Cells[i, 2].Value;
                    var code = worksheet.Cells[i, 3].Value;
                    list.Add(new Hashtable {
                        {"Name", name}
                    });
                }
            }
            //_service.ImportExcel(list);
            //return BadRequest(ex.Message);

            return Ok();
        }

        /// <summary>
        /// 조회
        /// </summary>
        [HttpGet("{siteId}/{orderId}/{materialId}")]
        public IActionResult Get(int siteId, int orderId, int materialId) {
            var data = _service.Gets(orderId, materialId, siteId);
            if (data.Count() == 0) {
                return NotFound("자재 발주 목록을 찾을 수 없습니다.");
            }
            var item = data.Select(x => new {
                x.PurchaseOrderId,
                x.SiteId,
                CmSite = new {
                    x.FmsMaterialPurchaseOrder.Site.Name,
                },
                x.BusinessFieldId,
                CmBusinessField = new {
                    x.FmsMaterialPurchaseOrder.CmBusinessField.Name,
                },
                x.FmsMaterialPurchaseOrder.Title,
                OrderDate = x.FmsMaterialPurchaseOrder.OrderDate,
                x.FmsMaterialPurchaseOrder.OrderUserId,
                OrderUserName = x.FmsMaterialPurchaseOrder.CmUser.Name,
                x.FmsMaterialPurchaseOrder.Reason,
                x.MaterialId,
                x.MaterialCount,
                FmsMaterials = x.FmsMaterialPurchaseOrder.FmsMaterialPurchaseOrderMaterial.Select(f => new {
                    f.SiteId,
                    f.PurchaseOrderId,
                    f.MaterialId,
                    UnitCost = f.FmsMaterial.FinalPrice,
                    MaterialName = f.FmsMaterial.Name,
                    MaterialStandard = f.FmsMaterial.Standard,
                    MaterialUnit = f.FmsMaterial.Unit,
                    f.FmsMaterial.FirstClassId,
                    FirstClassName = f.FmsMaterial.FmsMaterialCodeClass.Name,
                    f.FmsMaterial.SecondClassId,
                    SecondClassName = f.FmsMaterial.FmsMaterialCodeClass1.Name,
                    f.FmsMaterial.ThirdClassId,
                    ThirdClassName = f.FmsMaterial.FmsMaterialCodeClass2.Name,
                    f.MaterialCount,
                    StoredCount = Util.ToInt(_context.FmsMaterialStored.Where(fs => fs.SiteId == f.SiteId && fs.PurchaseOrderId == f.PurchaseOrderId && fs.MaterialId == f.MaterialId).Sum(fs => fs.StoredCount)),      //입고수량
                }).ToList(),
            });

            return Ok(item.First());
        }

        /// <summary>
        /// 입고
        /// </summary>
        /// <returns></returns>
        [HttpPost("{siteId}/{orderId}/{materialId}/{authBusiness}")]
        public IActionResult Stored(int siteId, int orderId, int materialId, bool authBusiness) {
            if (ModelState.IsValid) {
                _service.Stored(siteId, orderId, materialId, User.Identity.Name, authBusiness);
            } else {
                return BadRequest(ModelState);
            }

            return Ok();
        }

        // 셀렉트 공통
        private dynamic _ListSelect(IQueryable<FmsMaterialPurchaseOrderMaterial> query) {
            var list = query.Select(x => new {
                x.PurchaseOrderId,
                x.SiteId,
                SiteName = x.FmsMaterialPurchaseOrder.Site.Name,
                // x.BusinessFieldId,
                // BusinessFieldName = x.FmsMaterialPurchaseOrder.CmBusinessField.Name,
                // 2020.07.17 리스트에서만 재고의 업무분야 보여달라고 요청
                BusinessFieldId = x.FmsMaterial.BusinessFieldId,
                BusinessFieldName = x.FmsMaterial.CmBusinessField.Name,
                OrderDate = (x.FmsMaterialPurchaseOrder.OrderDate != null) ? x.FmsMaterialPurchaseOrder.OrderDate.ToString("yyyy-MM-dd") : "",
                ProgressName = x.FmsMaterialPurchaseOrder.FmsMaterialPurchaseRequest.Progress.Name,
                Title = x.FmsMaterialPurchaseOrder.Title,
                FirstClassName = x.FmsMaterial.FmsMaterialCodeClass.Name,
                SecondClassName = x.FmsMaterial.FmsMaterialCodeClass1.Name,
                ThirdClassName = x.FmsMaterial.FmsMaterialCodeClass2.Name,
                MaterialName = x.FmsMaterial.Name,
                MaterialStandard = x.FmsMaterial.Standard,
                MaterialUnit = x.FmsMaterial.Unit,
                MaterialCount = x.MaterialCount - (x.FmsMaterialPurchaseOrder.FmsMaterialStored.Where(f => f.MaterialId == x.MaterialId).Count() == 0 ? 0 : x.FmsMaterialPurchaseOrder.FmsMaterialStored.Where(f => f.MaterialId == x.MaterialId).Sum(f => f.StoredCount)),
                x.MaterialId,
            });
            return list;
        }

        // 검색 & 정렬 공통
        private IQueryable<FmsMaterialPurchaseOrderMaterial> _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));
            }

            // 업무분야 필드가 있는경우만 추가
            if (req.businessFieldId != null) {
                query = query.Where(x => x.SiteId == req.siteId);
                query = query.Where(x => x.FmsMaterialPurchaseOrder.BusinessFieldId == req.businessFieldId || x.FmsMaterialPurchaseOrder.CmBusinessField.Name == "공통");
            }

            //미입고
            query = query.Where(x => (x.FmsMaterialPurchaseOrder.FmsMaterialStored.Where(f => f.MaterialId == x.MaterialId).Count() == 0 ? 0 : x.FmsMaterialPurchaseOrder.FmsMaterialStored.Where(f => f.MaterialId == x.MaterialId).Sum(f => f.StoredCount)) < x.MaterialCount);

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

            // 추가 정렬
            if (req.sort.field == "OrderDate") { // 기본 커스텀 정렬 예제 (최근신청일순)
                sortQuery = sortQuery.ThenByDescending(x => x.FmsMaterialPurchaseOrder.OrderDate);
            } else {
                sortQuery = sortQuery.ThenSort(req.sort);
            }

            return sortQuery;
        }
    }
}