using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Datory;
using GxPress.Common.Exceptions;
using GxPress.Common.Page;
using GxPress.Common.Tools;
using GxPress.EnumConst;
using GxPress.Repository.Interface;
using GxPress.Repository.Interface.Missive;
using GxPress.Request.App.Middle;
using GxPress.Request.App.Missive;
using GxPress.Result;
using GxPress.Result.App.Missive;
using GxPress.Result.User;
using GxPress.Service.Interface.Analyze;
using GxPress.Service.Interface.Middle;
using GxPress.Service.Interface.Missive;
using GxPress.Service.Interface.UserMiddle;
using Newtonsoft.Json;
using IMapper = AutoMapper.IMapper;
using System.Transactions;
using GxPress.Entity;
using GxPress.Service.Interface.ContentJson;

namespace GxPress.Service.Implement.Missive
{
    public partial class MissiveService : IMissiveService
    {
        private readonly IMissiveRepository _missiveRepository;
        private readonly IUserRepository _userRepository;
        private readonly IMiddleService _middleService;
        private readonly IMapper _mapper;
        private readonly IMiddleRepository _middleRepository;
        private readonly IAnalyzeService _analyzeService;
        private readonly IUserMiddleService _userMiddleService;

        private readonly IAddresseeRepository _addresseeRepository;
        private readonly ICcRepository _ccRepository;
        private readonly IContentJsonService _contentJsonService;
        public MissiveService(IMissiveRepository missiveRepository,
            IUserRepository userRepository,
            IMiddleService middleService, IMapper mapper, IMiddleRepository middleRepository, IAnalyzeService analyzeService, IUserMiddleService userMiddleService, IAddresseeRepository addresseeRepository, ICcRepository ccRepository, IContentJsonService contentJsonService)
        {
            _missiveRepository = missiveRepository;
            _userRepository = userRepository;
            _middleService = middleService;
            _mapper = mapper;
            _middleRepository = middleRepository;
            _analyzeService = analyzeService;
            _userMiddleService = userMiddleService;
            _addresseeRepository = addresseeRepository;
            _ccRepository = ccRepository;
            _contentJsonService = contentJsonService;
        }

