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.Entity.Topic;
using GxPress.Repository.Interface;
using GxPress.Request.App.TopicComment;
using GxPress.Result.App.TopicComment;
using Microsoft.Extensions.Options;
using Datory;
using SqlKata;

namespace GxPress.Repository.Implement
{
    public class TopicCommentRepository : ITopicCommentRepository
    {
        private readonly Repository<TopicComment> _repository;
        private readonly Repository<TopicAnalyze> _topicAnalyzeRepository;
        private readonly Repository<Entity.Topic.Topic> _topicRepository;
        private readonly Repository<User> _userRepository;
        private readonly IMapper _mapper;

        public TopicCommentRepository(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<TopicComment>(database);
            _topicRepository = new Repository<Entity.Topic.Topic>(database);
            _userRepository = new Repository<User>(database);
            _topicAnalyzeRepository = new Repository<TopicAnalyze>(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> TopicCommentInAsync(TopicCommentInRequest request)
        {
            //查询文章是否存在
            var article = _topicRepository.ExistsAsync(Q.Where(nameof(Entity.Topic.Topic.Id), request.TopicId));
            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 topicComment = new TopicComment
            {
                TopicId = request.TopicId,
                Content = request.Content,
                UserId = request.UserId,
                Pid = request.Pid
            };
            //是否被回复
            if (request.Pid > 0)
            {
                //查询他的上级pid=0
                var commentEntity = await _repository.GetAsync(request.Pid);
                if (commentEntity.Pid > 0)
                {
                    topicComment.IsUnderstand = true;
                }
            }

            return await _repository.InsertAsync(topicComment);
        }
        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PagedList<TopicCommentPageResult>> GetPagedList(TopicCommentSearchPageRequest request)
        {
            var pagedList = new PagedList<TopicCommentPageResult>
            {
                Total = await GetCountAsync(request.TopicId)
            };
            request.Total=pagedList.Total;
            var list = await GetPageListAsync(request);
            pagedList.Items = list;
            return pagedList;
        }
        /// <summary>
        /// 总页数
        /// </summary>
        /// <param name="topicId"></param>
        /// <returns></returns>
        public async Task<int> GetCountAsync(int topicId)
        {
            return await _repository.CountAsync(Q.Where(nameof(TopicComment.TopicId), topicId)
                .Where(nameof(Comment.Pid), 0));
        }
        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<IEnumerable<TopicCommentPageResult>> GetPageListAsync(TopicCommentSearchPageRequest request)
        {
            List<TopicCommentPageResult> commentPageResults = new List<TopicCommentPageResult>();
            var query = new SqlKata.Query();
            query.Where(nameof(TopicComment.TopicId), request.TopicId).Where(nameof(TopicComment.Pid), 0);
            if (string.IsNullOrEmpty(request.Sort))
                query.OrderByDesc(nameof(TopicComment.CreatedDate));
            if (!string.IsNullOrEmpty(request.Sort) && request.Sort == "asc")
                query.OrderBy(nameof(TopicComment.CreatedDate));
            if (!string.IsNullOrEmpty(request.Sort) && request.Sort == "desc")
                query.OrderByDesc(nameof(TopicComment.CreatedDate));
            var commentList = await _repository.GetAllAsync(query.ForPage(request.Page, request.PerPage));
            var i = 1;
            foreach (var item in commentList)
            {
                //获取当前用户信息
                var user = _userRepository.GetAsync(item.UserId).Result;
                TopicCommentPageResult commentPageResult = new TopicCommentPageResult
                {
                    TopicId = item.TopicId,
                    AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl),
                    Name = user.Name,
                    Content = item.Content,
                    CreatedTime = item.CreatedDate,
                    LaudCount = item.Laud,
                    UserId = item.UserId,
                    //是否点赞
                    IsLaud = await IsLaudCommentAsync(item.Id, item.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<TopicCommentReplyResult> commentReplyResults = new List<TopicCommentReplyResult>();
                commentPageResult.TopicCommentReplyResults = await GetTopicCommentReplyResultByPid(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 _topicAnalyzeRepository.CountAsync(Q.Where(nameof(TopicAnalyze.TopicCommentId), commentId)
                       .Where(nameof(TopicAnalyze.UserId), userId).Where(nameof(TopicAnalyze.AnalyzeType), 2)) > 0;
        }

        /// <summary>
        /// 递归查询父级下面的所有回复
        /// </summary>
        public async Task<List<TopicCommentReplyResult>> GetTopicCommentReplyResultByPid(int pid,
            List<TopicCommentReplyResult> topicCommentReplyResults)
        {
            var result = _repository.GetAllAsync(Q.Where(nameof(TopicComment.Pid), pid)).Result.ToList();
            if (result.Count == 0)
                return topicCommentReplyResults;
            foreach (var item in result)
            {
                TopicCommentReplyResult topicCommentReplyResult = new TopicCommentReplyResult
                {
                    Id = item.Id,
                    Content = item.Content,
                    CreatedTime = item.CreatedDate
                };
                var user = _userRepository.GetAsync(item.UserId).Result;
                topicCommentReplyResult.Name = user.Name;
                if (item.IsUnderstand)
                {
                    var comment = _repository.GetAsync(Q.Where(nameof(Comment.Id), item.Pid)).Result;
                    user = _userRepository.GetAsync(comment.UserId).Result;
                    topicCommentReplyResult.ReplyName = user.Name;
                    topicCommentReplyResult.ReplyUserId=user.Id;
                }

                topicCommentReplyResult.IsUnderstand = item.IsUnderstand;
                topicCommentReplyResult.UserId = item.UserId;
                topicCommentReplyResults.Add(topicCommentReplyResult);
                topicCommentReplyResults = await GetTopicCommentReplyResultByPid(item.Id, topicCommentReplyResults);

            }

            return topicCommentReplyResults;
        }


        /// <summary>
        /// 删除评论
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> DeleteTopicCommentAsync(TopicCommentDeleteRequest request)
        {
            //查询评论数据
            var topicCommentEntity = _repository.GetAsync(Q.Where(nameof(TopicComment.TopicId), request.TopicId)
                .Where(nameof(TopicComment.Id), request.CommentId)).Result;
            if (topicCommentEntity.Id == 0)
                throw new BusinessException("该评论不存在!");
            //递归删除
            var commentList = new List<TopicComment> { topicCommentEntity };
            commentList = await GetTopicCommentByParentId(topicCommentEntity.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<TopicComment>> GetTopicCommentByParentId(int id, List<TopicComment> lists)
        {
            var topicComment = await _repository.GetAsync(Q.Where(nameof(TopicComment.Pid), id));
            if (topicComment == null)
                return lists;
            lists.Add(topicComment);
            await GetTopicCommentByParentId(topicComment.Id, lists);
            return lists;
        }
        /// <summary>
        /// 获取评论数量
        /// </summary>
        /// <param name="topicId"></param>
        /// <returns></returns>
        public async Task<int> GetTopicCommentCountAsync(int topicId)
        {
            return await _repository.CountAsync(Q.Where(nameof(TopicComment.TopicId), topicId));
        }

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