using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GxPress.Common.Exceptions;
using GxPress.Repository.Interface;
using GxPress.Request.App.Middle;
using GxPress.Request.Notice;
using GxPress.Service.Interface.Middle;
using Datory;
using GxPress.Entity.Middle;
using GxPress.Result.App.Middle;
using System.Transactions;
using GxPress.Repository.Interface.Collection;
using GxPress.Repository.Interface.Note;
using GxPress.Repository.Interface.Missive;
using GxPress.Common.Tools;
using GxPress.Repository.Interface.Analyze;
using GxPress.Service.Interface.UserMiddle;
using GxPress.Repository.Interface.RecordFolder;
using GxPress.Service.Interface.Analyze;
using GxPress.Request.App.Analyze;

namespace GxPress.Service.Implement.Middle
{
    public class MiddleService : IMiddleService
    {
        private readonly IMiddleRepository _middleRepository;
        private readonly IFolderUserRepository _folderUserRepository;
        private readonly IUserRepository _userRepository;
        private readonly ICollectionRepository _collectionRepository;
        private readonly INoteRepository _noteRepository;
        private readonly IMissiveRepository _missiveRepository;
        private readonly IGroupRepository _groupRepository;
        private readonly IAnalyzeRepository _analyzeRepository;
        private readonly INoticeRepository _noticeRepository;
        private readonly IUserMiddleService _userMiddleService;
        private readonly IAddresseeRepository _addresseeRepository;
        private readonly IRecordFolderRepository recordFolderRepository;
        private readonly IAnalyzeService analyzeService;
        public MiddleService(IMiddleRepository middleRepository, IFolderUserRepository folderUserRepository,
            IUserRepository userRepository, ICollectionRepository collectionRepository, INoteRepository noteRepository,
            IMissiveRepository missiveRepository, IGroupRepository groupRepository, INoticeRepository noticeRepository, IAnalyzeRepository analyzeRepository, IUserMiddleService userMiddleService, IAddresseeRepository addresseeRepository, IRecordFolderRepository recordFolderRepository, IAnalyzeService analyzeService)
        {
            _middleRepository = middleRepository;
            _folderUserRepository = folderUserRepository;
            _userRepository = userRepository;
            _collectionRepository = collectionRepository;
            _noteRepository = noteRepository;
            _missiveRepository = missiveRepository;
            _groupRepository = groupRepository;
            _noticeRepository = noticeRepository;
            _analyzeRepository = analyzeRepository;
            _userMiddleService = userMiddleService;
            _addresseeRepository = addresseeRepository;
            this.recordFolderRepository = recordFolderRepository;
            this.analyzeService = analyzeService;
        }

