using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
using AutoMapper;
using Datory;
using GxPress.Common.Exceptions;
using GxPress.Common.Page;
using GxPress.Common.Tools;
using GxPress.Entity;
using GxPress.EnumConst;
using GxPress.Repository.Interface;
using GxPress.Request.App.AdminVerify;
using GxPress.Request.App.Group;
using GxPress.Request.App.GroupUser;
using GxPress.Request.App.Middle;
using GxPress.Result.App.Group;
using GxPress.Result.App.GroupUser;
using GxPress.Service.Interface.AdminVerify;
using GxPress.Service.Interface.Group;
using GxPress.Service.Interface.Middle;

namespace GxPress.Service.Implement.Group
{
    public partial class GroupService : IGroupService
    {
        private readonly IGroupRepository _groupRepository;
        private readonly IGroupUserRepository _groupUserRepository;
        private readonly ITopicRepository _topicRepository;
        private readonly IMiddleService _middleService;
        private readonly IAdminVerifyInsertService _adminVerifyService;
        private readonly IMiddleRepository _middleRepository;
        private readonly IMapper _mapper;
        private readonly IUserRepository _userRepository;

        public GroupService(IGroupRepository groupRepository, IGroupUserRepository groupUserRepository,
            ITopicRepository topicRepository, IMiddleService middleService,
            IAdminVerifyInsertService adminVerifyService, IMiddleRepository middleRepository, IMapper mapper,
            IUserRepository userRepository)
        {
            _groupRepository = groupRepository;
            _groupUserRepository = groupUserRepository;
            _topicRepository = topicRepository;
            _middleService = middleService;
            _adminVerifyService = adminVerifyService;
            _middleRepository = middleRepository;
            _mapper = mapper;
            _userRepository = userRepository;
        }

        /// <summary>
        /// 添加小组
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<GroupDetailResult> InsertGroup(GroupInRequest request)
        {
            if (string.IsNullOrEmpty(request.Name))
                throw new BusinessException("小组名称不能为空");
            if (string.IsNullOrEmpty(request.Introduce))
                throw new BusinessException("小组简介不能为空");
            if (string.IsNullOrEmpty(request.AvatarUrl))
                throw new BusinessException("小组头像不能为空");
            try
            {
                using (TransactionScope transactionScope = new TransactionScope())
                {
                    var groupId = await _groupRepository.InsertAsync(request);
                    await _groupUserRepository.InsertAsync(request.UserId, groupId, GroupUserRoleTyeConst.SuperAdmin);
                    //插入用户
                    //await AddUsersAsync(new GroupUserInRequest { GroupId = groupId, UserIds = request.UserIds });
                    //新建中间件
                    var result = new MiddleInsertTypeRequest
                    {
                        MiddleSonId = 0,
                        FolderId = request.GroupFolderId,
                        FolderType = 7,
                        MiddleId = groupId,
                        UserId = request.UserId
                    };
                    await _middleService.InsertAsync(result);
                    var group = await _groupRepository.GetAsync(groupId);
                    var groupDetail = _mapper.Map<GroupDetailResult>(group);
                    var user = await _userRepository.GetAsync(group.UserId);
                    groupDetail.UserName = user.Name;
                    groupDetail.AvatarUrl = StringUtils.AddDomain(groupDetail.AvatarUrl);
                    groupDetail.QRCoder = StringUtils.AddDomain(groupDetail.QRCoder);
                    transactionScope.Complete();
                    return groupDetail;
                }
            }
            catch (Exception e)
            {
                throw new BusinessException(e.Message);
            }

        }


