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.TopicAnalyze;
using GxPress.Result.App.Topic;
using Microsoft.Extensions.Options;
using Datory;
using SqlKata;

namespace GxPress.Repository.Implement
{
    public class TopicAnalyzeRepository: ITopicAnalyzeRepository
    {
        private readonly Repository<TopicAnalyze> _repository;
        private readonly Repository<User> _userRepository;
        private readonly Repository<TopicComment> _topicCommentRepository;
        private readonly Repository<Entity.Topic.Topic> _topicRepository;
        private readonly Repository<Department> _departmentRepository;
        private readonly IMapper _mapper;

        public TopicAnalyzeRepository(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<TopicAnalyze>(database);
            _userRepository = new Repository<User>(database);
            _topicCommentRepository = new Repository<TopicComment>(database);
            _topicRepository = new Repository<Entity.Topic.Topic>(database);
            _departmentRepository=new Repository<Department>(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<bool> SetTopicAnalyzeAsync(TopicAnalyzeRequest request)
        {
            var user = await _userRepository.GetAsync(request.UserId);
            if (user == null) throw new BusinessException("不存在该账号");
            var topicAnalyze = await _repository.GetAsync(Q.Where(nameof(TopicAnalyze.AnalyzeType), request.TopicAnalyzeType)
                .Where(nameof(TopicAnalyze.TopicId), request.TopicId).Where(nameof(TopicAnalyze.TopicCommentId),request.TopicCommentId)
                .Where(nameof(TopicAnalyze.UserId), request.UserId));
            if (topicAnalyze != null && topicAnalyze.Id > 0)
                //throw new BusinessException("你已经点赞过了~!");
                return await _repository.DeleteAsync(topicAnalyze.Id);
            //查询该用户是否已经点赞过
            if (request.TopicAnalyzeType == 2)
            {
                if(request.TopicCommentId==0)
                   throw new BusinessException("评论Id必传!");
                //没有点赞则新增数据点赞条数
                var comment = await _topicCommentRepository.GetAsync(request.TopicCommentId);
                comment.Laud++;
                await _topicCommentRepository.UpdateAsync(comment);
            }
            return await InsertAsync(request);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> InsertAsync(TopicAnalyzeRequest request)
        {
            var topicAnalyze = new TopicAnalyze()
            {
                AnalyzeType = request.TopicAnalyzeType,
                TopicId = request.TopicId,
                TopicCommentId = request.TopicCommentId,
                UserId = request.UserId
            };
            return await _repository.InsertAsync(topicAnalyze) > 0;
        }
        /// <summary>
        /// 获取文章点赞数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PagedList<TopicPraisePageResult>> GetTopicPraisePageAsync(TopicPraisePageSearchRequest request)
        {
            var query = Q.NewQuery();
            query.Where(nameof(TopicAnalyze.AnalyzeType), 1).Where(nameof(TopicAnalyze.TopicId), request.TopicId);
              if(request.Sort=="desc")
                query.OrderByDesc(nameof(TopicAnalyze.CreatedDate));
            var pagedList = new PagedList<TopicPraisePageResult>
            {
                Total = await _repository.CountAsync(query)
            };
            var list = await _repository.GetAllAsync(query.ForPage(request.Page, request.PerPage));
            var items = list.Select(user => _mapper.Map<TopicPraisePageResult>(user)).ToList();
            //获取文章名称
            var topic = await _topicRepository.GetAsync(request.TopicId);
            foreach (var item in items)
            {
                //获取用户
                var user = await _userRepository.GetAsync(item.UserId);
                item.TopicName = topic.Title;
                item.UserName = user.Name;
                item.Signature = user.Signature;
                item.AvatarUrl =StringUtils.AddDomain(user.AvatarUrl);
                //获取部门
                var department = await _departmentRepository.GetAsync(user.DepartmentId);
                item.DepartmentName = department != null ? department.Name : "";
            }
            pagedList.Items = items;
            return pagedList;
        }

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

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

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