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 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 FMSApp.Controllers {
    [Authorize]
    [ApiController]
    [ApiVersion("1")]
    [Route("api/app/[controller]")]
    public class MaterialDailyStockController : Controller {
        private readonly ILogger<MaterialDailyStockController> _logger;
        private readonly FMSContext _context;
        private readonly MaterialService _service;

        public MaterialDailyStockController(
            ILogger<MaterialDailyStockController> logger,
            FMSContext context,
            MaterialService 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, bool businessAuth) {
            var query = _FilterAndSort(req);

            query = BusinessFieldHelper.Apply<MaterialStockHistory>(_context, User, businessAuth, query, "Material");

            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}")]
        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.Date,
                x.Material.Name,
                x.Material.Standard,
                x.Material.Unit,
                x.StockCount,
                x.StockAmount,
                x.StoredCount,
                x.ReleaseCount,
                x.ReleaseLossCount,
                x.ReleaseReturnCount,
                x.LastStockCount,
                x.LastStockDate,
            });

            return list;
        }

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

            query = query.Filter(req.conditions);

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

            query = query.Sort(req.sort);

            return query;
        }

    }

}