        /// <summary>
        /// 添加文件夹
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<int> InsertAsync(MiddleInsertRequest request)
        {
            var folderRoleId = new List<int> { 1, 2, 3 };
            if (!folderRoleId.Contains(request.RoleId) && (request.FolderType == 3 || request.FolderType == 4))
                throw new BusinessException("文件夹权限有误！");
            var oldMiddle = await _middleRepository.GetMiddleAsync(Q
                .Where(nameof(Entity.Middle.Middle.UserId), request.UserId)
                .Where(nameof(Entity.Middle.Middle.AttributeValue), 2)
                .Where(nameof(Entity.Middle.Middle.FolderType), request.FolderType)
                .Where(nameof(Entity.Middle.Middle.FolderName), request.FolderName)
                .Where(nameof(Entity.Middle.Middle.ParentId), request.ParentId).Where(nameof(Entity.Middle.Middle.IsDelete), false));
            if (string.IsNullOrEmpty(request.FolderName))
                throw new BusinessException("文件名称未填写！");
            if (oldMiddle != null)
                throw new BusinessException("文件夹名称重复，请重新命名！");
            var middle = new Entity.Middle.Middle
            {
                FolderName = request.FolderName,
                FolderType = request.FolderType,
                IsTop = false,
                AttributeValue = 2,
                ParentId = request.ParentId,
                RoleId = request.RoleId,
                UserId = request.UserId,
                Sort = 0
            };
            //存在父级
            var middleDto = new Entity.Middle.Middle();
            if (request.ParentId > 0)
            {
                //获取父级数据
                middleDto = await _middleRepository.GetMiddleAsync(request.ParentId);
                if (middleDto != null)
                {
                    middle.RoleId = middleDto.RoleId;
                    request.RoleId = middleDto.RoleId;
                    if (middleDto.ParentId == 0)
                        middle.MiddleSonId = middleDto.Id;
                    else middle.MiddleSonId = middleDto.MiddleSonId;
                }

            }
            if (request.RoleId == 0)
                middle.RoleId = 1;
            if (request.RoleId == 3)
            {
                if (request.UserIds == null)
                    request.UserIds = new List<int>();
                if (request.UserIds.Count == 0 && request.UserMiddles.Count == 0 && request.ParentId == 0)
                    throw new BusinessException("共享用户必须");
            }
            if (request.RoleId > 0)
                middle.RoleId = request.RoleId;
            var middleId = await _middleRepository.InsertAsync(middle);
            if (middle.ParentId == 0)
            {
                middle = await _middleRepository.GetMiddleAsync(middleId);
                if (middle != null)
                {
                    middle.MiddleSonId = middleId;
                    await _middleRepository.UpdateAsync(middle);
                }
            }
            await _middleRepository.UpdateAsync(Q.Set(nameof(Entity.Middle.Middle.Sort), middleId)
                .Where(nameof(Entity.Middle.Middle.Id), middleId));
            if (request.RoleId == 3 && request.ParentId == 0)
                //添加人员
                await InsertFolderUsers(request, middleId);
            return middleId;
        }

        /// <summary>
        /// 添加文件夹用户
        /// </summary>
        /// <param name="userIds"></param>
        /// <param name="middleId"></param>
        /// <returns></returns>
        public async Task<bool> InsertFolderUsers(MiddleInsertRequest request, int middleId)
        {
            //添加
            if (request.UserMiddles.Count > 0)
            {
                foreach (var item in request.UserMiddles)
                {
                    item.DataSourceId = middleId;
                    item.MiddleType = request.FolderType;
                }
                //添加中间表
                await _userMiddleService.AddUserMiddleAsync(request.UserMiddles);
                var users = await _userMiddleService.FindUsersAsync(request.UserMiddles, middleId);
                request.UserIds = users.Select(n => n.Id).ToList();
            }
            if (request.UserIds.Count > 0)
            {
                var users = await _userRepository.GetAllAsync(Q.WhereIn(nameof(Entity.User.Id), request.UserIds));
                //插入用户
                var folderUsers = new List<FolderUser>();
                foreach (var user in users)
                {
                    var folderUser = new FolderUser();
                    folderUser.UserId = user.Id;
                    folderUser.UserName = user.Name;
                    folderUser.MiddleId = middleId;
                    folderUsers.Add(folderUser);
                }
                return await _folderUserRepository.InsertsAsync(folderUsers.ToList());
            }
            return false;
        }

