using DotNetCore.CAP;
using Hotline.Orders;
using Hotline.Push;
using Hotline.Push.Notifies;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Dtos.Push;
using Hotline.Share.Enums.Push;
using Hotline.Share.Mq;
using Hotline.Users;
using MediatR;
using Microsoft.AspNetCore.Http;
using StackExchange.Redis;
using XF.Domain.Dependency;
using XF.Domain.Repository;

namespace Hotline.Application.Subscribers
{
    public class InternalCapSubscriber: ICapSubscribe, ITransientDependency
    {
        private readonly IOrderRepository _orderRepository;
        private readonly IMediator _mediator;
        private readonly IRepository<User> _userRepository;
        private readonly ICapPublisher _capPublisher;
        private readonly IRepository<BatchSmsTask> _batchSmsTaskRepository;

        public InternalCapSubscriber(IOrderRepository orderRepository,IMediator mediator,IRepository<User> userRepository,ICapPublisher capPublisher,IRepository<BatchSmsTask> batchSmsTaskRepository)
        {
            _orderRepository = orderRepository;
            _mediator = mediator;
            _userRepository = userRepository;
            _capPublisher = capPublisher;
            _batchSmsTaskRepository = batchSmsTaskRepository;
        }

        /// <summary>
        /// 工单即将超期短信发送（延迟消息）
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(EventNames.HotlineOrderNearlyExpiredTimeSms)]
        public async Task SendOrderNearlyExpiredTimeSms(PublishNearlyExpiredTimeSmsDto dto,CancellationToken cancellationToken)
        {
            var order = await _orderRepository.GetAsync(dto.OrderId, cancellationToken);
            if (order!=null && order.Status< Share.Enums.Order.EOrderStatus.Filed && order.NearlyExpiredTime?.ToString("yyyy-MM-dd hh:mm") == DateTime.Now.ToString("yyyy-MM-dd hh:mm"))
            {
                //当前办理人不为空发短信给个人
                if (!string.IsNullOrEmpty(order.CurrentHandlerId))
                {
                    //查询人员
                    var user = await _userRepository.GetAsync(order.CurrentHandlerId, cancellationToken);
                    if(user!=null && !string.IsNullOrEmpty(user.PhoneNo))
                    {
                        //发送短信
                        var messageDto = new Share.Dtos.Push.MessageDto
                        {
                            PushBusiness = EPushBusiness.OrderUrge,
                            ExternalId = order.Id,
                            OrderId = order.Id,
                            PushPlatform = EPushPlatform.Sms,
                            Remark = order.Title,
                            Name = user.Name,
                            TemplateCode = "1001",
                            Params = new List<string>() { order.No },
                            TelNumber = user.PhoneNo,
                        };
                        await _mediator.Publish(new PushMessageNotify(messageDto), cancellationToken);
                    }
                }
                //当前办理部门不为空，发短信给部门经办人
                else if(!string.IsNullOrEmpty(order.CurrentHandleOrgId))
                {
                    //查询部门经办人
                    var userlist = await _userRepository.Queryable().Where(x =>
                        x.OrgId == order.CurrentHandleOrgId && !string.IsNullOrEmpty(x.PhoneNo) &&
                        x.Roles.Any(d => d.Id == "08dae71e-0eca-4bc4-89fe-7eaefae8a98e")).ToListAsync();
                    foreach (var user in userlist)
                    {
                        if (!string.IsNullOrEmpty(user.PhoneNo))
                        {
                            //发送短信
                            var messageDto = new Share.Dtos.Push.MessageDto
                            {
                                PushBusiness = EPushBusiness.OrderUrge,
                                ExternalId = order.Id,
                                OrderId = order.Id,
                                PushPlatform = EPushPlatform.Sms,
                                Remark = order.Title,
                                Name = user.Name,
                                TemplateCode = "1001",
                                Params = new List<string>() { order.No },
                                TelNumber = user.PhoneNo,
                            };
                            await _mediator.Publish(new PushMessageNotify(messageDto), cancellationToken);
                        }
                    }
                }
                //TODO发送短信超期
                //_capPublisher.PublishDelay(order.ExpiredTime.Value- DateTime.Now, EventNames.HotlineOrderExpiredTimeSms, new PublishNearlyExpiredTimeSmsDto() { OrderId = order.Id });
            }
        }