        /// <summary>
        /// 添加修改站内信
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> InsertOrUpdateAsync(MissiveInRequest request)
        {
            var missive = new Entity.Missive.Missive();
            var middle = new Entity.Middle.Middle();
            if (request.Id > 0)
            {
                //获取当前站内信
                missive = await _missiveRepository.GetAsync(request.Id);
                if (missive != null)
                {
                    middle = await _middleRepository.GetMiddleAsync(Q.Where(nameof(Entity.Middle.Middle.MiddleId), missive.Id).Where(nameof(Entity.Middle.Middle.FolderType), GxPress.EnumConst.FolderTypeConst.Missive.GetHashCode()));
                }
            }
            //收件人
            if (request.MissiveAttributeType == NoticeTypeConst.Send)
            {
                if (request.MissiveAddresseeUserIds.Count == 0 && request.AddresseeUserMiddles.Count == 0)
                    throw new BusinessException("收件人不能为空");
                if (request.Id > 0)
                {
                    //获取当前站内信
                    if (missive != null)
                    {
                        if (middle.NoticeAddresseeType == NoticeTypeConst.Draft)
                        {
                            //删除草稿
                            await _missiveRepository.DeleteAsync(Q.Where(nameof(Entity.Missive.Missive.Id), request.Id));
                            //删除middle
                            await _middleRepository.DeleteAsync(Q.Where(nameof(Entity.Middle.Middle.MiddleId), request.Id).Where(nameof(Entity.Middle.Middle.FolderType), GxPress.EnumConst.FolderTypeConst.Missive.GetHashCode()));
                            missive = await _missiveRepository.GetAsync(Q.Where(nameof(Entity.Missive.Missive.Id), missive.SourceId));
                            if (missive != null)
                                request.Id = missive.Id;
                            else
                                request.Id = 0;

                        }
                    }
                }
            }
            if (request.Id == 0)
            {
                if (string.IsNullOrEmpty(request.Title) && string.IsNullOrEmpty(request.HtmlContent))
                    throw new BusinessException("标题内容为空");
                if (request.UserId == 0)
                    throw new BusinessException("用户不存在");
            }
            var user = await _userRepository.GetAsync(request.UserId);

            if (request.Id == 0)
            {
                var data = JsonConvert.DeserializeObject<List<ContentJsonData>>(request.Content);
                foreach (var item in data)
                    item.File = StringUtils.RemoveDomain(item.File);
                request.Content = JsonConvert.SerializeObject(data);
                using (TransactionScope transactionScope = new TransactionScope())
                {
                    missive = new Entity.Missive.Missive
                    {
                        ParentId = request.ParentId,
                        Content = request.Content,
                        Title = request.Title,
                        UserId = request.UserId,
                        UserName = user.Name,
                        HtmlContent = request.HtmlContent,
                        MissiveType = request.MissiveType,
                        SendUserId = request.UserId
                    };
                    request.Id = await _missiveRepository.InsertAsync(missive);
                    var addressee = new Addressee
                    {
                        SourceId = request.Id,
                        UserId = request.UserId,
                        UserName = "",
                        IsAdmin = true,
                        IsRead = true,
                        IsDelete = false,
                        SourceType = GxPress.EnumConst.FolderTypeConst.Missive.GetHashCode()
                    };
                    await _addresseeRepository.InsertAsync(addressee);
                    //插入中间件
                    var result = new MiddleInsertTypeRequest
                    {
                        MiddleSonId = 0,
                        FolderId = request.FolderId,
                        FolderType = GxPress.EnumConst.FolderTypeConst.Missive.GetHashCode(),
                        MiddleId = request.Id,
                        UserId = request.UserId,
                        AttributeValue = 1,
                        NoticeAddresseeType = request.MissiveAttributeType,
                        IsAdmin = true,
                        Title = _contentJsonService.GetTitile(request.Title, request.Content),
                        TitleLong = request.Title,
                        Content = request.Content,
                    };
                    await _middleService.InsertAsync(result);
                    transactionScope.Complete();
                }
            }
            else
            {
                //
                //修改
                if (!string.IsNullOrEmpty(request.Content))
                {
                    var data = JsonConvert.DeserializeObject<List<ContentJsonData>>(request.Content);
                    foreach (var item in data)
                        item.File = StringUtils.RemoveDomain(item.File);
                    request.Content = JsonConvert.SerializeObject(data);
                    missive.Content = request.Content;
                    missive.HtmlContent = request.HtmlContent;
                }
                if (!string.IsNullOrEmpty(request.Title))
                    missive.Title = request.Title;
                //如果是草稿
                if (request.MissiveAttributeType == NoticeTypeConst.Draft && middle.NoticeAddresseeType == NoticeTypeConst.Send)
                {
                    missive.SourceId = request.Id;
                    var missiveId = await _missiveRepository.InsertAsync(missive);
                    //插入中间件
                    var result = new MiddleInsertTypeRequest
                    {
                        MiddleSonId = 0,
                        FolderId = request.FolderId,
                        FolderType = GxPress.EnumConst.FolderTypeConst.Missive.GetHashCode(),
                        MiddleId = missiveId,
                        UserId = request.UserId,
                        AttributeValue = 1,
                        NoticeAddresseeType = request.MissiveAttributeType,
                        IsAdmin = true,
                        Title = _contentJsonService.GetTitile(request.Title, request.Content),
                        TitleLong = request.Title,
                        Content = request.Content,
                    };
                    await _middleService.InsertAsync(result);
                    request.Id = missiveId;
                }
                else
                    await _missiveRepository.UpdateAsync(missive);
            }
            if (await SendMissive(request, request.Id)) return true;
            return true;
        }
        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="request"></param>
        /// <param name="missiveId"></param>
        /// <returns></returns>
        private async Task<bool> SendMissive(MissiveInRequest request, int missiveId)
        {
            var addresseeUsers = new List<User>();
            var ccUsers = new List<User>();
            //删除收件人
            await _addresseeRepository.DeleteAsync(missiveId, GxPress.EnumConst.FolderTypeConst.Missive.GetHashCode(), 0);
            //删除抄送人
            await _ccRepository.DeleteAsync(missiveId, GxPress.EnumConst.FolderTypeConst.Missive.GetHashCode());
            //获取收件人
            request.MissiveAddresseeUserIds = request.MissiveAddresseeUserIds.Distinct().ToList();
            //获取抄送人
            request.MissiveCcUserIds = request.MissiveCcUserIds.Distinct().ToList();
            //删除新版收件人
            await _userMiddleService.DeleteAsync(Q.Where(nameof(Entity.UserMiddle.UserMiddle.MiddleType), 30).Where(nameof(Entity.UserMiddle.UserMiddle.DataSourceId), request.Id));
            //删除新版抄送人
            await _userMiddleService.DeleteAsync(Q.Where(nameof(Entity.UserMiddle.UserMiddle.MiddleType), 40).Where(nameof(Entity.UserMiddle.UserMiddle.DataSourceId), request.Id));
            //判断是不是新版通知
            if (request.AddresseeUserMiddles.Count > 0)
            {
                foreach (var item in request.AddresseeUserMiddles)
                {
                    item.DataSourceId = missiveId;
                    item.MiddleType = 30;
                }
                await _userMiddleService.AddUserMiddleAsync(request.AddresseeUserMiddles);
                //获取用户
                addresseeUsers = await _userMiddleService.FindUsersAsync(request.AddresseeUserMiddles, request.UserId);
                request.MissiveAddresseeUserIds = addresseeUsers.Select(n => n.Id).ToList();
            }
            if (request.CcUserMiddles.Count > 0)
            {
                foreach (var item in request.CcUserMiddles)
                {
                    item.DataSourceId = missiveId;
                    item.MiddleType = 40;
                }
                await _userMiddleService.AddUserMiddleAsync(request.CcUserMiddles);
                ccUsers = await _userMiddleService.FindUsersAsync(request.CcUserMiddles, request.UserId);
                request.MissiveCcUserIds = ccUsers.Select(n => n.Id).ToList();
                //添加抄送人
                request.MissiveAddresseeUserIds.AddRange(request.MissiveCcUserIds);
            }
            request.MissiveCcUserIds = request.MissiveCcUserIds.Distinct().ToList();
            request.MissiveAddresseeUserIds = request.MissiveAddresseeUserIds.Distinct().ToList();
            request.MissiveCcUserIds.Remove(request.UserId);
            request.MissiveAddresseeUserIds.Remove(request.UserId);
            var addressees = new List<Addressee>();
            var middles = new List<Entity.Middle.Middle>();
            var ccs = new List<Entity.Cc>();
            //添加收件人
            foreach (var userId in request.MissiveAddresseeUserIds)
            {
                var addressee = new Addressee
                {
                    SourceId = missiveId,
                    UserId = userId,
                    UserName = "",
                    IsAdmin = false,
                    IsRead = false,
                    IsDelete = false,
                    SourceType = GxPress.EnumConst.FolderTypeConst.Missive.GetHashCode()
                };
                addressees.Add(addressee);
                // await _missiveAddresseeRepository.InsertAsync(missiveAddressee);
                //如果是发送
                if (request.MissiveAttributeType == NoticeTypeConst.Send)
                {
                    var middle = new Entity.Middle.Middle
                    {
                        MiddleId = missiveId,
                        FolderType = GxPress.EnumConst.FolderTypeConst.Missive.GetHashCode(),
                        IsTop = false,
                        AttributeValue = 1,
                        ParentId = 0,
                        UserId = userId,
                        MiddleSonId = 0,
                        IsAdmin = false,
                        NoticeAddresseeType = request.MissiveAttributeType,
                        IsRead = false,
                        Title = _contentJsonService.GetTitile(request.Title, request.Content),
                        TitleLong = request.Title,
                        Content = request.Content,
                        AddressUserComplete = Common.Tools.StringUtils.ObjectCollectionToString(addresseeUsers.Select(n => n.Name)),
                        AddressUser = Common.Tools.StringUtils.ObjectCollectionToString(addresseeUsers.Select(n => n.Name), 10),
                        CcUserComplete = Common.Tools.StringUtils.ObjectCollectionToString(addresseeUsers.Select(n => n.Name)),
                        CcUser = Common.Tools.StringUtils.ObjectCollectionToString(addresseeUsers.Select(n => n.Name), 10),
                    };
                    middles.Add(middle);
                }
            }
            //抄送人
            foreach (var userId in request.MissiveCcUserIds)
            {
                var cc = new Cc
                {
                    SourceId = missiveId,
                    UserId = userId,
                    UserName = "",
                    SourceType = GxPress.EnumConst.FolderTypeConst.Missive.GetHashCode()
                };
                ccs.Add(cc);
            }
            //插入
            await _addresseeRepository.InsertAsync(addressees);
            await _ccRepository.InsertAsync(ccs);
            await _middleRepository.InsertAsync(middles);
            //
            var middleModel = await _middleRepository.GetMiddleAsync(Q.Where(nameof(Entity.Middle.Middle.FolderType), GxPress.EnumConst.FolderTypeConst.Missive.GetHashCode()).Where(nameof(Entity.Middle.Middle.MiddleId), missiveId));
            middleModel.AddressUserComplete = Common.Tools.StringUtils.ObjectCollectionToString(addresseeUsers.Select(n => n.Name));
            middleModel.AddressUser = Common.Tools.StringUtils.ObjectCollectionToString(addresseeUsers.Select(n => n.Name), 10);
            middleModel.CcUserComplete = Common.Tools.StringUtils.ObjectCollectionToString(addresseeUsers.Select(n => n.Name));
            middleModel.CcUser = Common.Tools.StringUtils.ObjectCollectionToString(addresseeUsers.Select(n => n.Name), 10);
            await _middleRepository.UpdateAsync(middleModel);
            return true;
        }