        /// <summary>
        /// 根据用户ID文件夹ID查询小组
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PagedList<GroupUserFindResult>> FindGroupByGroupFolderIdAsync(GroupSearchRequest request)
        {
            var result = await _groupRepository.FindGroupByGroupFolderId(request);
            foreach (var item in result.Items)
            {
                // //共享数量
                // item.TopicSharingCount = await _groupRepository.SharingCountAsync(item.GroupId);
                // //总话题数量
                // item.TopicAllCount = await _topicRepository.GetGroupTopicCountAsync(item.GroupId);
                //未读话题数量
                //item.UReadTopicCount = await _groupRepository.GetUReadCountAsync(request.UserId, item.GroupId);
                //获取目录名称
                // var middle =
                //     await _middleRepository.GetMiddleAsync(Q.Where(nameof(Entity.Middle.Middle.Id), item.ParentId));
                if (string.IsNullOrWhiteSpace(item.CategoryName))
                {
                    item.CategoryName = "根目录";
                }

            }
            return result;
        }
        /// <summary>
        /// 添加成员
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> InsertsAsync(GroupUserInRequest request)
        {
            //获取当前小组
            var group = await _groupRepository.GetAsync(request.GroupId);
            //不是管理员添加
            if (request.SourceType == 2 || group.IsAdmin && request.SourceType == 1)
            {
                var adminVerifyInsertRequest = new AdminVerifyInsertRequest
                {
                    AdminId = group.UserId,
                    UserIds = request.UserIds,
                    VerifyType = GroupTypeConst.Group,
                    SourceId = group.Id,
                    UserId = request.UserId,
                    SourceType = request.SourceType
                };
                await _adminVerifyService.InsertAsync(adminVerifyInsertRequest);
                // if (request.SourceType == 2)
                //     throw new BusinessException("等待用户同意同意");
                // if (request.SourceType == 1)
                //     throw new BusinessException("等待管理员同意");
            }

            if (!group.IsAdmin && request.SourceType == 1)
            {
                //管理员插入
                await AddUsersAsync(request);
                return true;
            }

            return false;
        }

        /// <summary>
        /// 小组添加用户
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> AddUsersAsync(GroupUserInRequest request)
        {
            var groupUsers = await _groupUserRepository.GetAllAsync(Q.Where(nameof(GroupUser.GroupId), request.GroupId)
                .WhereIn(nameof(GroupUser.UserId), request.UserIds));
            var middles = new List<Entity.Middle.Middle>();
            var groupUserList = new List<GroupUser>();
            foreach (var item in request.UserIds)
            {
                if (groupUsers.Any(n => n.UserId == item))
                    continue;
                var groupUser = new GroupUser
                {
                    GroupId = request.GroupId,
                    UserId = item,
                    GroupUserRoleId = GroupUserRoleTyeConst.General,
                    IsUDisturb = false
                };
                groupUserList.Add(groupUser);
                //await _groupUserRepository.InsertAsync(groupUser);
                //新建中间件
                var result = new MiddleInsertTypeRequest
                {
                    MiddleSonId = 0,
                    FolderId = 0,
                    FolderType = 7,
                    MiddleId = request.GroupId,
                    UserId = item,
                    IsRead = false
                };
                var middle = new Entity.Middle.Middle
                {
                    MiddleId = result.MiddleId,
                    FolderType = result.FolderType,
                    IsTop = false,
                    AttributeValue = result.AttributeValue,
                    ParentId = result.FolderId,
                    UserId = result.UserId,
                    MiddleSonId = result.MiddleSonId,
                    IsAdmin = result.IsAdmin,
                    NoticeAddresseeType = result.NoticeAddresseeType,
                    IsRead = false,
                    IsUpload = false
                };
                if (result.AttributeValue == 0)
                    middle.AttributeValue = 1;
                middles.Add(middle);
            }
            await _middleRepository.InsertAsync(middles);
            await _groupUserRepository.InsertAsync(groupUserList);
            return true;
        }



        /// <summary>
        /// 获取小组详情
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<GroupDetailResult> GroupDetailAsync(GroupDetailRequest request)
        {
            var result = await _groupRepository.GroupDetailAsync(request);
            var user = await _userRepository.GetAsync(result.UserId);
            result.UserName = user.Name;
            result.GroupUserNumber = result.GroupUserListResult.Count();
            //获取小组话题数量
            result.GroupTopicNumber = await _topicRepository.GetGroupTopicCountAsync(result.Id);
            return result;
        }

        /// <summary>
        /// 获取小组详情
        /// </summary>
        /// <param name="guId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<GroupDetailResult> GroupDetailByGuIdAsync(string guId, int userId)
        {
            var result = await _groupRepository.GroupDetailByGuIdAsync(guId, userId);
            var user = await _userRepository.GetAsync(result.UserId);
            result.UserName = user.Name;
            result.GroupUserNumber = result.GroupUserListResult.Count();
            result.IsUser = result.GroupUserListResult.Any(n => n.UserId == userId);
            //获取小组话题数量
            result.GroupTopicNumber = await _topicRepository.GetGroupTopicCountAsync(result.Id);
            return result;
        }
    }
}
