using System;
using System.Threading.Tasks;
using System.Transactions;
using GxPress.Common.Exceptions;
using GxPress.Entity;
using GxPress.Request.App.Middle;
using GxPress.Request.Notice;
using GxPress.EnumConst;
using System.Linq;
using System.Collections.Generic;
using Datory;

namespace GxPress.Service.Implement.Notice
{
    public partial class NoticeService
    {
        public async Task<bool> InsertAsync(NoticeInRequest request)
        {
            if (string.IsNullOrEmpty(request.Content))
                throw new BusinessException("内容必填");
            if ((request.AddresseeUserMiddles.Count == 0 && request.NoticeType == NoticeTypeConst.Send))
                throw new BusinessException("收件人未选择");
            try
            {
                using (TransactionScope transactionScope = new TransactionScope())
                {
                    var userEntity = await _userRepository.GetAsync(request.UserId);
                    if (userEntity == null)
                        throw new BusinessException("用户不存在");
                    var noticeId = 0;
                    if (request.Id == 0)
                    {
                        noticeId = await _noticeRepository.InsertAsync(request);
                        var middleInsertTypes = new MiddleInsertTypeRequest
                        {
                            FolderId = 0,
                            MiddleId = noticeId,
                            FolderType = 1,
                            UserId = request.UserId,
                            MiddleSonId = 0,
                            NoticeAddresseeType = request.NoticeType,
                            AttributeValue = 1,
                            IsAdmin = true
                        };
                        middleInsertTypes.FolderId = request.FolderId;
                        //添加自己
                        await _middleService.InsertAsync(middleInsertTypes);
                    }
                    else
                    {
                        noticeId = request.Id;
                        var notice = await _noticeRepository.GetAsync(noticeId);
                        notice.NoticeType = request.NoticeType;
                        notice.Content = request.Content;
                        notice.Title = request.Title;
                        notice.HtmlContent = request.HtmlContent;
                        notice.SourceId = request.SoureId;
                        await _noticeRepository.UpdateNoticeAsync(notice);
                        //删除middle
                        await _middleRepository.DeleteAsync(Q.Where(nameof(Entity.Middle.Middle.MiddleId), noticeId).Where(nameof(Entity.Middle.Middle.FolderType), 1).Where(nameof(Entity.Middle.Middle.IsAdmin), false));
                        //删除收件人
                        await _noticeAddresseeRepository.DeleteAsync(noticeId);
                        //删除抄送人
                        await _noticeCcRepository.DeleteAsync(noticeId);
                        //删除userMiddle
                        await _userMiddleService.DeleteAsync(noticeId,10);
                        await _userMiddleService.DeleteAsync(noticeId,20);
                    }
                    //判断是不是新版通知
                    if (request.AddresseeUserMiddles.Count > 0)
                    {
                        //删除收件人
                        await _userMiddleService.DeleteAsync(request.Id, 10);
                        foreach (var item in request.AddresseeUserMiddles)
                        {
                            item.DataSourceId = noticeId;
                            item.MiddleType = 10;
                        }
                        await _userMiddleService.AddUserMiddleAsync(request.AddresseeUserMiddles);
                        //获取用户
                        var users = await _userMiddleService.FindUsersAsync(request.AddresseeUserMiddles, request.UserId);
                        request.NoticeAddresseeUserIds = users.Select(n => n.Id).ToList();
                    }
                    if (request.CcUserMiddles.Count > 0)
                    {
                        //删除抄送人
                        await _userMiddleService.DeleteAsync(request.Id, 20);
                        foreach (var item in request.CcUserMiddles)
                        {
                            item.DataSourceId = noticeId;
                            item.MiddleType = 20;
                        }
                        await _userMiddleService.AddUserMiddleAsync(request.CcUserMiddles);
                        var users = await _userMiddleService.FindUsersAsync(request.CcUserMiddles, request.UserId);
                        request.NoticeCcUserIds = users.Select(n => n.Id).ToList();
                        //添加抄送人
                        request.NoticeAddresseeUserIds.AddRange(request.NoticeCcUserIds);
                    }

                    //创建人
                    var noticeAddresseeEntity = new NoticeAddressee
                    {
                        NoticeId = noticeId,
                        UserId = request.UserId,
                        UserName = userEntity.Name,
                        IsAdmin = true,
                        NoticeAddresseeType = request.NoticeType,
                        IsTop = false,
                        IsRead = true
                    };
                    var noticeAddresseeId = await _noticeAddresseeRepository.InsertAsync(noticeAddresseeEntity);
                    request.NoticeAddresseeUserIds = request.NoticeAddresseeUserIds.Distinct().ToList();
                    request.NoticeAddresseeUserIds.AddRange(request.NoticeCcUserIds);
                    //通知收件人
                    var noticeAddressees = new List<NoticeAddressee>();
                    //中间件
                    var middles = new List<Entity.Middle.Middle>();
                    //抄送人
                    var noticeCcs = new List<NoticeCc>();
                    //收件人
                    if (request.NoticeType == NoticeTypeConst.Send)
                    {
                        foreach (var noticeAddresseeUserId in request.NoticeAddresseeUserIds.Distinct().ToList())
                        {
                            if (noticeAddresseeUserId == request.UserId)
                                continue;
                            var noticeAddressee = new NoticeAddressee
                            {
                                NoticeId = noticeId,
                                UserId = noticeAddresseeUserId,
                                NoticeAddresseeType = request.NoticeType,
                                IsRead = false
                            };
                            noticeAddressees.Add(noticeAddressee);
                        }
                    }
                    request.NoticeCcUserIds = request.NoticeCcUserIds.Distinct().ToList();
                    if (request.NoticeType == NoticeTypeConst.Send)
                    {
                        //抄送
                        foreach (var noticeCcUserId in request.NoticeCcUserIds)
                        {
                            if (noticeCcUserId == 0)
                                continue;
                            var noticeCc = new NoticeCc
                            {
                                UserId = noticeCcUserId,
                                NoticeId = noticeId,
                                NoticeCcType = request.NoticeType
                            };
                            noticeCcs.Add(noticeCc);
                        }
                    }
                    //添加收件人
                    await _noticeAddresseeRepository.InsertAsync(noticeAddressees);
                    //添加草送人
                    await _noticeCcRepository.InsertAsync(noticeCcs);
                    //查询添加的收件人
                    var noticeAddresseelist = await _noticeAddresseeRepository.GetAllAsync(Q.Where(nameof(Entity.NoticeAddressee.NoticeId), noticeId));
                    if (request.NoticeType == NoticeTypeConst.Send)
                    {
                        foreach (var item in noticeAddresseelist)
                        {
                            if (item.UserId == request.UserId)
                                continue;
                            var middle = new Entity.Middle.Middle
                            {
                                MiddleId = noticeId,
                                FolderType = 1,
                                IsTop = false,
                                AttributeValue = 1,
                                ParentId = 0,
                                UserId = item.UserId,
                                MiddleSonId = item.Id,
                                IsAdmin = false,
                                NoticeAddresseeType = request.NoticeType,
                                IsRead = false
                            };
                            middles.Add(middle);
                        }
                    }

                    //添加文件
                    if (request.NoticeType == NoticeTypeConst.Send)
                        //添加收件人
                        await _middleRepository.InsertAsync(middles);
                    transactionScope.Complete();
                }
            }

            catch (Exception e)
            {
                throw new BusinessException(e.Message);
            }
            return true;
        }
    }
}