        /// <summary>
        /// 根据站内信ID获取详情
        /// </summary>
        /// <param name="missiveId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<MissiveInfoResult> GetMissiveInfoAsync(int missiveId, int userId)
        {
            //修改阅读
            await _addresseeRepository.UpdateAsync(Q.Where(nameof(Entity.Addressee.SourceId), missiveId).Where(nameof(Entity.Addressee.UserId), userId).Set(nameof(Addressee.IsRead), true));
            var result = new MissiveInfoResult
            {
                Items = await GetResult(new List<MissiveInfo>(), missiveId, userId)
            };
            result.Total = result.Items.Count();
            //单回复
            var missiveInfo = result.Items.FirstOrDefault();
            if (missiveInfo == null)
                return result;

            //全部回复
            result.missiveAddressees = new List<MissiveAddresseeUser>();
            result.UserMiddleResults = new List<Result.App.UserMiddle.UserMiddleResult>();
            result.UseCcrMiddleResults = new List<Result.App.UserMiddle.UserMiddleResult>();
            //回复全部
            var userMiddleResult = new Result.App.UserMiddle.UserMiddleResult { MiddleType = 30, SourceId = missiveInfo.UserId, SourceName = missiveInfo.UserName, SourceType = 0, DataSourceId = missiveId };
            //判断是否匿名
            result.UserMiddleResult = new Result.App.UserMiddle.UserMiddleResult();
            result.UserMiddleResults.Add(userMiddleResult);
            foreach (var item in result.Items)
            {
                result.missiveAddressee = new MissiveAddresseeUser();
                result.missiveAddressee.Id = item.UserId;
                result.missiveAddressee.Name = item.UserName;
                result.UserMiddleResult.SourceType = 0;
                result.UserMiddleResult.SourceName = item.UserName;
                if (missiveInfo.MissiveType == 2)
                {
                    if (missiveInfo.UserId != userId)
                    {
                        result.UserMiddleResult.SourceName = "匿名";
                        result.missiveAddressee.Name = "匿名";
                    }

                }
                //全部回复
                var userMiddles = await _userMiddleService.FindUserMiddlesAsync(30, item.Id);
                foreach (var userMiddle in userMiddles)
                {
                    userMiddleResult = new Result.App.UserMiddle.UserMiddleResult { MiddleType = userMiddle.MiddleType, SourceId = userMiddle.SourceId, SourceName = userMiddle.SourceName, SourceType = userMiddle.SourceType, DataSourceId = userMiddle.DataSourceId };
                    result.UserMiddleResults.Add(userMiddleResult);

                }
                //判断是否是匿名
                foreach (var userMiddle in result.UserMiddleResults)
                {
                    if (item.MissiveType == 2)
                    {
                        if (userMiddle.SourceId == item.UserId && item.UserId != userId && userMiddle.SourceType == 0)
                            userMiddle.SourceName = "匿名";
                    }
                }
                //抄送人
                userMiddles = await _userMiddleService.FindUserMiddlesAsync(40, item.Id);
                foreach (var userMiddle in userMiddles)
                {
                    userMiddleResult = new Result.App.UserMiddle.UserMiddleResult { MiddleType = userMiddle.MiddleType, SourceId = userMiddle.SourceId, SourceName = userMiddle.SourceName, SourceType = userMiddle.SourceType, DataSourceId = userMiddle.DataSourceId };
                    result.UseCcrMiddleResults.Add(userMiddleResult);

                }
                break;
            }

            return result;
        }

