using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using GxPress.Common.AppOptions;
using GxPress.Common.Exceptions;
using GxPress.Common.Page;
using GxPress.Common.Tools;
using GxPress.Entity;
using GxPress.Repository.Interface;
using GxPress.Request.Comment;
using GxPress.Result.Comment;
using Microsoft.Extensions.Options;
using Datory;
using SqlKata;

namespace GxPress.Repository.Implement
{
    public class CommentRepository : ICommentRepository
    {
        private readonly Repository<Comment> _repository;
        private readonly Repository<Entity.Analyze.Analyze> _analyzeRepository;
        private readonly Repository<Article> _articleRepository;
        private readonly Repository<User> _userRepository;
        private readonly IMapper _mapper;

        public CommentRepository(IOptionsMonitor<DatabaseOptions> dbOptionsAccessor, IMapper mapper)
        {
            var databaseType = StringUtils.ToEnum<DatabaseType>(dbOptionsAccessor.CurrentValue.DatabaseType, DatabaseType.MySql);
            var database = new Database(databaseType, dbOptionsAccessor.CurrentValue.ConnectionString);
            _repository = new Repository<Comment>(database);
            _articleRepository = new Repository<Article>(database);
            _userRepository = new Repository<User>(database);
            _analyzeRepository = new Repository<Entity.Analyze.Analyze>(database);
            _mapper = mapper;
        }

        public IDatabase Database => _repository.Database;
        public string TableName => _repository.TableName;
        public List<TableColumn> TableColumns => _repository.TableColumns;

        /// <summary>
        /// 添加评论
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<int> CommentInAsync(CommentInRequest request)
        {
            //查询文章是否存在
            // var article = _articleRepository.ExistsAsync(Q.Where(nameof(Article.Id), request.ArticleId));
            // if (await article == false)
            //     throw new BusinessException("该文章不存在");
            //查询用户
            var user = _userRepository.ExistsAsync(Q.Where(nameof(User.Id), request.UserId));
            if (await user == false)
                throw new BusinessException("该用户不存在");
            var comment = new Comment
            {
                ArticleId = request.ArticleId,
                Content = request.Content,
                UserId = request.UserId,
                Pid = request.Pid,
                TypeValue = request.TypeValue
            };
            //是否被回复
            if (request.Pid > 0)
            {
                //查询他的上级pid=0
                var commentEntity = await _repository.GetAsync(request.Pid);
                if (commentEntity.Pid > 0)
                {
                    comment.IsUnderstand = true;
                }
            }

            return await _repository.InsertAsync(comment);
        }

        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PagedList<CommentPageResult>> GetPagedList(CommentSearchPageRequest request)
        {
            var pagedList = new PagedList<CommentPageResult>
            {
                Total = await GetCountAsync(request)
            };
            request.Total = pagedList.Total;
            var list = await GetPageListAsync(request);
            pagedList.Items = list;
            return pagedList;
        }
        /// <summary>
        /// 获取总条数
        /// </summary>
        /// <param name="articleId"></param>
        /// <returns></returns>
        public async Task<int> GetCountAsync(CommentSearchPageRequest request)
        {
            return await _repository.CountAsync(Q.Where(nameof(Comment.ArticleId), request.ArticleId)
                .Where(nameof(Comment.Pid), 0).Where(nameof(Comment.TypeValue), request.TypeValue));
        }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<IEnumerable<CommentPageResult>> GetPageListAsync(CommentSearchPageRequest request)
        {
            List<CommentPageResult> commentPageResults = new List<CommentPageResult>();
            var query = new SqlKata.Query();
            query.Where(nameof(Comment.ArticleId), request.ArticleId)
                .Where(nameof(Comment.Pid), 0).Where(nameof(Comment.TypeValue), request.TypeValue);
            if (string.IsNullOrEmpty(request.Sort))
                query.OrderByDesc(nameof(Comment.CreatedDate));
            if (!string.IsNullOrEmpty(request.Sort) && request.Sort == "asc")
                query.OrderBy(nameof(Comment.CreatedDate));
            if (!string.IsNullOrEmpty(request.Sort) && request.Sort == "desc")
                query.OrderByDesc(nameof(Comment.CreatedDate));
            var commentList = await _repository.GetAllAsync(query.ForPage(request.Page, request.PerPage));
            var i = 1;
            foreach (var item in commentList)
            {
                //获取当前用户信息
                var user = await _userRepository.GetAsync(item.UserId);
                if (user == null)
                    continue;
                CommentPageResult commentPageResult = new CommentPageResult
                {
                    ArticleId = item.ArticleId,
                    AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl),
                    Name = user.Name,
                    Content = item.Content,
                    CreatedTime = item.CreatedDate,
                    LaudCount =await LaudCommentAsync(item.Id),
                    UserId = item.UserId,
                    //是否点赞
                    IsLaud = await IsLaudCommentAsync(item.Id, request.UserId)
                };
                if (request.Sort == "asc")
                    commentPageResult.FloorCount = $"第{((request.Page - 1) * request.PerPage) + i}楼";
                else
                    commentPageResult.FloorCount = $"第{((request.Total - (request.Page - 1) * request.PerPage) - (i - 1))}楼";
                //计算点赞数量
                //计算被回复数据
                List<CommentReplyResult> commentReplyResults = new List<CommentReplyResult>();
                commentPageResult.CommentReplyResults = await GetCommentReplyResultByPid(item.Id, commentReplyResults);
                commentPageResult.Id = item.Id;
                commentPageResults.Add(commentPageResult);
                i++;
            }