        /// <summary>
        /// 工单超期短信发送（延迟消息）
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(EventNames.HotlineOrderExpiredTimeSms)]
        public async Task SendOrderExpiredTimeSms(PublishNearlyExpiredTimeSmsDto dto,CancellationToken cancellationToken)
        {
            var order = await _orderRepository.GetAsync(dto.OrderId, cancellationToken);
            if (order != null && order.Status < Share.Enums.Order.EOrderStatus.Filed && order.NearlyExpiredTime?.ToString("yyyy-MM-dd hh:mm") == DateTime.Now.ToString("yyyy-MM-dd hh:mm"))
            {
                //当前办理人不为空发短信给个人
                if (!string.IsNullOrEmpty(order.CurrentHandlerId))
                {
                    //查询人员
                    var user = await _userRepository.GetAsync(order.CurrentHandlerId, cancellationToken);
                    if (user != null && !string.IsNullOrEmpty(user.PhoneNo))
                    {
                        //发送短信
                        var messageDto = new Share.Dtos.Push.MessageDto
                        {
                            PushBusiness = EPushBusiness.OrderUrge,
                            ExternalId = order.Id,
                            OrderId = order.Id,
                            PushPlatform = EPushPlatform.Sms,
                            Remark = order.Title,
                            Name = user.Name,
                            TemplateCode = "1009",
                            Params = new List<string>() { order.No },
                            TelNumber = user.PhoneNo,
                        };
                        await _mediator.Publish(new PushMessageNotify(messageDto), cancellationToken);
                    }
                }
                //当前办理部门不为空，发短信给部门经办人
                else if (!string.IsNullOrEmpty(order.CurrentHandleOrgId))
                {
                    //查询部门经办人
                    var userlist = await _userRepository.Queryable().Where(x =>
                        x.OrgId == order.CurrentHandleOrgId && !string.IsNullOrEmpty(x.PhoneNo) &&
                        x.Roles.Any(d => d.Id == "08dae71e-0eca-4bc4-89fe-7eaefae8a98e")).ToListAsync();
                    foreach (var user in userlist)
                    {
                        if (!string.IsNullOrEmpty(user.PhoneNo))
                        {
                            //发送短信
                            var messageDto = new Share.Dtos.Push.MessageDto
                            {
                                PushBusiness = EPushBusiness.OrderUrge,
                                ExternalId = order.Id,
                                OrderId = order.Id,
                                PushPlatform = EPushPlatform.Sms,
                                Remark = order.Title,
                                Name = user.Name,
                                TemplateCode = "1009",
                                Params = new List<string>() { order.No },
                                TelNumber = user.PhoneNo,
                            };
                            await _mediator.Publish(new PushMessageNotify(messageDto), cancellationToken);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 批量发送短信（延迟消息）
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [CapSubscribe(EventNames.HotlineBatchSmsTask)]
        public async Task SendBatchSmsTask(PublishBatchSmsTaskDto dto,CancellationToken cancellationToken)
        {
            var task = await _batchSmsTaskRepository.Queryable()
                .Includes(x=>x.BatchSmsTaskDetails)
                .Where(x=> x.Id == dto.TaskId).FirstAsync();
            if (task != null && task.SmsTaskState == ESmsTaskState.WaitDo && task.PlanSendTime.ToString("yyyy-MM-dd hh:mm") == DateTime.Now.ToString("yyyy-MM-dd hh:mm"))
            {
                foreach (var item in task.BatchSmsTaskDetails)
                {
                    //发送短信
                    var messageDto = new Share.Dtos.Push.MessageDto
                    {
                        PushBusiness = EPushBusiness.BatchSms,
                        PushPlatform = EPushPlatform.Sms,
                        Name = item.Name,
                        TelNumber = item.PhoneNum,
                        Content = task.Content
                    };
                    await _mediator.Publish(new PushMessageNotify(messageDto), cancellationToken);
                }
            }
        }
    }
}
