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 MaterialMonthlyStockController : Controller {
        private readonly ILogger<MaterialMonthlyStockController> _logger;
        private readonly FMSContext _context;
        private readonly MaterialStockService _service;

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

        /// <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="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>
        /// <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.MaterialId,
                x.SiteId,
                CmSite = new {
                    x.CmSite.Name,
                },
                x.BusinessFieldId,
                CmBusinessField = new {
                    x.CmBusinessField.Name,
                },
                x.MaterialTypeId,
                FmsMaterialCodeType = new {
                    x.FmsMaterialCodeType.Name,
                },
                x.FirstClassId,
                FmsMaterialCodeClass = new {
                    x.FmsMaterialCodeClass.MaterialClassId,
                    x.FmsMaterialCodeClass.Name,
                },
                x.SecondClassId,
                FmsMaterialCodeClass1 = new {
                    x.FmsMaterialCodeClass1.MaterialClassId,
                    x.FmsMaterialCodeClass1.Name,
                },
                x.ThirdClassId,
                FmsMaterialCodeClass2 = new {
                    x.FmsMaterialCodeClass2.MaterialClassId,
                    x.FmsMaterialCodeClass2.Name,
                },
                x.MaterialCode,
                x.Name,
                x.Standard,
                x.Unit,
                x.Rfid,
                x.Manufacturer,
                x.DurableYears,
                x.FinalPrice,
                x.ReasonableStockCount,
                x.IsDiscontinued,
                x.IsUse,
                x.Note,
            });

            return Ok(item.First());
        }

        // 셀렉트 공통
        private dynamic _ListSelect(IQueryable<MaterialStockHistory> query) {
            var list = query.Select(x => new {
                x.Material.MaterialId,
                SiteName = x.Material.CmSite.Name,
                x.Material.BusinessFieldId,
                BusinessFieldName = x.Material.CmBusinessField.Name,
                x.Material.FirstClassId,
                FirstClassName = x.Material.FmsMaterialCodeClass.Name,
                x.Material.SecondClassId,
                SecondClassName = x.Material.FmsMaterialCodeClass1.Name,
                x.Material.ThirdClassId,
                ThirdClassName = x.Material.FmsMaterialCodeClass2.Name,
                x.Material.Name,
                x.Material.Standard,
                x.Material.Unit,
                Date = x.Date.ToString("yyyy/MM"),
                x.Year,
                x.Month,
                x.StoredCount,
                x.ReleaseCount,
                x.ReleaseLossCount,
                x.ReleaseReturnCount,
                x.StockCount,
                x.StockAmount,
                x.Warehouse.WarehouseId,
                WarehouseName = x.Warehouse.Name,
                x.LastStockCount,
                x.LastStockDate,
            });

            return list;
        }

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

            query = query.Filter(req.conditions);

            if (req.siteId != null) {
                query = query.Where(x => x.Material.SiteId == Util.ToInt(req.siteId));
            }
            if (req.siteIds != null && req.siteIds.Length > 0) {
                query = query.Where(x => req.siteIds.Contains(x.Material.SiteId));
            }

            if (req.conditions != null) {
                foreach (var item in req.conditions) {
                    if (item.field == "DateSearchFrom") {
                        query = query.Where(x => x.Date >= DateTime.Parse(item.value + "-01"));
                    } else if (item.field == "DateSearchTo") {
                        query = query.Where(x => x.Date <= DateTime.Parse(item.value + "-01").AddMonths(1).AddDays(-1));
                    }
                }
            }

            // 업무분야 필드가 있는경우만 추가
            if (req.businessFieldId != null) {
                query = query.Where(x => new int[] { req.businessFieldId.Value, 1 }.Contains(x.Material.BusinessFieldId));
            }

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

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

            return sortQuery;
        }

    }
}