            return commentPageResults;
        }

        /// <summary>
        /// 当前用户是否点赞该评论
        /// </summary>
        /// <param name="commentId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>

        public async Task<bool> IsLaudCommentAsync(int commentId, int userId)
        {
            return await _analyzeRepository.CountAsync(Q.Where(nameof(Entity.Analyze.Analyze.CommentId), commentId)
                       .Where(nameof(Entity.Analyze.Analyze.UserId), userId).Where(nameof(Entity.Analyze.Analyze.AnalyzeType), 2)) > 0;
        }

     /// <summary>
        /// 当前用户是否点赞该评论
        /// </summary>
        /// <param name="commentId"></param>
        /// <returns></returns>

        public async Task<int> LaudCommentAsync(int commentId)
        {
            return await _analyzeRepository.CountAsync(Q.Where(nameof(Entity.Analyze.Analyze.CommentId), commentId).Where(nameof(Entity.Analyze.Analyze.AnalyzeType), 2));
        }
        /// <summary>
        /// 递归查询父级下面的所有回复
        /// </summary>
        public async Task<List<CommentReplyResult>> GetCommentReplyResultByPid(int pid,
            List<CommentReplyResult> commentReplyResults)
        {
            var result = _repository.GetAllAsync(Q.Where(nameof(Comment.Pid), pid)).Result.ToList();
            if (result.Count == 0)
                return commentReplyResults;
            foreach (var item in result)
            {
                CommentReplyResult commentReplyResult = new CommentReplyResult
                {
                    Id = item.Id,
                    Content = item.Content,
                    CreatedTime = item.CreatedDate
                };
                var user = await _userRepository.GetAsync(item.UserId);
                if (user == null)
                    continue;
                commentReplyResult.Name = user.Name;
                if (item.IsUnderstand)
                {
                    var comment = await _repository.GetAsync(Q.Where(nameof(Comment.Id), item.Pid));
                    if (comment == null)
                        continue;
                    user = _userRepository.GetAsync(comment.UserId).Result;
                    commentReplyResult.ReplyName = user.Name;
                    commentReplyResult.ReplyUserId = user.Id;
                }
                commentReplyResult.IsUnderstand = item.IsUnderstand;
                commentReplyResult.UserId = item.UserId;
                commentReplyResults.Add(commentReplyResult);
                commentReplyResults = await GetCommentReplyResultByPid(item.Id, commentReplyResults);
            }
            return commentReplyResults;
        }

        /// <summary>
        /// 删除评论
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> DeleteCommentAsync(CommentDeleteRequest request)
        {
            //查询评论数据
            var commentEntity = await _repository.GetAsync(Q.Where(nameof(Comment.ArticleId), request.ArticleId)
                .Where(nameof(Comment.Id), request.CommentId));
            if (commentEntity.Id == 0)
                throw new BusinessException("该评论不存在!");
            //递归删除
            var commentList = new List<Comment> { commentEntity };
            commentList = await GetCommentByParentId(commentEntity.Id, commentList);
            //删除
            foreach (var item in commentList)
            {
                await _repository.DeleteAsync(item.Id);
            }

            return true;
        }

        /// <summary>
        /// 递归删除
        /// </summary>
        /// <param name="id"></param>
        /// <param name="lists"></param>
        /// <returns></returns>
        public async Task<List<Comment>> GetCommentByParentId(int id, List<Comment> lists)
        {
            var commentList = await _repository.GetAllAsync(Q.Where(nameof(Comment.Pid), id));
            if (!commentList.Any())
                return lists;
            foreach (var comment in commentList)
            {
                lists.Add(comment);
                await GetCommentByParentId(comment.Id, lists);
            }
            return lists;
        }


        /// <summary>
        /// 获取评论数量
        /// </summary>
        /// <param name="articleId"></param>
        /// <returns></returns>
        public async Task<int> GetCommentCountAsync(int articleId)
        {
            return await _repository.CountAsync(Q.Where(nameof(Comment.ArticleId), articleId));
        }

        public async Task<Comment> GetAsync(Query query)
        {
            return await _repository.GetAsync(query);
        }

        public async Task<bool> UpdateAsync(Comment comment)
        {
            return await _repository.UpdateAsync(comment);
        }

        public async Task<int> CountAsync(Query query)
        {
            return await _repository.CountAsync(query);
        }
    }
}
