using IceCreamBusinessLogic.OfficePackage.HelperModels;
using IceCreamBusinessLogic.OfficePackage;
using IceCreamShopContracts.BusinessLogicsContracts;
using IceCreamShopContracts.SearchModels;
using IceCreamShopContracts.StoragesContracts;
using IceCreamShopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IceCreamShopContracts.BindingModels;

namespace IceCreamBusinessLogic.BusinessLogics
{
    public class ReportLogic : IReportLogic
    {
        private readonly IComponentStorage _componentStorage;

        private readonly IIceCreamStorage _iceCreamStorage;

        private readonly IOrderStorage _orderStorage;

        private readonly IShopStorage _shopStorage;

        private readonly AbstractSaveToExcel _saveToExcel;

        private readonly AbstractSaveToWord _saveToWord;

        private readonly AbstractSaveToPdf _saveToPdf;

        public ReportLogic(IIceCreamStorage iceCreamStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, 
            AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf, IShopStorage shopStorage)
        {
            _iceCreamStorage = iceCreamStorage;
            _componentStorage = componentStorage;
            _orderStorage = orderStorage;

            _saveToExcel = saveToExcel;
            _saveToWord = saveToWord;
            _saveToPdf = saveToPdf;
            this._shopStorage = shopStorage;
        }

        /// <summary>
        /// Получение списка компонент с указанием, в каких изделиях используются
        /// </summary>
        /// <returns></returns>
        public List<ReportIceCreamComponentViewModel> GetIceCreamComponent()
        {
            var components = _componentStorage.GetFullList();

            var iceCreams = _iceCreamStorage.GetFullList();

            var list = new List<ReportIceCreamComponentViewModel>();

            foreach (var icecream in iceCreams)
            {
                var record = new ReportIceCreamComponentViewModel
                {
                    IceCreamName = icecream.IceCreamName,
                    Components = new List<(string, int)>(),
                    TotalCount = 0
                };
                foreach (var component in components)
                {
                    if (icecream.IceCreamComponents.ContainsKey(component.Id))
                    {
                        record.Components.Add(new(component.ComponentName, icecream.IceCreamComponents[component.Id].Item2));
                        record.TotalCount += icecream.IceCreamComponents[component.Id].Item2;
                    }
                }

                list.Add(record);
            }

            return list;
        }

        /// <summary>
        /// Получение списка заказов за определенный период
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public List<ReportOrdersViewModel> GetOrders(ReportBindingModel model)
        {
            return _orderStorage.GetFilteredList(new OrderSearchModel { DateFrom = model.DateFrom, DateTo = model.DateTo })
                    .Select(x => new ReportOrdersViewModel
                    {
                        Id = x.Id,
                        DateCreate = x.DateCreate,
                        IceCreamName = x.IceCreamName,
                        OrderStatus = Convert.ToString(x.Status) ?? String.Empty,
                        Sum = x.Sum
                    })
                    .ToList();
        }

        public void SaveShopsToWordFile(ReportBindingModel model)
        {
            _saveToWord.CreateTableDoc(new WordInfo
            {
                FileName = model.FileName,
                Title = "Список магазинов",
                Shops = _shopStorage.GetFullList()
            });
        }

        public void SaveShopWorkloadToExcelFile(ReportBindingModel model)
        {
            _saveToExcel.CreateShopReport(new ExcelInfo
            {
                FileName = model.FileName,
                Title = "Загруженность магазинов",
                ShopIceCreams = GetShopIceCreams()
            });
        }

        public List<ReportShopWorkloadViewModel> GetShopIceCreams()
        {
            var shops = _shopStorage.GetFullList();
            var list = new List<ReportShopWorkloadViewModel>();
            foreach (var shop in shops)
            {
                var record = new ReportShopWorkloadViewModel
                {
                    ShopName = shop.Name,
                    IceCreams = new List<Tuple<string, int>>(),
                    Count = 0
                };
                foreach (var iceCreamCount in shop.ShopIceCreams.Values)
                {
                    record.IceCreams.Add(new Tuple<string, int>(iceCreamCount.Item1.IceCreamName, iceCreamCount.Item2));
                    record.Count += iceCreamCount.Item2;
                }
                list.Add(record);
            }
            return list;
        }

        public List<ReportDateOrdersViewModel> GetDateOrders()
        {
            return _orderStorage.GetFullList().GroupBy(x => x.DateCreate.Date).Select(x => new ReportDateOrdersViewModel
            {
                DateCreate = x.Key,
                CountOrders = x.Count(),
                SumOrders = x.Sum(y => y.Sum)
            }).ToList();
        }
        public void SaveDateOrdersToPdfFile(ReportBindingModel model)
        {
            _saveToPdf.CreateReportDateDoc(new PdfInfo
            {
                FileName = model.FileName,
                Title = "Заказы по датам",
                DateOrders = GetDateOrders()
            });
        }

        /// <summary>
        /// Сохранение компонент в файл-Word
        /// </summary>
        /// <param name="model"></param>
        public void SaveIceCreamsToWordFile(ReportBindingModel model)
        {
            _saveToWord.CreateDoc(new WordInfo
            {
                FileName = model.FileName,
                Title = "Список изделий",
                IceCreams = _iceCreamStorage.GetFullList()
            });
        }

        /// <summary>
        /// Сохранение компонент с указаеним продуктов в файл-Excel
        /// </summary>
        /// <param name="model"></param>
        public void SaveIceCreamComponentToExcelFile(ReportBindingModel model)
        {
            _saveToExcel.CreateReport(new ExcelInfo
            {
                FileName = model.FileName,
                Title = "Список изделий",
                IceCreamComponents = GetIceCreamComponent()
            });
        }

        /// <summary>
        /// Сохранение заказов в файл-Pdf
        /// </summary>
        /// <param name="model"></param>
        public void SaveOrdersToPdfFile(ReportBindingModel model)
        {
            _saveToPdf.CreateDoc(new PdfInfo
            {
                FileName = model.FileName,
                Title = "Список заказов",
                DateFrom = model.DateFrom!.Value,
                DateTo = model.DateTo!.Value,
                Orders = GetOrders(model)
            });
        }
    }
}
