using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
using AutoMapper;
using GxPress.Common.Tools;
using GxPress.Entity.Topic;
using GxPress.Repository.Interface;
using GxPress.Request.App.Topic;
using GxPress.Service.Interface.Topic;
using Datory;
using GxPress.Common.Exceptions;
using GxPress.Common.Page;
using GxPress.Repository.Interface.Topic;
using GxPress.Result;
using GxPress.Result.App.Topic;
using GxPress.Service.Interface.Note;
using Newtonsoft.Json;
using GxPress.Repository.Interface.Visit;
using GxPress.Service.Interface.Visit;
using GxPress.Service.Interface.Analyze;
using GxPress.EnumConst;

namespace GxPress.Service.Implement.Topic
{
    public partial class TopicService : ITopicService
    {

        private readonly ITopicRepository _topicRepository;
        private readonly IUserRepository _userRepository;
        private readonly ITopicAddresseeRepository _topicAddresseeRepository;
        private readonly IDepartmentRepository _departmentRepository;
        private readonly ITopicGroupRepository _topicGroupRepository;
        private readonly ITopicGroupUserRepository _topicGroupUserRepository;
        private readonly IAnalyzeService _analyzeService;
        private readonly ICommentRepository _commentRepository;
        private readonly IMapper _mapper;
        private readonly IGroupUserRepository _groupUserRepository;
        private readonly IFolderUserRepository _folderUserRepository;
        private readonly INoteService _noteService;
        private readonly IMiddleRepository _middleRepository;
        private readonly IVisitRepository _visitRepository;

        private readonly IVisitService _visitService;
        public TopicService(ITopicRepository topicRepository, IUserRepository userRepository,
            ITopicAddresseeRepository topicAddresseeRepository,
            ITopicGroupRepository topicGroupRepository,
            ITopicGroupUserRepository topicGroupUserRepository, IAnalyzeService analyzeService,
            ICommentRepository commentRepository, IMapper mapper, IDepartmentRepository departmentRepository,
            IGroupUserRepository groupUserRepository, IFolderUserRepository folderUserRepository,
            INoteService noteService, IMiddleRepository middleRepository, IVisitRepository visitRepository, IVisitService visitService)
        {
            _topicRepository = topicRepository;
            _userRepository = userRepository;
            _topicAddresseeRepository = topicAddresseeRepository;
            _topicGroupRepository = topicGroupRepository;
            _topicGroupUserRepository = topicGroupUserRepository;
            _analyzeService = analyzeService;
            _commentRepository = commentRepository;
            _departmentRepository = departmentRepository;
            _mapper = mapper;
            _groupUserRepository = groupUserRepository;
            _folderUserRepository = folderUserRepository;
            _noteService = noteService;
            _middleRepository = middleRepository;
            _visitRepository = visitRepository;
            _visitService = visitService;
        }