        /// <summary>
        /// 修改文件夹名称
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> UpdateNameAsync(MiddleUpdateNameRequest request)
        {
            var middle =
                await _middleRepository.GetMiddleAsync(Q.Where(nameof(Entity.Middle.Middle.Id), request.MiddleId)
                    .Where(nameof(Entity.Middle.Middle.AttributeValue), 1));
            if (middle == null)
                throw new BusinessException("文件不存在");
            return await _middleRepository.UpdateAsync(
                Q.Set(nameof(Entity.Middle.Middle.FolderName), request.FolderName).Where(
                    nameof(Entity.Middle.Middle.Id),
                    request.MiddleId));
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<int> InsertAsync(MiddleInsertTypeRequest request)
        {
            var middle = new Entity.Middle.Middle
            {
                MiddleId = request.MiddleId,
                FolderType = request.FolderType,
                IsTop = false,
                AttributeValue = request.AttributeValue,
                ParentId = request.FolderId,
                UserId = request.UserId,
                MiddleSonId = request.MiddleSonId,
                IsAdmin = request.IsAdmin,
                NoticeAddresseeType = request.NoticeAddresseeType,
                Title=request.Title,
                IsRead = false,
                IsUpload = false,
                TitleLong=request.TitleLong,
                Content=request.Content,
                AddressUser=request.AddressUser,
                CcUser=request.CcUser,
                CcUserComplete=request.CcUserComplete,
                AddressUserComplete=request.AddressUserComplete
            };
            if (request.AttributeValue == 0)
                middle.AttributeValue = 1;
            var middleId = await _middleRepository.InsertAsync(middle);
            await _middleRepository.UpdateAsync(Q.Set(nameof(Entity.Middle.Middle.Sort), middleId)
                .Where(nameof(Entity.Middle.Middle.Id), middleId));
            return middleId;
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> AddOrUpdateAsync(MiddleInsertTypeRequest request)
        {
            var middle = await _middleRepository.GetMiddleAsync(Q
                .Where(nameof(Entity.Middle.Middle.UserId), request.UserId)
                .Where(nameof(Entity.Middle.Middle.AttributeValue), 3)
                .Where(nameof(Entity.Middle.Middle.FolderType), request.FolderType));
            if (middle == null)
            {
                middle = new Entity.Middle.Middle
                {
                    MiddleId = request.MiddleId,
                    FolderType = request.FolderType,
                    IsTop = false,
                    AttributeValue = request.AttributeValue,
                    ParentId = request.FolderId,
                    UserId = request.UserId,
                    MiddleSonId = request.MiddleSonId
                };
                var middleId = await _middleRepository.InsertAsync(middle);
                //修改Middle sort
                await _middleRepository.UpdateAsync(Q.Where(nameof(Entity.Middle.Middle.Id), middleId).Set(nameof(Entity.Middle.Middle.Sort), middleId));
                return true;
            }

            return await _middleRepository.UpdateAsync(Q.Set(nameof(Entity.Middle.Middle.IsDelete), false)
                .Where(nameof(Entity.Middle.Middle.UserId), request.UserId)
                .Where(nameof(Entity.Middle.Middle.AttributeValue), 3));

        }

        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> MiddleSortAsync(MiddleSortRequest request)
        {
            return await _middleRepository.SetSortAsync(request);
        }

        /// <summary>
        /// 设置置顶
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> SetTopAsync(int id)
        {
            return await _middleRepository.SetTopAsync(id);
        }
        /// <summary>
        /// 删除 1 通知 2话题 3 收藏 4笔记 5 普通站内信 6匿名站内信 7 小组
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> DeleteAsync(NoticeDeRequest request)
        {
            try
            {
                using TransactionScope transactionScope = new TransactionScope();
                //查询middle
                var middles = await _middleRepository.FindAsync(Q.WhereIn(nameof(Entity.Middle.Middle.Id), request.MiddleIds));
                var ids = middles.Select(n => n.MiddleId).ToList();
                //收藏
                if (request.FolderType == 3)
                {
                    //查询收藏
                    var collections = await _collectionRepository.GetAllAsync(Q.WhereIn(nameof(Entity.Collection.Id), ids));
                    foreach (var item in collections)
                    {
                        var analyzeRequest = new AnalyzeRequest();
                        analyzeRequest.AnalyzeType = 3;
                        analyzeRequest.SourceId = item.CollectionDataId;
                        analyzeRequest.UserId = item.UserId;
                        //删除文章收藏
                        if (item.CollectionType == 1)
                        {
                            analyzeRequest.TypeValue = 0;
                            var analyze = await analyzeService.GetAnalyzeAsync(analyzeRequest);
                            if (analyze != null)
                                await _analyzeRepository.DeleteAsync(analyze.Id);
                        }
                        //删除话题收藏
                        if (item.CollectionType == 2)
                        {
                            analyzeRequest.TypeValue = 1;
                            var analyze = await analyzeService.GetAnalyzeAsync(analyzeRequest);
                            if (analyze != null)
                                await _analyzeRepository.DeleteAsync(analyze.Id);
                        }

                        //删除笔记收藏
                        if (item.CollectionType == 4)
                        {
                            analyzeRequest.TypeValue = 3;
                            var analyze = await analyzeService.GetAnalyzeAsync(analyzeRequest);
                            if (analyze != null)
                                await _analyzeRepository.DeleteAsync(analyze.Id);
                        }

                        //删除通知收藏
                        if (item.CollectionType == 5)
                        {
                            analyzeRequest.TypeValue = 2;
                            var analyze = await analyzeService.GetAnalyzeAsync(analyzeRequest);
                            if (analyze != null)
                                await _analyzeRepository.DeleteAsync(analyze.Id);
                            await _addresseeRepository.UpdateAsync(Q.Where(nameof(Entity.Addressee.UserId), request.UserId).WhereIn(nameof(Entity.Addressee.SourceId), ids).Set(nameof(Entity.Addressee.IsDelete), true));
                        }
                        //删除站内信收藏
                        if (item.CollectionType == 6)
                        {
                            analyzeRequest.TypeValue = 4;
                            var analyze = await analyzeService.GetAnalyzeAsync(analyzeRequest);
                            if (analyze != null)
                                await _analyzeRepository.DeleteAsync(analyze.Id);
                            await _addresseeRepository.UpdateAsync(Q.Where(nameof(Entity.Addressee.UserId), request.UserId).WhereIn(nameof(Entity.Addressee.SourceId), ids).Set(nameof(Entity.Addressee.IsDelete), true));
                        }
                        //删除收藏会议
                        if (item.CollectionType == 8)
                        {
                            analyzeRequest.TypeValue = 10;
                            var analyze = await analyzeService.GetAnalyzeAsync(analyzeRequest);
                            if (analyze != null)
                                await _analyzeRepository.DeleteAsync(analyze.Id);
                        }
                        //收藏笔记文件夹
                        if (item.CollectionType == 12 || item.CollectionType == 13)
                        {
                            analyzeRequest.TypeValue = item.CollectionType;
                            var analyze = await analyzeService.GetAnalyzeAsync(analyzeRequest);
                            if (analyze != null)
                                await _analyzeRepository.DeleteAsync(analyze.Id);
                        }
                    }
                    //删除收藏
                    request.IsDelete = true;
                    //删除
                    await _collectionRepository.RecursionDeleteAsync(request.MiddleIds);
                }
                //删除笔记
                if (request.FolderType == 4)
                {
                    await _noteRepository.UpdateAsync(Q.WhereIn(nameof(Entity.Note.Note.Id), ids).Set(nameof(Entity.Note.Note.IsDelete), true));
                    //删除默认共享文件夹
                    await recordFolderRepository.DeleteAsync(request.FolderType, request.UserId, request.MiddleIds);
                }
                //站内信
                // if (request.FolderType == 5)
                //     await _missiveRepository.DeleteAsync(Q.WhereIn(nameof(Entity.Missive.Missive.Id), ids));
                //小组
                if (request.FolderType == 7)
                    await _groupRepository.DeleteAsync(Q.WhereIn(nameof(Entity.Group.Id), ids));
                // //删除通知
                // if (request.FolderType == 1 && request.IsDelete)
                //     await _noticeRepository.DeleteAsync(Q.WhereIn(nameof(Entity.Notice.Id), middles.Select(n => n.MiddleId)));
                // //删除站内信
                // if (request.FolderType == 5 && request.IsDelete)
                //     await _missiveRepository.DeleteAsync(Q.WhereIn(nameof(Entity.Missive.Missive.Id), middles.Select(n => n.MiddleId)));
                //删除通知
                if (request.FolderType == 1)
                    await _addresseeRepository.UpdateAsync(Q.Where(nameof(Entity.Addressee.UserId), request.UserId).WhereIn(nameof(Entity.Addressee.SourceId), ids).Set(nameof(Entity.Addressee.IsDelete), true).Set(nameof(Entity.Addressee.IsRead), true));
                //删除站内信
                if (request.FolderType == 5)
                    await _addresseeRepository.UpdateAsync(Q.Where(nameof(Entity.Addressee.UserId), request.UserId).WhereIn(nameof(Entity.Addressee.SourceId), ids).Set(nameof(Entity.Addressee.IsDelete), true).Set(nameof(Entity.Addressee.IsRead), true));
                if (request.FolderType == 1 || request.FolderType == 5)
                {
                    foreach (var item in middles)
                    {
                        if (item.AttributeValue == 2)
                        {
                            //永久删除文件夹
                            await _middleRepository.DeleteAsync(Q.Where(nameof(Entity.Middle.Middle.Id), item.Id));
                            //修改文件夹下级数据
                            await _middleRepository.UpdateAsync(Q.Set(nameof(Entity.Middle.Middle.IsDelete), 1).Where(nameof(Entity.Middle.Middle.ParentId), item.Id));
                        }
                    }
                }
                //删除信源以及文件夹
                if (request.FolderType == 10)
                {
                    foreach (var middle in middles)
                    {
                        //判断是否文件夹
                        if (middle.AttributeValue == 2)
                            await _middleRepository.UpdateAsync(Q.Set(nameof(Entity.Middle.Middle.ParentId), 0).Where(nameof(Entity.Middle.Middle.ParentId), middle.Id).Where(nameof(Entity.Middle.Middle.FolderType), 10));
                    }
                }
                await _middleRepository.DeleteAsync(request);
                transactionScope.Complete();
            }
            catch (Exception ex)
            {
                throw new BusinessException(ex.Message);
            }
            return true;
        }

        public async Task<bool> RecoverDeleteAsync(NoticeDeRequest request)
        {
            return await _middleRepository.RecoverDeleteAsync(request);
        }

        public async Task<bool> SetMove(MiddleMoveRequest request)
        {
            return await _middleRepository.UpdateAsync(Q.Set(nameof(Entity.Middle.Middle.ParentId), request.ParentId).WhereIn(nameof(Entity.Middle.Middle.Id), request.Ids));
        }
        /// <summary>
        /// 恢复全部
        /// </summary>
        /// <param name="folderType"></param>
        /// <returns></returns>
        public async Task<bool> RecoverAllAsync(int folderType, int userId)
        {
            return await _middleRepository.UpdateAsync(Q.Set(nameof(Entity.Middle.Middle.IsDelete), false).Where(nameof(Entity.Middle.Middle.FolderType), folderType).Where(nameof(Entity.Middle.Middle.UserId), userId));

        }
        /// <summary>
        /// 修改文件夹名称
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> UpdateFolderNameAsync(MiddleFolderNameRequest request)
        {
            var middle = await _middleRepository.GetMiddleAsync(request.Id);
            if (middle == null)
                throw new BusinessException("文件夹不存在");
            var oldMiddle = await _middleRepository.GetMiddleAsync(Q
                .Where(nameof(Entity.Middle.Middle.UserId), request.UserId)
                .Where(nameof(Entity.Middle.Middle.AttributeValue), 2)
                .Where(nameof(Entity.Middle.Middle.FolderType), middle.FolderType)
                .Where(nameof(Entity.Middle.Middle.FolderName), request.FolderName)
                .Where(nameof(Entity.Middle.Middle.IsDelete), false));
            if (oldMiddle != null && oldMiddle.Id != middle.Id)
                throw new BusinessException("文件夹名称重复，请重新命名！");
            return await _middleRepository.UpdateFolderNameAsync(request);
        }

        /// <summary>
        /// 查询文件夹
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<List<MiddleSearchFolderResult>> SearchFolderAsync(MiddleSearchFolderRequest request)
        {
            var query = Q.NewQuery();
            query.Where(nameof(Entity.Middle.Middle.ParentId), request.ParentId)
                .Where(nameof(Entity.Middle.Middle.AttributeValue), 2)
                .Where(nameof(Entity.Middle.Middle.FolderType), request.TypeId)
                .Where(nameof(Entity.Middle.Middle.UserId), request.UserId)
                .Where(nameof(Entity.Middle.Middle.IsDelete), false).WhereNotIn(nameof(Entity.Middle.Middle.Id), request.FolderIds);
            if (!string.IsNullOrWhiteSpace(request.KeyWord))
                query.WhereLike(nameof(Entity.Middle.Middle.FolderName), $"%{request.KeyWord}%");
            if (request.RoleId > 0)
                query.Where(nameof(Entity.Middle.Middle.RoleId), request.RoleId);
            var middles = await _middleRepository.FindAsync(query.OrderByDesc(nameof(Entity.Middle.Middle.IsTop), nameof(Entity.Middle.Middle.Sort), nameof(Entity.Middle.Middle.LastModifiedDate)));
            List<MiddleSearchFolderResult> result = new List<MiddleSearchFolderResult>();
            foreach (var item in middles)
            {
                MiddleSearchFolderResult middleSearchFolderResult = new MiddleSearchFolderResult
                {
                    Name = item.FolderName,
                    Id = item.Id,
                    IsDisable = request.FolderIds.Any(n => n.Equals(item.Id)),
                    RoleId = item.RoleId,
                    IsFolder = await _middleRepository.IsFolderAsync(item.Id),
                    IsTop = item.IsTop
                };
                if (item.RoleId == 3)
                {
                    var sourceId = item.Id;
                    if (item.ParentId != 0)
                        sourceId = item.MiddleSonId;
                    var userMiddles = await _userMiddleService.FindUserMiddlesAsync(item.FolderType, sourceId);
                    // var folderUsers = await _folderUserRepository.GetAllAsync(Q.Where(nameof(FolderUser.MiddleId), item.Id).OrderByDesc(nameof(FolderUser.CreatedDate)).Take(10));
                    middleSearchFolderResult.EnjoyUser = StringUtils.ObjectCollectionToString(userMiddles.Select(n => n.SourceName), "、");
                }
                result.Add(middleSearchFolderResult);
            }

            return result;
        }

        /// <summary>
        /// 修改权限
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> UpdateFolderRoleAsync(MiddleUpdateFolderRoleRequest request)
        {
            var middle = await _middleRepository.GetMiddleAsync(request.MiddleId);
            if (middle == null)
                throw new BusinessException("文件夹不存在");
            var oldMiddle = await _middleRepository.GetMiddleAsync(Q
                .Where(nameof(Entity.Middle.Middle.UserId), middle.UserId)
                .Where(nameof(Entity.Middle.Middle.AttributeValue), 2)
                .Where(nameof(Entity.Middle.Middle.FolderType), middle.FolderType)
                .Where(nameof(Entity.Middle.Middle.FolderName), request.FolderName)
                .Where(nameof(Entity.Middle.Middle.ParentId), middle.ParentId).Where(nameof(Entity.Middle.Middle.IsDelete), false));
            if (string.IsNullOrEmpty(request.FolderName))
                throw new BusinessException("文件名称未填写");
            if (oldMiddle != null && oldMiddle.Id != middle.Id)
                throw new BusinessException("文件夹名称重复，请重新命名！");
            if (middle.RoleId == 3)
            {
                if (request.RoleId != 3)
                {
                    //删除共享用户
                    await _folderUserRepository.DeleteAsync(Q.Where(nameof(Entity.Middle.FolderUser.MiddleId), middle.Id));
                    //删除
                    await _userMiddleService.DeleteAsync(middle.Id, middle.FolderType);
                }
            }
            if (request.RoleId == 3 && middle.ParentId == 0)
            {
                if (request.UserIds.Count == 0 && request.UserMiddles.Count == 0)
                    throw new BusinessException("共享成员必须");
                //添加人员
                await _folderUserRepository.DeleteAsync(Q.Where(nameof(FolderUser.MiddleId), request.MiddleId));
                var middleInsertRequest = new MiddleInsertRequest();
                middleInsertRequest.UserIds = request.UserIds;
                middleInsertRequest.UserMiddles = request.UserMiddles;
                middleInsertRequest.FolderType = middle.FolderType;
                if (request.UserMiddles.Count > 0)
                {
                    //删除原有的数据
                    await _userMiddleService.DeleteAsync(middle.Id, middle.FolderType);
                    //await _userMiddleService.AddUserMiddleAsync(request.UserMiddles);
                    //查询用户
                    // var users = await _userMiddleService.FindUsersAsync(request.UserMiddles, middle.UserId);
                    // middleInsertRequest.UserIds = users.Select(n => n.Id).ToList();
                }
                await InsertFolderUsers(middleInsertRequest, request.MiddleId);
            }
            middle.RoleId = request.RoleId;
            middle.FolderName = request.FolderName;
            await _middleRepository.UpdateAsync(middle);
            //修改子集权限
            if (middle.ParentId == 0)
                await _middleRepository.UpdateAsync(Q.Set(nameof(Entity.Middle.Middle.RoleId), request.RoleId).Where(nameof(Entity.Middle.Middle.MiddleSonId), middle.Id));
            return true;
        }
        /// <summary>
        /// 修改共享文件夹下的所有文件夹属性
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> UpdateChildrenMiddleFolder(MiddleUpdateFolderRoleRequest request)
        {
            //获取下级数据
            var middles = await _middleRepository.GetMiddleChildrenAsync(request.MiddleId);
            if (middles.Count() == 0)
                return true;
            foreach (var item in middles)
            {
                if (request.UserMiddles.Count > 0)
                {
                    var middleInsertRequest = new MiddleInsertRequest();
                    middleInsertRequest.UserIds = request.UserIds;
                    middleInsertRequest.UserMiddles = request.UserMiddles;
                    //删除原有的数据
                    await _userMiddleService.DeleteAsync(item.Id, item.FolderType);
                    await _userMiddleService.AddUserMiddleAsync(request.UserMiddles);
                    //查询用户
                    var users = await _userMiddleService.FindUsersAsync(request.UserMiddles, item.UserId);
                    middleInsertRequest.UserIds = users.Select(n => n.Id).ToList();
                    //插入共享成员
                    await InsertFolderUsers(middleInsertRequest, request.MiddleId);
                    item.RoleId = request.RoleId;
                    item.FolderName = request.FolderName;
                    //修改
                    await _middleRepository.UpdateAsync(item);
                    request.MiddleId = item.Id;
                    //修改下级权限和共享范围人
                    await UpdateChildrenMiddleFolder(request);
                }

            }
            return true;
        }

        /// <summary>
        /// 根据文件夹ID获取文件夹信息
        /// </summary>
        /// <param name="middleId"></param>
        /// <returns></returns>
        public async Task<MiddleFolderInfoResult> GetFolderInfo(int middleId)
        {
            if (middleId == 0)
                throw new Common.Exceptions.BusinessException("文件夹不存在");
            var result = new MiddleFolderInfoResult();
            var middle = await _middleRepository.GetMiddleAsync(middleId);
            result.Id = middle.Id;
            result.FolderName = middle.FolderName;
            result.FolderType = middle.FolderType == 3 ? 12 : 13;
            result.UserId = middle.UserId;
            result.RoleId = middle.RoleId;
            result.FolderUsers = await _folderUserRepository.GetAllAsync(middleId);
            //获取共享人员
            if (result.RoleId == 3)
            {
                var sourceId = middle.Id;
                if (middle.ParentId > 0)
                    sourceId = middle.MiddleSonId;
                var userMiddles = await _userMiddleService.FindUserMiddlesAsync(middle.FolderType, sourceId);
                result.EnjoyUser = StringUtils.ObjectCollectionToString(userMiddles.Select(n => n.SourceName), "、");
                // var folderUsers = await _folderUserRepository.GetAllAsync(Q.Where(nameof(FolderUser.MiddleId), middle.Id).OrderByDesc(nameof(FolderUser.CreatedDate)).Take(10));
                // result.EnjoyUser = StringUtils.ObjectCollectionToString(folderUsers.Select(n => n.UserName), "、");
            }
            result.UserMiddles = await _userMiddleService.FindUserMiddlesAsync(middle.FolderType, middleId);
            return result;
        }
        /// <summary>
        /// 获取默认的共享文件夹范围
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<MiddleDefaultResult> GetEnjoyDefaultAsync(int userId, int folderType)
        {
            // var middle = await _middleRepository.GetMiddleAsync(Q.Where(nameof(Entity.Middle.Middle.UserId), userId).WhereIn(nameof(Entity.Middle.Middle.RoleId), new List<int> { 1, 3 }).Where(nameof(Entity.Middle.Middle.IsDefault), true));
            // var result = new MiddleDefaultResult();
            // result.IsDefault = middle != null;
            // result.FolderName = middle == null ? "" : middle.FolderName;
            // result.MiddleId = middle == null ? 0 : middle.Id;
            var recordFolder = await recordFolderRepository.GetAsync(folderType, userId);
            var result = new MiddleDefaultResult();
            result.IsDefault = recordFolder != null;
            result.FolderName = recordFolder == null ? "" : recordFolder.FolderName;
            result.FolderType = recordFolder == null ? 0 : recordFolder.FolderType;
            result.MiddleId = recordFolder == null ? 0 : recordFolder.FolderId;
            return result;
        }
        /// <summary>
        /// 获取话题 笔记共享范围文件夹
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<List<MiddleSearchFolderResult>> SearchNoteFolderAsync(MiddleSearchFolderRequest request)
        {
            var query = Q.NewQuery();
            query.Where(nameof(Entity.Middle.Middle.ParentId), request.ParentId)
                .Where(nameof(Entity.Middle.Middle.AttributeValue), 2)
                .Where(nameof(Entity.Middle.Middle.FolderType), request.TypeId)
                .Where(nameof(Entity.Middle.Middle.UserId), request.UserId)
                .Where(nameof(Entity.Middle.Middle.IsDelete), false).WhereNotIn(nameof(Entity.Middle.Middle.Id), request.FolderIds).WhereIn(nameof(Entity.Middle.Middle.RoleId), new List<int>() { 1, 3 });
            if (!string.IsNullOrWhiteSpace(request.KeyWord))
                query.Where(nameof(Entity.Middle.Middle.FolderName), request.KeyWord);

            var middles = await _middleRepository.FindAsync(query.OrderByDesc(
                nameof(Entity.Middle.Middle.AttributeValue), nameof(Entity.Middle.Middle.IsTop),
                nameof(Entity.Middle.Middle.CreatedDate)));
            List<MiddleSearchFolderResult> result = new List<MiddleSearchFolderResult>();
            foreach (var item in middles)
            {
                MiddleSearchFolderResult middleSearchFolderResult = new MiddleSearchFolderResult
                {
                    Name = item.FolderName,
                    Id = item.Id,
                    IsDisable = request.FolderIds.Any(n => n.Equals(item.Id)),
                    RoleId = item.RoleId,
                    IsFolder = await _middleRepository.IsFolderAsync(item.Id),
                    IsTop = item.IsTop
                };
                if (item.RoleId == 3)
                {
                    var sourceId = item.Id;
                    if (item.ParentId != 0)
                        sourceId = item.MiddleSonId;
                    var userMiddles = await _userMiddleService.FindUserMiddlesAsync(item.FolderType, sourceId);
                    // var folderUsers = await _folderUserRepository.GetAllAsync(Q.Where(nameof(FolderUser.MiddleId), item.Id).OrderByDesc(nameof(FolderUser.CreatedDate)).Take(10));
                    middleSearchFolderResult.EnjoyUser = StringUtils.ObjectCollectionToString(userMiddles.Select(n => n.SourceName), "、");
                    //middleSearchFolderResult.EnjoyUser = StringUtils.ObjectCollectionToString(folderUsers.Select(n => n.UserName), "、");
                }
                result.Add(middleSearchFolderResult);
            }

            return result;
        }
        /// <summary> =-
        /// 删除全部
        /// </summary>
        /// <param name="folderType"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<bool> DeleteAllAsync(int folderType, int userId)
        {
            return await _middleRepository.DeleteAsync(Q.Where(nameof(Entity.Middle.Middle.FolderType), folderType).Where(nameof(Entity.Middle.Middle.UserId), userId).Where(nameof(Entity.Middle.Middle.IsDelete), true));
        }
    }
}
