using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Datory;
using GxPress.Common.Tools;
using GxPress.Entity;
using GxPress.Repository.Interface;
using GxPress.Repository.Interface.Collection;
using GxPress.Result.Article;
using GxPress.Service.Interface.Article;
using GxPress.Service.Interface.Analyze;
using GxPress.Request.Analyze;
using GxPress.Service.Interface.Visit;
using GxPress.Request.Article;
using GxPress.Service.Interface.ArticleLabel;
namespace GxPress.Service.Implement.Article
{
    /// <summary>
    /// 文章
    /// </summary>
    public class ArticleService : IArticleService
    {
        private readonly IUserRepository _userRepository;
        private readonly ICommentRepository _commentRepository;
        private readonly IArticleRepository _articleRepository;
        private readonly IArticleGroupRepository _articleGroupRepository;
        private readonly IMiddleRepository _middleRepository;
        private readonly ICollectionRepository _collectionRepository;
        private readonly IAnalyzeService _analyzeService;
        private readonly IVisitService _visitService;

        private readonly IArticleLabelService _articleLabelService;
        public ArticleService(IUserRepository userRepository,
            ICommentRepository commentRepository, IArticleRepository articleRepository, IArticleGroupRepository articleGroupRepository, ICollectionRepository collectionRepository, IMiddleRepository middleRepository, IAnalyzeService analyzeService, IVisitService visitService, IArticleLabelService articleLabelService)
        {
            _userRepository = userRepository;
            _commentRepository = commentRepository;
            _articleRepository = articleRepository;
            _articleGroupRepository = articleGroupRepository;
            _middleRepository = middleRepository;
            _collectionRepository = collectionRepository;
            _analyzeService = analyzeService;
            _visitService = visitService;
            _articleLabelService = articleLabelService;
        }