        /// <summary>
        /// 根据GroupId删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<bool> DeleteTopicGroupAsync(List<int> ids)
        {
            try
            {
                using (TransactionScope transactionScope = new TransactionScope())
                {
                    await _topicGroupRepository.DeleteAsync(ids);
                    await _topicGroupUserRepository.DeleteGroupIdAsync(ids);
                    transactionScope.Complete();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            return false;
        }


        /// <summary>
        /// 获取话题列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PagedList<TopicListPageResult>> GetTopicPageAsync(TopicPageSearchRequest request)
        {
            var result = await _topicRepository.GetTopicPage(request);
            //获取数量
            // result.Total = 10;
            foreach (var item in result.Items)
            {
                if (string.IsNullOrWhiteSpace(item.UserName))
                {
                    item.Content = "[]";
                    item.Data = JsonConvert.DeserializeObject<List<ContentJsonData>>(item.Content);
                    item.Content = "";
                    continue;
                }
                if (string.IsNullOrWhiteSpace(item.Content))
                    item.Content = "[]";
                var contentJsonData = JsonConvert.DeserializeObject<List<ContentJsonData>>(item.Content);
                foreach (var contentJsonDataItem in contentJsonData)
                    contentJsonDataItem.File = StringUtils.AddDomain(contentJsonDataItem.File);
                if (contentJsonData.Count == 0)
                    item.DataType = 1;
                item.Content = "";
                if (contentJsonData.Count > 0)
                {
                    var imgData = new List<ContentJsonData>();
                    var FileData = new List<ContentJsonData>();
                    var forCount = 1;
                    var firstContent = string.Empty;
                    foreach (var jsonData in contentJsonData)
                    {
                        if (jsonData.TypeValue == OldTextEditorTypeConst.Text.GetHashCode() && forCount == 1)
                            //文本
                            firstContent = jsonData.Text;
                        else if (jsonData.TypeValue == OldTextEditorTypeConst.Text.GetHashCode() && forCount > 1)
                            //文本
                            continue;
                        //图片
                        else if (jsonData.TypeValue == OldTextEditorTypeConst.Image.GetHashCode() && FileData.Count == 0)
                        {
                            if (imgData.Count > 9)
                                break;
                            imgData.Add(jsonData);
                        }
                        //附件
                        else
                        {
                            FileData.Add(jsonData);
                            break;
                        }
                        forCount++;
                    }
                    item.Content = string.IsNullOrWhiteSpace(firstContent) ? "" : firstContent;
                    if (imgData.Count > 0) { item.DataType = 2; item.Data = imgData; }
                    else if (FileData.Count > 0) { item.DataType = 3; item.Data = FileData; }
                    else item.DataType = 1;
                    var contType = new List<int> { OldTextEditorTypeConst.Text.GetHashCode(), OldTextEditorTypeConst.Image.GetHashCode() };
                    item.FileCount = contentJsonData.Count(n => !contType.Contains(n.Type));
                }
                if (item.Data == null || item.Data.Count == 0)
                    item.Data = new List<ContentJsonData>();
            }
            return result;
        }
        /// <summary>
        /// APP列表显示用
        /// </summary>
        /// <param name="contentJsonDataList"></param>
        /// <returns></returns>
        public List<ContentJsonData> GetListAsync(List<ContentJsonData> contentJsonDataList)
        {
            var result = new List<ContentJsonData>();
            if (contentJsonDataList.Count > 0)
            {
                //查询文本
                var txtType = contentJsonDataList.FirstOrDefault(n => n.Type == 1);
                if (txtType != null)
                    result.Add(txtType);
                //拼接图片
                var imgType = contentJsonDataList.FindAll(n => n.Type == 2);
                if (imgType.Any())
                {
                    foreach (var item in imgType)
                    {
                        //判断图片数量
                        if (result.Count(n => n.Type == 2) > 8)
                            break;
                        result.Add(item);
                    }
                }
                else
                {
                    var values = new List<int> { 1, 2 };
                    var list = contentJsonDataList.FindAll(n => !values.Contains(n.Type));
                    if (list.Any())
                        result.Add(list.FirstOrDefault());
                }
            }
            return result;
        }


        /// <summary>
        /// 添加话题分组成员
        /// </summary>
        /// <param name="userIds"></param>
        /// <param name="topicGroupId"></param>
        /// <returns></returns>
        public async Task<bool> InsertTopicGroupUserAsync(List<int> userIds, int topicGroupId)
        {
            try
            {
                using (TransactionScope transactionScope = new TransactionScope())
                {
                    //获取话题小组成员
                    var topicGroupUsers =
                        await _topicGroupUserRepository.GetAllAsync(Q.Where(nameof(TopicGroupUser.TopicGroupId),
                            topicGroupId));
                    var groupUsers = topicGroupUsers as TopicGroupUser[] ?? topicGroupUsers.ToArray();
                    foreach (var userId in userIds)
                    {
                        if (groupUsers.Any(n => n.UserId == userId))
                            continue;
                        var topicGroupUser = new TopicGroupUser { TopicGroupId = topicGroupId, UserId = userId };
                        await _topicGroupUserRepository.InsertAsync(topicGroupUser);
                    }

                    //获取人数
                    var includeCount =
                        await _topicGroupUserRepository.CountAsync(Q.Where(nameof(TopicGroupUser.TopicGroupId),
                            topicGroupId));
                    //修改人数
                    await _topicGroupRepository.UpdateAsync(Q.Where(nameof(TopicGroup.Id), topicGroupId)
                        .Set(nameof(TopicGroup.IncludeCount), includeCount));
                    transactionScope.Complete();
                    return true;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
        /// <summary>
        /// 根据ID删除换题分组成员
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<bool> DeleteTopicGroupUserAsync(List<int> ids)
        {
            if (ids.Count == 0)
                throw new BusinessException("删除的话题分组成员不存在");
            try
            {
                using (TransactionScope transactionScope = new TransactionScope())
                {
                    //查询分组
                    var topicGroupUser = await _topicGroupUserRepository.GetAsync(ids[0]);
                    await _topicGroupUserRepository.DeleteAsync(Q.WhereIn(nameof(TopicGroupUser.Id), ids));
                    var count = await _topicGroupUserRepository.CountAsync(Q.Where(nameof(TopicGroupUser.TopicGroupId),
                        topicGroupUser.TopicGroupId));
                    //修改数量
                    await _topicGroupRepository.UpdateAsync(Q.Set(nameof(TopicGroup.IncludeCount), count)
                        .Where(nameof(TopicGroup.Id), topicGroupUser.TopicGroupId));
                    transactionScope.Complete();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            return true;

        }


        /// <summary>
        /// 话题分组移动成员到
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> MoveToGroupAsync(MoveToGroupRequest request)
        {
            using (TransactionScope transactionScope = new TransactionScope())
            {
                //获取源小组ID
                var topicGroupUser = await _topicGroupUserRepository.GetAsync(request.Ids[0]);
                //
                await _topicGroupUserRepository.UpdateAsync(Q
                    .Set(nameof(TopicGroupUser.TopicGroupId), request.TopicGroupId)
                    .WhereIn(nameof(TopicGroupUser.Id), request.Ids));
                //原始修改数量
                var originalCount = await _topicGroupUserRepository.CountAsync(Q.Where(nameof(TopicGroupUser.TopicGroupId),
                    topicGroupUser.TopicGroupId));
                await _topicGroupRepository.UpdateAsync(Q.Set(nameof(TopicGroup.IncludeCount), originalCount)
                    .Where(nameof(TopicGroup.Id), topicGroupUser.TopicGroupId));
                //修改数量
                var count = await _topicGroupUserRepository.CountAsync(Q.Where(nameof(TopicGroupUser.TopicGroupId),
                    request.TopicGroupId));
                await _topicGroupRepository.UpdateAsync(Q.Set(nameof(TopicGroup.IncludeCount), count)
                    .Where(nameof(TopicGroup.Id), request.TopicGroupId));
                transactionScope.Complete();
            }

            return true;
        }

        /// <summary>
        /// 根据GroupId获取通知
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PagedList<TopicListPageResult>> FindTopicByGroupIdAsync(TopicDetailListRequest request)
        {
            //根据groupID查询话题
            var topics = await _topicRepository.GetAllAsync(Q.Where(nameof(Entity.Topic.Topic.GroupId), request.GroupId));
            //根据话题ID修改用户的阅读
            await _topicAddresseeRepository.UpdateAsync(Q.WhereIn(nameof(Entity.Topic.TopicAddressee.TopicId), topics.Select(n => n.Id).ToList()).Where(nameof(Entity.Topic.TopicAddressee.UserId), request.UserId).Set(nameof(Entity.Topic.TopicAddressee.IsRead), true));
            var topicListPageResults = await _topicRepository.FindTopicByGroupIdAsync(request);
            foreach (var item in topicListPageResults.Items)
            {
                // var analyzeRequest = new Request.App.Analyze.AnalyzeRequest();
                // analyzeRequest.TypeValue = 1;
                // analyzeRequest.AnalyzeType = 1;
                // analyzeRequest.SourceId = item.Id;
                // analyzeRequest.UserId = request.UserId;
                // //点赞数量
                // item.PraiseCount = await _analyzeService.CountAsync(analyzeRequest);
                // //获取话题的评论数量
                // var commentCount =
                //     await _commentRepository.CountAsync(Q.Where(nameof(Entity.Comment.ArticleId), item.Id).Where(nameof(Entity.Comment.TypeValue), 1));
                // item.CommentCount = commentCount;
                // //获取话题的转发数量
                // analyzeRequest.AnalyzeType = 4;
                // var retransmissionCount = await _analyzeService.CountAsync(analyzeRequest);
                // item.RetransmissionCount = retransmissionCount;
                // item.IsRetransmission = await _analyzeService.ExistsAsync(analyzeRequest);
                // //获取话题的收藏数量
                // analyzeRequest.AnalyzeType = 3;
                // var collectCount = await _analyzeService.CountAsync(analyzeRequest);
                // item.CollectCount = collectCount;
                // //是否收藏
                // item.IsCollect = await _analyzeService.ExistsAsync(analyzeRequest);
                // //获取话题的点赞数量
                // analyzeRequest.AnalyzeType = 1;
                // var praiseCount = await _analyzeService.CountAsync(analyzeRequest);
                // item.PraiseCount = praiseCount;
                // //是否点赞
                // item.IsPraise = await _analyzeService.ExistsAsync(analyzeRequest);
                if (string.IsNullOrWhiteSpace(item.Content))
                    item.Content = "[]";
                var contentJsonData = JsonConvert.DeserializeObject<List<ContentJsonData>>(item.Content);
                foreach (var contentJsonDataItem in contentJsonData)
                    contentJsonDataItem.File = StringUtils.AddDomain(contentJsonDataItem.File);
                if (contentJsonData.Count == 0)
                    item.DataType = 1;
                item.Content = "";
                if (contentJsonData.Count > 0)
                {
                    var imgData = new List<ContentJsonData>();
                    var FileData = new List<ContentJsonData>();
                    var forCount = 1;
                    var firstContent = string.Empty;
                    foreach (var jsonData in contentJsonData)
                    {
                        if (jsonData.TypeValue == OldTextEditorTypeConst.Text.GetHashCode() && forCount == 1)
                            //文本
                            firstContent = jsonData.Text;
                        else if (jsonData.TypeValue == OldTextEditorTypeConst.Text.GetHashCode() && forCount > 1)
                            //文本
                            continue;
                        //图片
                        else if (jsonData.TypeValue == OldTextEditorTypeConst.Image.GetHashCode() && FileData.Count == 0)
                        {
                            if (imgData.Count > 9)
                                break;
                            imgData.Add(jsonData);
                        }
                        //附件
                        else
                        {
                            FileData.Add(jsonData);
                            break;
                        }
                        forCount++;
                    }
                    item.Content = string.IsNullOrWhiteSpace(firstContent) ? "" : firstContent;
                    if (imgData.Count > 0) { item.DataType = 2; item.Data = imgData; }
                    else if (FileData.Count > 0) { item.DataType = 3; item.Data = FileData; }
                    else item.DataType = 1;
                    var contType = new List<int> { OldTextEditorTypeConst.Text.GetHashCode(), OldTextEditorTypeConst.Image.GetHashCode() };
                    item.FileCount = contentJsonData.Count(n => !contType.Contains(n.Type));
                }
                if (item.Data == null || item.Data.Count == 0)
                    item.Data = new List<ContentJsonData>();
                //item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
            }
            return topicListPageResults;
        }
    }
}
