using Hotline.Orders;
using Hotline.Realtimes;
using Hotline.Share.Dtos.Article;
using Hotline.Share.Enums.Article;
using MapsterMapper;
using Microsoft.AspNetCore.Http;
using XF.Domain.Authentications;
using XF.Domain.Dependency;
using XF.Domain.Repository;

namespace Hotline.Article
{
    public class CircularRecordDomainService : ICircularRecordDomainService, IScopeDependency
    {
        private readonly IRepository<CircularRecord> _circularRecordRepository;
        private readonly IRealtimeService _realtimeService;
        private readonly IMapper _mapper;
        private readonly IRepository<Circular> _circularRepository;
        private readonly IRepository<CircularReadGroup> _circularReadGroupRepository;
        private readonly ISessionContext _sessionContext;

        public CircularRecordDomainService(IRepository<CircularRecord> circularRecordRepository, IRealtimeService realtimeService, IMapper mapper, IRepository<Circular> circularRepository, IRepository<CircularReadGroup> circularReadGroupRepository, ISessionContext sessionContext)
        {
            _circularRecordRepository = circularRecordRepository;
            _realtimeService = realtimeService;
            _mapper = mapper;
            _circularRepository = circularRepository;
            _circularReadGroupRepository = circularReadGroupRepository;
            _sessionContext = sessionContext;
        }
        public async Task RecordUserHandle(List<string> userIds, bool isAdd,string title,string sendContent,int count = 1, CancellationToken cancellationToken= default)
        {
            foreach (var item in userIds)
            {
                var userRecord = await _circularRecordRepository.GetAsync(x => x.UserId == item);
                if (isAdd)
                {
                    if (userRecord != null)
                    {
                        userRecord.RecordCount = userRecord.RecordCount + count;
                        await _circularRecordRepository.UpdateAsync(userRecord);
                    }
                    else
                    {
                        userRecord = new CircularRecord();
                        userRecord.UserId = item;
                        userRecord.CircularType = Share.Enums.Article.ECircularType.Person;
                        userRecord.RecordCount = 1;
                        await _circularRecordRepository.AddAsync(userRecord);
                    }
                }
                else
                {
                    if (userRecord != null)
                    {
                        if (userRecord.RecordCount > 0)
                        {
                            userRecord.RecordCount = userRecord.RecordCount - count;
                        }
                        else
                        {
                            userRecord.RecordCount = 0;
                        }
                        await _circularRecordRepository.UpdateAsync(userRecord);
                    }
                }
                try
                {
                    await _realtimeService.CircularRecoordAsync(userRecord.Id,title,sendContent, cancellationToken);
                }
                catch{}
            }
            
        }

        public async Task RecordOrgHandle(List<string> orgIds, bool isAdd,string title, string sendContent, int count =1, CancellationToken cancellationToken = default)
        {
            foreach (var item in orgIds)
            {
                var orgRecord = await _circularRecordRepository.GetAsync(x => x.OrgId == item);
                if (isAdd)
                {
                    if (orgRecord != null)
                    {
                        orgRecord.RecordCount = orgRecord.RecordCount + count;
                        await _circularRecordRepository.UpdateAsync(orgRecord);
                    }
                    else
                    {
                        orgRecord = new CircularRecord();
                        orgRecord.OrgId = item;
                        orgRecord.CircularType = Share.Enums.Article.ECircularType.Org;
                        orgRecord.RecordCount = 1;
                        await _circularRecordRepository.AddAsync(orgRecord);
                    }
                }
                else
                {
                    if (orgRecord != null)
                    {
                        if (orgRecord.RecordCount > 0)
                        {
                            orgRecord.RecordCount = orgRecord.RecordCount - count;
                        }
                        else
                        {
                            orgRecord.RecordCount = 0;
                        }
                        await _circularRecordRepository.UpdateAsync(orgRecord);
                    }
                }
                try
                {
                    await _realtimeService.CircularRecoordAsync(orgRecord.Id, title, sendContent, cancellationToken);
                }
                catch{}
            }
        }