        /// <summary>
        /// 递归拿出所有被回复的站内信数据
        /// </summary>
        /// <param name="missiveInfoResults"></param>
        /// <param name="missiveId"></param>
        /// <returns></returns>
        public async Task<List<MissiveInfo>> GetResult(List<MissiveInfo> missiveInfoResults, int missiveId, int userId)
        {
            var missive = await _missiveRepository.GetAsync(missiveId);
            if (missive == null)
            {
                throw new Common.Exceptions.BusinessException("站内信已删除");
                //return missiveInfoResults;
            }
            var missiveInfoResult = _mapper.Map<MissiveInfo>(missive);
            //是否可撤回
            if (missive.UserId == userId)
            {
                // var createdDate = Convert.ToDateTime(missive.CreatedDate);
                // if (createdDate.AddMinutes(5) > DateTime.Now)
                missiveInfoResult.IsRecall = true;
            }
            //获取新版
            missiveInfoResult.AddresseeUserMiddles = await _userMiddleService.FindUserMiddlesAsync(30, missiveId);
            missiveInfoResult.CcUserMiddles = await _userMiddleService.FindUserMiddlesAsync(40, missiveId);
            //获取当前站内信类型
            var middle = await _middleRepository.GetMiddleAsync(Q.Where(nameof(Entity.Middle.Middle.MiddleId), missiveId).Where(nameof(Entity.Middle.Middle.FolderType), 5));
            if (middle != null)
                //获取当前的站内信的类型  1 发送 2 草稿
                missiveInfoResult.MissiveSendType = middle.NoticeAddresseeType.GetHashCode();
            //获取当前站内信的用户数据
            var missiveAddressees =
                await _addresseeRepository.GetAllAsync(Q.Where(nameof(Addressee.SourceId), missiveId));
            var users = await _userRepository.FindAllUserAsync(Q.WhereIn(nameof(Entity.User.Id), missiveAddressees.Select(n => n.UserId)));
            missiveInfoResult.AddresseeUsers = users.Select(n => new UserResult { Name = n.Name, Id = n.Id }).ToList();
            //获取当前站内信的抄送人用户数据
            // var missiveCcs =
            //     await _missiveCcRepository.GetAllAsync(Q.Where(nameof(MissiveAddressee.MissiveId), missiveId));
            // users = await _userRepository.FindAllUserAsync(Q.WhereIn(nameof(Entity.User.Id), missiveCcs.Select(n => n.UserId)));
            // missiveInfoResult.CcUsers = users.Select(n => new UserResult { Name = n.Name, Id = n.Id }).ToList();
            //获取已读
            missiveInfoResult.ReadCount = missiveAddressees.Count(n => n.IsRead);
            //总数量
            missiveInfoResult.AllCount = missiveAddressees.Count();
            var analyzeRequest = new Request.App.Analyze.AnalyzeRequest();
            analyzeRequest.TypeValue = 4;
            analyzeRequest.AnalyzeType = 1;
            analyzeRequest.SourceId = missiveId;
            analyzeRequest.UserId = userId;
            //点赞数量
            missiveInfoResult.PraiseCount = await _analyzeService.CountAsync(analyzeRequest);
            //是否点赞
            missiveInfoResult.IsPraise = await _analyzeService.ExistsAsync(analyzeRequest);
            //获取话题的转发数量
            analyzeRequest.AnalyzeType = 4;
            var retransmissionCount = await _analyzeService.CountAsync(analyzeRequest);
            missiveInfoResult.RetransmissionCount = retransmissionCount;
            missiveInfoResult.IsRetransmission = await _analyzeService.ExistsAsync(analyzeRequest);
            //获取话题的收藏数量
            analyzeRequest.AnalyzeType = 3;
            var collectCount = await _analyzeService.CountAsync(analyzeRequest);
            missiveInfoResult.CollectCount = collectCount;
            //是否收藏
            missiveInfoResult.IsCollect = await _analyzeService.ExistsAsync(analyzeRequest);
            //发件人姓名
            if (missiveInfoResult.MissiveType == 1)
            {
                var user = await _userRepository.GetAsync(missiveInfoResult.UserId);
                missiveInfoResult.SendName = user == null ? "" : user.Name;
            }
            else
            {
                if (missiveInfoResult.UserId == userId)
                {
                    var user = await _userRepository.GetAsync(missiveInfoResult.UserId);
                    missiveInfoResult.SendName = user == null ? "" : user.Name;
                }
                else
                    missiveInfoResult.SendName = "匿名";
            }
            //
            missiveInfoResult.IsAdmin = missive.UserId == userId;
            missiveInfoResult.Data = JsonConvert.DeserializeObject<List<ContentJsonData>>(missiveInfoResult.Content);
            foreach (var item in missiveInfoResult.Data)
                item.File = StringUtils.AddDomain(item.File);
            missiveInfoResults.Add(missiveInfoResult);
            if (missive.ParentId == 0)
                return missiveInfoResults;
            return await GetResult(missiveInfoResults, missive.ParentId, userId);
        }


