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;
using Aliyun.Acs.Core.Utils;

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;
                    var middleId = 0;
                    var addresseeUsers = new List<User>();
                    var ccUsers = new List<User>();
                    if (request.Id == 0)
                    {
                        noticeId = await _noticeRepository.InsertAsync(request);
                        var middleInsertTypes = new MiddleInsertTypeRequest
                        {
                            FolderId = request.FolderId,
                            MiddleId = noticeId,
                            FolderType = GxPress.EnumConst.FolderTypeConst.Notice.GetHashCode(),
                            UserId = request.UserId,
                            MiddleSonId = 0,
                            NoticeAddresseeType = request.NoticeType,
                            AttributeValue = 1,
                            Title = _contentJsonService.GetTitile(request.Title, request.Content),
                            IsAdmin = true,
                            TitleLong = request.Title,
                            Content = request.Content,
                        };
                        //添加自己
                        middleId = 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 _addresseeRepository.DeleteAsync(noticeId, GxPress.EnumConst.FolderTypeConst.Notice.GetHashCode(), 2);
                        //删除抄送人
                        await _ccRepository.DeleteAsync(noticeId, GxPress.EnumConst.FolderTypeConst.Notice.GetHashCode());
                        //删除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);
                        //获取用户
                        addresseeUsers = await _userMiddleService.FindUsersAsync(request.AddresseeUserMiddles, request.UserId);
                        request.NoticeAddresseeUserIds = addresseeUsers.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);
                        ccUsers = await _userMiddleService.FindUsersAsync(request.CcUserMiddles, request.UserId);
                        request.NoticeCcUserIds = ccUsers.Select(n => n.Id).ToList();
                        //添加抄送人
                        request.NoticeAddresseeUserIds.AddRange(request.NoticeCcUserIds);
                    }

                    //创建人
                    var addresseeEntity = new Addressee
                    {
                        SourceId = noticeId,
                        UserId = request.UserId,
                        UserName = userEntity.Name,
                        IsAdmin = true,
                        NoticeAddresseeType = request.NoticeType,
                        IsTop = false,
                        IsRead = true,
                        SourceType = GxPress.EnumConst.FolderTypeConst.Notice.GetHashCode()
                    };
                    var noticeAddresseeId = await _addresseeRepository.InsertAsync(addresseeEntity);
                    request.NoticeAddresseeUserIds = request.NoticeAddresseeUserIds.Distinct().ToList();
                    request.NoticeAddresseeUserIds.AddRange(request.NoticeCcUserIds);
                    //通知收件人
                    var addressees = new List<Addressee>();
                    //中间件
                    var middles = new List<Entity.Middle.Middle>();
                    //抄送人
                    var ccs = new List<Cc>();
                    //收件人
                    if (request.NoticeType == NoticeTypeConst.Send)
                    {
                        foreach (var noticeAddresseeUserId in request.NoticeAddresseeUserIds.Distinct().ToList())
                        {
                            if (noticeAddresseeUserId == request.UserId)
                                continue;
                            var noticeAddressee = new Addressee
                            {
                                SourceId = noticeId,
                                UserId = noticeAddresseeUserId,
                                NoticeAddresseeType = request.NoticeType,
                                IsRead = false,
                                SourceType = GxPress.EnumConst.FolderTypeConst.Notice.GetHashCode()
                            };
                            addressees.Add(noticeAddressee);
                        }
                    }
                    request.NoticeCcUserIds = request.NoticeCcUserIds.Distinct().ToList();
                    if (request.NoticeType == NoticeTypeConst.Send)
                    {
                        //抄送
                        foreach (var noticeCcUserId in request.NoticeCcUserIds)
                        {
                            if (noticeCcUserId == 0)
                                continue;
                            var cc = new Cc
                            {
                                UserId = noticeCcUserId,
                                SourceId = noticeId,
                                SourceType = GxPress.EnumConst.FolderTypeConst.Notice.GetHashCode()
                            };
                            ccs.Add(cc);
                        }
                    }
                    //添加收件人
                    await _addresseeRepository.InsertAsync(addressees);
                    //添加草送人
                    await _ccRepository.InsertAsync(ccs);
                    //查询添加的收件人
                    var noticeAddresseelist = await _addresseeRepository.GetAllAsync(Q.Where(nameof(Entity.Addressee.SourceId), 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 = GxPress.EnumConst.FolderTypeConst.Notice.GetHashCode(),
                                IsTop = false,
                                AttributeValue = 1,
                                ParentId = 0,
                                UserId = item.UserId,
                                MiddleSonId = item.Id,
                                IsAdmin = false,
                                NoticeAddresseeType = request.NoticeType,
                                Title = _contentJsonService.GetTitile(request.Title, request.Content),
                                IsRead = false,
                                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(ccUsers.Select(n => n.Name)),
                                CcUser = Common.Tools.StringUtils.ObjectCollectionToString(ccUsers.Select(n => n.Name), 10),
                            };
                            middles.Add(middle);
                        }
                    }
                    //修改middler
                    if (middleId > 0)
                    {
                        var middle = await _middleRepository.GetMiddleAsync(middleId);
                        middle.AddressUserComplete = Common.Tools.StringUtils.ObjectCollectionToString(addresseeUsers.Select(n => n.Name));
                        middle.AddressUser = Common.Tools.StringUtils.ObjectCollectionToString(addresseeUsers.Select(n => n.Name), 10);
                        middle.CcUserComplete = Common.Tools.StringUtils.ObjectCollectionToString(addresseeUsers.Select(n => n.Name));
                        middle.CcUser = Common.Tools.StringUtils.ObjectCollectionToString(addresseeUsers.Select(n => n.Name), 10);
                        await _middleRepository.UpdateAsync(middle);
                    }
                    //添加文件
                    if (request.NoticeType == NoticeTypeConst.Send)
                        //添加收件人
                        await _middleRepository.InsertAsync(middles);
                    transactionScope.Complete();
                }
            }

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