        /// <summary>
        /// 获取文章详情
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<ArticleResult> GetAsync(int id, int userId)
        {
            var article = await _articleRepository.GetAsync(id);
            if (article == null)
                return new ArticleResult();
            //增加阅读量
            //访问
            if (userId > 0)
                await _visitService.AddVisit(userId, 1, id);
            //获取文章类型名称
            var articleGroup = await _articleGroupRepository.GetAsync(article.GroupId);
            var groupName = articleGroup == null ? "" : articleGroup.Name;
            //获取文章的点赞数据
            var articleResult = new ArticleResult
            {
                Id = article.Id,
                Title = article.Title,
                GroupId = article.GroupId,
                ImageUrls = StringUtils.StringCollectionToStringList(article.ImageUrls),
                Summary = article.Summary,
                Author = article.Author,
                Source = article.Source,
                ArticleBlocks = StringUtils.JsonDeserialize<IEnumerable<Block>>(article.Blocks),
                IsChecked = article.IsChecked,
                AddDate = article.AddDate,
                Sort = article.Sort,
                GroupName = groupName,
                ReadCount = await _visitService.GetCountAsync(1, article.Id),
                IsTop = article.IsTop,
                CreatedDate = article.CreatedDate
            };
            //标签
            articleResult.ArticleInnerLabelsResult = await _articleLabelService.GetArticleLabelsAsync(id);
            //文章图片
            foreach (var block in articleResult.ArticleBlocks)
            {
                if (block.Type == "image")
                    block.Data.File.Url = StringUtils.AddDomain(block.Data.File.Url);
            }
            var imageUrls = articleResult.ImageUrls.ToList();
            for (int i = 0; i < imageUrls.Count(); i++)
                imageUrls[i] = StringUtils.AddDomain(imageUrls[i]);
            articleResult.ImageUrls = imageUrls;
            var analyzeRequest = new Request.App.Analyze.AnalyzeRequest();
            analyzeRequest.TypeValue = 0;
            analyzeRequest.AnalyzeType = 1;
            analyzeRequest.SourceId = id;
            analyzeRequest.UserId = userId;
            //点赞数量
            articleResult.PraiseCount = await _analyzeService.CountAsync(analyzeRequest);
            //获取话题的评论数量
            var commentCount =
                await _commentRepository.CountAsync(Q.Where(nameof(Entity.Comment.ArticleId), id).Where(nameof(Entity.Comment.TypeValue), 0).Where(nameof(Entity.Comment.Pid), 0));
            articleResult.CommentCount = commentCount;
            //获取话题的转发数量
            analyzeRequest.AnalyzeType = 4;
            var retransmissionCount = await _analyzeService.CountAsync(analyzeRequest);
            articleResult.RetransmissionCount = retransmissionCount;
            articleResult.IsRetransmission = await _analyzeService.ExistsAsync(analyzeRequest);
            //获取话题的收藏数量
            analyzeRequest.AnalyzeType = 3;
            var collectCount = await _analyzeService.CountAsync(analyzeRequest);
            articleResult.CollectCount = collectCount;
            //是否收藏
            articleResult.IsCollect = await _analyzeService.ExistsAsync(analyzeRequest);
            //获取话题的点赞数量
            analyzeRequest.AnalyzeType = 1;
            var praiseCount = await _analyzeService.CountAsync(analyzeRequest);
            articleResult.PraiseCount = praiseCount;
            //是否点赞
            articleResult.IsPraise = await _analyzeService.ExistsAsync(analyzeRequest);
            var request = new PraisePageSearchRequest { SourceId = id, TypeValue = 0, Page = 1, PerPage = 3 };
            articleResult.ArticlePraisePagedList = await _analyzeService.GetPraisePageAsync(request);
            return articleResult;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ArticleResult> AddAsync(ArticleAddRequest request)
        {
            //文章图片
            var resultImageUrls = request.ImageUrls.ToList();
            for (int i = 0; i < resultImageUrls.Count; i++)
                resultImageUrls[i] = StringUtils.RemoveDomain(resultImageUrls[i]);
            request.ImageUrls = resultImageUrls;
            //文章内容图片
            foreach (var block in request.Blocks)
            {
                if (block.Type == "image")
                {
                    block.Data.File.Url = StringUtils.RemoveDomain(block.Data.File.Url);
                }
            }
            var sort = request.Sort == 0 ? await _articleRepository.MaxAsync(nameof(Entity.Article.Sort)) : request.Sort;
            var article = new Entity.Article
            {
                Title = request.Title,
                GroupId = request.GroupId,
                ImageUrls = StringUtils.ObjectCollectionToString(request.ImageUrls),
                Summary = request.Summary,
                Author = request.Author,
                Source = request.Source,
                Blocks = StringUtils.JsonSerialize(request.Blocks),
                IsChecked = request.IsChecked,
                AddDate = request.AddDate,
                Sort = sort ?? 1,
                IsTop = request.IsTop
            };
            article.Id = await _articleRepository.InsertAsync(article);
            //添加文章标签
            await _articleLabelService.AddArticleInnerLabel(article.Id, request.ArticleLabelIds);
            var articleResult = new ArticleResult
            {
                Id = article.Id,
                Title = article.Title,
                GroupId = article.GroupId,
                ImageUrls = StringUtils.StringCollectionToStringList(article.ImageUrls),
                Summary = article.Summary,
                Author = article.Author,
                Source = article.Source,
                ArticleBlocks = StringUtils.JsonDeserialize<IEnumerable<Block>>(article.Blocks),
                IsChecked = article.IsChecked,
                AddDate = article.AddDate,
                Sort = article.Sort,
                IsTop = article.IsTop
            };
            //文章图片
            resultImageUrls = articleResult.ImageUrls.ToList();
            for (int i = 0; i < resultImageUrls.Count; i++)
            {
                resultImageUrls[i] = StringUtils.AddDomain(resultImageUrls[i]);
            }
            articleResult.ImageUrls = resultImageUrls;
            //文章内容图片
            foreach (var block in articleResult.ArticleBlocks)
            {
                if (block.Type == "image")
                {
                    block.Data.File.Url = StringUtils.AddDomain(block.Data.File.Url);
                }
            }
            return articleResult;
        }

        public async Task<ArticleResult> EditAsync(ArticleEditRequest request)
        {
            //解析文章类容 图片地址
            foreach (var block in request.Blocks)
            {
                if (block.Type == "image")
                {
                    block.Data.File.Url = StringUtils.RemoveDomain(block.Data.File.Url);
                }
            }
            //
            var imageUrls = request.ImageUrls.ToList();
            for (int i = 0; i < imageUrls.Count; i++)
            {
                imageUrls[i] = StringUtils.RemoveDomain(imageUrls[i]);
            }
            request.ImageUrls = imageUrls;

            var article = new Entity.Article
            {
                Id = request.Id,
                Title = request.Title,
                GroupId = request.GroupId,
                ImageUrls = StringUtils.ObjectCollectionToString(request.ImageUrls),
                Summary = request.Summary,
                Author = request.Author,
                Source = request.Source,
                Blocks = StringUtils.JsonSerialize(request.Blocks),
                IsChecked = request.IsChecked,
                AddDate = request.AddDate,
                Sort = request.Sort,
                IsTop = request.IsTop
            };
            await _articleRepository.UpdateAsync(article);
            //添加文章标签
            await _articleLabelService.AddArticleInnerLabel(article.Id, request.ArticleLabelIds);
            var articleResult = new ArticleResult
            {
                Id = article.Id,
                Title = article.Title,
                GroupId = article.GroupId,
                ImageUrls = StringUtils.StringCollectionToStringList(article.ImageUrls),
                Summary = article.Summary,
                Author = article.Author,
                Source = article.Source,
                ArticleBlocks = StringUtils.JsonDeserialize<IEnumerable<Block>>(article.Blocks),
                IsChecked = article.IsChecked,
                AddDate = article.AddDate,
                Sort = article.Sort,
                IsTop = request.IsTop
            };
            //文章图片
            var resultImageUrls = articleResult.ImageUrls.ToList();
            for (int i = 0; i < resultImageUrls.Count; i++)
            {
                resultImageUrls[i] = StringUtils.AddDomain(resultImageUrls[i]);
            }
            articleResult.ImageUrls = resultImageUrls;
            //文章内容图片
            foreach (var block in articleResult.ArticleBlocks)
            {
                if (block.Type == "image")
                {
                    block.Data.File.Url = StringUtils.AddDomain(block.Data.File.Url);
                }
            }
            return articleResult;
        }
    }
}
