using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Datory;
using GxPress.Common.Exceptions;
using GxPress.Common.Page;
using GxPress.Common.Tools;
using GxPress.Entity;
using GxPress.Repository.Interface;
using GxPress.Repository.Interface.Analyze;
using GxPress.Request.Analyze;
using GxPress.Request.App.Analyze;
using GxPress.Result.App.Analyze;
using GxPress.Service.Interface.Analyze;

namespace GxPress.Service.Implement.Analyze
{
    public class AnalyzeService : IAnalyzeService
    {
        private readonly IUserRepository _userRepository;
        private readonly IAnalyzeRepository _repository;
        private readonly ICommentRepository _commentRepository;
        private readonly IDepartmentRepository _departmentRepository;
        private readonly IMapper _mapper;
        public AnalyzeService(IUserRepository userRepository, IAnalyzeRepository analyzeRepository, ICommentRepository commentRepository, IMapper mapper, IDepartmentRepository departmentRepository)
        {
            _userRepository = userRepository;
            _repository = analyzeRepository;
            _commentRepository = commentRepository;
            _departmentRepository = departmentRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 设置 点赞 转发 收藏
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> SetAnalyzeAsync(AnalyzeRequest request)
        {
            var user = await _userRepository.GetAsync(request.UserId);
            if (user == null) throw new BusinessException("不存在该账号");
            //查询该用户是否存在记录
            var query = new SqlKata.Query();
            query
                .Where(nameof(Entity.Analyze.Analyze.AnalyzeType), request.AnalyzeType)
                .Where(nameof(Entity.Analyze.Analyze.SourceId), request.SourceId).Where(nameof(Entity.Analyze.Analyze.CommentId), request.CommentId)
                .Where(nameof(Entity.Analyze.Analyze.UserId), request.UserId).Where(nameof(Entity.Analyze.Analyze.TypeValue), request.TypeValue);
            if (request.SourceUserId > 0)
                query.Where(nameof(Entity.Analyze.Analyze.SourceUserId), request.SourceUserId);
            var analyze = await _repository.GetAsync(query);
            if (analyze != null && analyze.Id > 0 && analyze.AnalyzeType != 4)
            {
                return await _repository.DeleteAsync(analyze.Id);
            }
            //添加
            var analyzeDto = new Entity.Analyze.Analyze();
            analyzeDto.SourceId = request.SourceId;
            analyzeDto.UserId = request.UserId;
            analyzeDto.AnalyzeType = request.AnalyzeType;
            analyzeDto.TypeValue = request.TypeValue;
            analyzeDto.CommentId = request.CommentId;
            analyzeDto.SourceUserId = request.SourceUserId;
            //修改文章评论的点赞数量
            if (request.CommentId > 0)
            {
                //查询评论
                var commit = await _commentRepository.GetAsync(Q.Where(nameof(Comment.TypeValue), request.TypeValue).Where(nameof(Comment.ArticleId), request.SourceId).Where(nameof(Comment.Id), request.CommentId));
                commit.Laud = await _repository.CountAsync(Q.Where(nameof(Entity.Analyze.Analyze.SourceId), request.SourceId).Where(nameof(Entity.Analyze.Analyze.TypeValue), request.TypeValue).Where(nameof(Entity.Analyze.Analyze.CommentId), request.CommentId));
                await _commentRepository.UpdateAsync(commit);
            }
            return await _repository.InsertAsync(analyzeDto) > 0;
        }


        /// <summary>
        /// 获取点赞数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PagedList<PraisePageResult>> GetPraisePageAsync(PraisePageSearchRequest request)
        {
            var query = Q.NewQuery();
            query.Where(nameof(Entity.Analyze.Analyze.AnalyzeType), 1).Where(nameof(Entity.Analyze.Analyze.SourceId), request.SourceId).Where(nameof(Entity.Analyze.Analyze.TypeValue), request.TypeValue);
            if (request.Sort == "desc")
                query.OrderByDesc(nameof(Entity.Analyze.Analyze.CreatedDate));
            var pagedList = new PagedList<PraisePageResult>
            {
                Total = await _repository.CountAsync(query)
            };
            var list = await _repository.GetAllAsync(query.ForPage(request.Page, request.PerPage));
            var items = list.Select(user => _mapper.Map<PraisePageResult>(user)).ToList();
            for (int i = 0; i < items.Count; i++)
            {
                //获取用户
                var user = await _userRepository.GetAsync(items[i].UserId);
                if (user == null)
                {
                    items.Remove(items[i]);
                    continue;
                }
                items[i].UserName = user.Name;
                items[i].Signature = user.Signature;
                items[i].AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
                //获取部门
                var department = await _departmentRepository.GetAsync(user.DepartmentId);
                items[i].DepartmentName = department != null ? department.Name : "";
            }
            // foreach (var item in items)
            // {
            //     //获取用户
            //     var  user = await _userRepository.GetAsync(item.UserId);
            //     item.UserName = user.Name;
            //     item.Signature = user.Signature;
            //     item.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
            //     //获取部门
            //     var department = await _departmentRepository.GetAsync(user.DepartmentId);
            //     item.DepartmentName = department != null ? department.Name : "";
            // }
            pagedList.Items = items;
            return pagedList;
        }
        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> ExistsAsync(AnalyzeRequest request)
        {
            return await _repository.ExistsAsync(Q.Where(nameof(Entity.Analyze.Analyze.SourceId), request.SourceId).Where(nameof(Entity.Analyze.Analyze.TypeValue), request.TypeValue).Where(nameof(Entity.Analyze.Analyze.UserId), request.UserId).Where(nameof(Entity.Analyze.Analyze.AnalyzeType), request.AnalyzeType).Where(nameof(Entity.Analyze.Analyze.CommentId), request.CommentId));
        }
        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> ExistsSourceUserAsync(AnalyzeRequest request)
        {
            return await _repository.ExistsAsync(Q.Where(nameof(Entity.Analyze.Analyze.SourceId), request.SourceId).Where(nameof(Entity.Analyze.Analyze.TypeValue), request.TypeValue).Where(nameof(Entity.Analyze.Analyze.UserId), request.UserId).Where(nameof(Entity.Analyze.Analyze.AnalyzeType), request.AnalyzeType).Where(nameof(Entity.Analyze.Analyze.CommentId), request.CommentId).Where(nameof(Entity.Analyze.Analyze.SourceUserId), request.SourceUserId));
        }
        /// <summary>
        /// 条数
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<int> CountAsync(AnalyzeRequest request)
        {
            return await _repository.CountAsync(Q.Where(nameof(Entity.Analyze.Analyze.SourceId), request.SourceId).Where(nameof(Entity.Analyze.Analyze.TypeValue), request.TypeValue).Where(nameof(Entity.Analyze.Analyze.AnalyzeType), request.AnalyzeType).Where(nameof(Entity.Analyze.Analyze.CommentId), request.CommentId));
        }
        /// <summary>
        /// 转发数量
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<int> RetransmissionCountAsync(AnalyzeRequest request)
        {
            return await _repository.CountAsync(Q.Where(nameof(Entity.Analyze.Analyze.SourceId), request.SourceId).Where(nameof(Entity.Analyze.Analyze.TypeValue), request.TypeValue).Where(nameof(Entity.Analyze.Analyze.AnalyzeType), request.AnalyzeType).Where(nameof(Entity.Analyze.Analyze.CommentId), request.CommentId).Where(nameof(Entity.Analyze.Analyze.SourceUserId), request.SourceUserId));
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<Entity.Analyze.Analyze> GetAnalyzeAsync(AnalyzeRequest request)
        {
            var query = new SqlKata.Query();
            query.Where(nameof(Entity.Analyze.Analyze.SourceId), request.SourceId).Where(nameof(Entity.Analyze.Analyze.TypeValue), request.TypeValue).Where(nameof(Entity.Analyze.Analyze.AnalyzeType), request.AnalyzeType).Where(nameof(Entity.Analyze.Analyze.CommentId), request.CommentId);
            if (request.SourceUserId > 0)
                query.Where(nameof(Entity.Analyze.Analyze.SourceUserId), request.SourceUserId);
            return await _repository.GetAsync(query);
        }

        public async Task<bool> DeleteAsync(int id)
        {
            return await _repository.DeleteAsync(id);
        }
    }
}