        /// <summary>
        /// 获取站内信
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PagedList<MissiveSearchResult>> GetMissiveSearchResultAsync(MissiveSearchRequest request)
        {
            var result = await _missiveRepository.GetMissiveSearchResultAsync(request);
            foreach (var item in result.Items)
            {
                //获取已读
                // var missiveAddressees = await _missiveAddresseeRepository.GetAllAsync(Q.Where(nameof(MissiveAddressee.MissiveId), item.MiddleId));
                // var users = await _userRepository.FindAllUserAsync(Q.WhereIn(nameof(Entity.User.Id), missiveAddressees.Select(n => n.UserId)));
                // item.AddresseeUsers = users.Select(n => new UserResult { Id = n.Id, Name = n.Name }).ToList();
                //var userMiddles = await _userMiddleService.FindUserMiddlesAsync(30, item.MiddleId);
                //item.EnjoyUser = StringUtils.ObjectCollectionToString(userMiddles.Select(n => n.SourceName).ToList(), "、");
                if (item.IsDelete == true)
                    item.MissiveStatus = 0;
                else if (item.NoticeAddresseeType == NoticeTypeConst.Draft)
                    item.MissiveStatus = 2;
                else
                    item.MissiveStatus = 1;
                if (!string.IsNullOrWhiteSpace(item.Title))
                    continue;
                var data = JsonConvert.DeserializeObject<List<ContentJsonData>>(item.Content);
                if (data.Count > 0)
                {
                    var first = data.First();
                    if (first.TypeValue == 1 && !string.IsNullOrWhiteSpace(first.Text))
                    {
                        if (!string.IsNullOrWhiteSpace(first.Text))
                            item.Title = first.Text;
                    }
                    else
                    {

                        foreach (var contentJsonData in data)
                        {
                            //是否是文本
                            if (contentJsonData.TypeValue == OldTextEditorTypeConst.Text.GetHashCode())
                                continue;
                            else if (contentJsonData.TypeValue == OldTextEditorTypeConst.Image.GetHashCode())
                            {
                                item.Title = "[图片]";
                                break;
                            }
                            else if (contentJsonData.TypeValue == OldTextEditorTypeConst.File.GetHashCode())
                            {
                                item.Title = "[附件]";
                                break;
                            }
                            else
                            {
                                item.Title = "[附件]";
                                break;
                            }
                        }
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 获取站内信详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<MissiveDetailResult> GetMissiveDetailAsync(int id)
        {
            var missive = await _missiveRepository.GetAsync(id);
            var result = _mapper.Map<MissiveDetailResult>(missive);
            result.Items = await GetResult(new List<MissiveInfo>(), id, missive.UserId);
            for (int i = 0; i < result.Items.Count; i++)
            {
                if (result.Items[i].Id == id)
                {
                    result.Items.Remove(result.Items[i]);
                    break;
                }
            }
            //获取抄送人
            var missiveCcs = await _ccRepository.GetNoticeCcByNoticeIdAsync(id, GxPress.EnumConst.FolderTypeConst.Missive.GetHashCode());
            var missiveCcList = new List<MissiveCcUser>();
            foreach (var missiveCc in missiveCcs)
                missiveCcList.Add(new MissiveCcUser { Id = missiveCc.UserId, Name = missiveCc.UserName });
            //获取收件人
            var missiveAddresseeList = new List<MissiveAddresseeUser>();
            var missiveAddresss = await _addresseeRepository.GetAllAsync(Q.Where(nameof(Addressee.SourceId), id));
            foreach (var missiveAddress in missiveAddresss)
                missiveAddresseeList.Add(new MissiveAddresseeUser { Id = missiveAddress.UserId, Name = missiveAddress.UserName });
            result.Data = JsonConvert.DeserializeObject<List<ContentJsonData>>(result.Content);
            foreach (var item in result.Data)
                item.File = StringUtils.AddDomain(item.File);
            //收集人
            result.MissiveAddresseeUsers = missiveAddresseeList;
            //抄送人
            result.MissiveCcUsers = missiveCcList;
            //获取新版
            result.AddresseeUserMiddles = await _userMiddleService.FindUserMiddlesAsync(30, id);
            result.CcUserMiddles = await _userMiddleService.FindUserMiddlesAsync(40, id);
            return result;
        }

        /// <summary>
        /// 获取站内信已读未读数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<IEnumerable<MissiveReadListResult>> GetMissiveReadListAsync(MissiveReadListRequest request)
        {
            return await _addresseeRepository.GetMissiveReadListAsync(request);
        }
    }
}