        public async Task AddCircularMessage(AddCircularDto dto, CancellationToken cancellationToken = default)
        {
            var model = _mapper.Map<Circular>(dto);
            model.CommitTime = DateTime.Now;
            model.ExaminTime = DateTime.Now;
            model.ExaminManId = _sessionContext.UserId;
            model.CircularState = ECircularState.ReviewPass;
            model.ExaminOpinion = "内部消息,系统默认通过";
            model.ReadedNum = 0;
            model.NeedReadNum = model.CircularReadGroups.Count;
            model.LostEfficacyTime = DateTime.Now.AddYears(50);
            var id = await _circularRepository.AddAsync(model,cancellationToken);
            //子表
            var list = dto.CircularReadGroups;
            var readGroupList = new List<CircularReadGroup>();
            foreach (var item in list)
            {
                var readGroup = _mapper.Map<CircularReadGroup>(item);
                readGroup.CircularId = id;
                readGroup.IsRead = false;
                readGroupList.Add(readGroup);
            }
            await _circularReadGroupRepository.AddRangeAsync(readGroupList);

            //更新阅读数量
            if (model.CircularType == Share.Enums.Article.ECircularType.Person)
            {
                //个人
                var userlist = await _circularReadGroupRepository.Queryable()
                    .Where(x => x.CircularId == model.Id)
                .Select(x => x.UserId)
                    .ToListAsync();
                if (userlist != null && userlist.Count > 0)
                {
                    await this.RecordUserHandle(userlist, true,model.Title,model.Content);
                }
            }
            else
            {
                //部门
                var orglist = await _circularReadGroupRepository.Queryable()
                    .Where(x => x.CircularId == model.Id)
                .Select(x => x.OrgId)
                    .ToListAsync();
                if (orglist != null && orglist.Count > 0)
                {
                    await this.RecordOrgHandle(orglist, true,model.Title,model.Content);
                }
            }
        }



        /// <summary>
        /// 特提处理通知公告
        /// </summary>
        /// <param name="special"></param>
        /// <param name="order"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task OrderSpecialCircularMessage(OrderSpecial special,Order order,CancellationToken cancellationToken = default) {

			var cMessage = new AddCircularDto
			{
				Title = "信件特提信息",
				Content = $"编号为{order.No}的工单已被特提。",
				CircularTypeId = "1",
				CircularTypeName = "公告通知",
				CircularType = ECircularType.Org,
				IsMustRead = false,
				SourceOrgId = _sessionContext.RequiredOrgId,
				SourceOrgName = _sessionContext.OrgName
			};
			var groups = new CircularReadGroupDto
			{
				OrgId = order.ActualHandleOrgCode,
				OrgName = order.ActualHandleOrgName
			};
			cMessage.CircularReadGroups = new List<CircularReadGroupDto> { groups };

            await AddCircularMessage(cMessage, cancellationToken);
		}

        /// <summary>
        /// 信件退回公告通知
        /// </summary>
        /// <returns></returns>
		public async Task OrderSendBackCircularMessage(string userId,string userName, Order order, CancellationToken cancellationToken = default)
		{

			var cMessage = new AddCircularDto
			{
				Title = "信件退回信息",
				Content = $"工单编码为{order.No}的工单，已被退回，请及时处理！",
				CircularTypeId = "1",
				CircularTypeName = "公告通知",
				CircularType = ECircularType.Person,
				IsMustRead = false,
				SourceOrgId = _sessionContext.RequiredOrgId,
				SourceOrgName = _sessionContext.OrgName
			};
			var groups = new CircularReadGroupDto
			{
				UserId = userId,
				UserName = userName
			};
			cMessage.CircularReadGroups = new List<CircularReadGroupDto> { groups };
			await AddCircularMessage(cMessage, cancellationToken);
		}

	}
}
