using Dapper;
using Lada.Framework.Data.Domains.Cms;
using Lada.Framework.Data.Repositories;
using Lada.Framework.Infrastructures.Helpers;
using ladaexpress.vn.Infrastructures.DTO;
using ladaexpress.vn.Infrastructures.DTO.Models.Post.Detail;
using ladaexpress.vn.Infrastructures.DTO.Models.Product.Index;
using ladaexpress.vn.Infrastructures.DTO.Models.Product.Index.Childs;
using ladaexpress.vn.Infrastructures.DTO.Models.Products.Detail;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using System.Data;
using System.Text.RegularExpressions;

namespace ladaexpress.vn.Infrastructures.Services
{
    public interface IProductService
    {
        /// <summary>
        /// Tìm kiếm bài viết
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        Task<ProductIndexModel> PrepareProductIndex();

        Task<ProductDetailModel> PrepareProductDetail(int id);

        /// <summary>
        /// Tạo / cập nhật bài viết
        /// </summary>
        /// <param name="model"></param>
        /// <param name="updateBy"></param>
        /// <param name="updateByUserName"></param>
        /// <returns></returns>
        //Task<ProductResult> CreateOrUpdate(ProductModel model);

        /// <summary>
        /// Lấy thông tin bài viết qua Id
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        //Task<ProductModel> GetById(int productId);

        /// <summary>
        /// Xóa bài viết
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        //Task<BaseResult> Delete(int productId);



    }


    public class ProductService : IProductService
    {
        private readonly IRepository<Product> _productRepository;
        private readonly IRepository<Category> _categoryRepository;
        private readonly IRepository<UrlRecord> _urlRecordRepository;
        private readonly IDbConnection _dbConnection;


        public ProductService(IRepository<Product> productRepository, IRepository<UrlRecord> urlRecordRepository,
            IRepository<Category> categoryRepository, IDbConnection dbConnection)
        {
            _productRepository = productRepository;
            _urlRecordRepository = urlRecordRepository;
            _categoryRepository = categoryRepository;
            _dbConnection = dbConnection;
        }

        public async Task<ProductIndexModel> PrepareProductIndex()
        {
            var model = new ProductIndexModel();
            var currentTime = DateTimeHelper.CurrentTime();
            var newTime = currentTime.AddDays(-3);//Những bài viết có ngày xuất bản 3 ngày trở về đây được coi là bài viết mới
            var query = _productRepository.Query();

            model.FeaturedProducts = await PrepareFeaturedProducts();
            model.NewProducts = await PrepareNewProducts();

            return model;

        }

        #region ProductIndex Sections

        public async Task<List<ProductItem>> PrepareNewProducts()
        {
            var products = new List<ProductItem>();
            try
            {
                products = (await _dbConnection.QueryAsync<ProductItem>("ProductIndex_GetNewProducts", commandType: CommandType.StoredProcedure)).ToList();
            }
            catch (Exception)
            {
            }
            return products;
        }



        public async Task<List<ProductItem>> PrepareFeaturedProducts()
        {
            var currentTime = DateTimeHelper.CurrentTime();
            var query = _productRepository.Query();

            return await query.Where(p => p.IsFeatured)
                                            .OrderByDescending(p => p.UpdatedTime).Take(5)
                                            .Include(p => p.UrlRecord).Select(p => p.ToItem()).ToListAsync();
        }


        #endregion


        public async Task<ProductDetailModel> PrepareProductDetail(int id)
        {
            var model = new ProductDetailModel();
            var currentTime = DateTimeHelper.CurrentTime();
            var product = await _productRepository.Query().
                Include(p => p.UrlRecord)
                .Include(p => p.ProductTags!).ThenInclude(pt => pt.Tag!).ThenInclude(t => t.UrlRecord!)
                .FirstOrDefaultAsync(p => p.Id == id);
            if (product != null && product.Id > 0)
            {
                model = product.ToDetailModel();
                if (product.ProductTags != null && product.ProductTags.Any())
                {
                    foreach (var productTag in product.ProductTags)
                    {
                        if (productTag.Tag != null && productTag.Tag.Id > 0)
                        {
                            var tagSlug = "";
                            if (productTag.Tag.UrlRecord != null)
                            {
                                tagSlug = productTag.Tag.UrlRecord.Slug;
                            }
                            model.Tags.Add(new ProductTagItem() { Id = productTag.Tag.Id, Name = productTag.Tag.Name, Slug = tagSlug });
                        }
                    }
                }


                if (!string.IsNullOrEmpty(model.Description))
                {
                    var plaintext = Regex.Replace(model.Description, "<(.|\n)*?>", "").Trim();
                    char[] delimiters = new char[] { ' ', '\r', '\n' };
                    var wordCount = plaintext.Split(delimiters, StringSplitOptions.RemoveEmptyEntries).Length;
                    int readingSpeed = 200;
                    int estimatedReadingTime = (wordCount * 60) / readingSpeed;
                    // Chuyển thời gian từ giây thành phút và giây
                    int minutes = estimatedReadingTime / 60;
                }
                //if (model.Tags.Any())
                //{
                //    var tagIds = model.Tags.Select(t => t.Id).ToList();
                //    var tagUrlRecords = await _urlRecordRepository.Query().Where(u => u.TagId.HasValue && tagIds.Contains(u.TagId.Value)).ToListAsync();
                //    if (tagUrlRecords.Any())
                //    {
                //        foreach (var item in model.Tags)
                //        {
                //            var urlRecord = tagUrlRecords.FirstOrDefault(u => u.TagId == item.Id);
                //            if (urlRecord != null && urlRecord.Id > 0)
                //            {
                //                item.Slug = urlRecord.Slug;
                //            }
                //        }
                //    }
                //}

            }
            return model;
        }



    }
}
