using DotNetCore.CAP;
using Hotline.Orders;
using Hotline.Orders.Notifications;
using Hotline.Push.Notifies;
using Hotline.Share.Enums.Push;
using MediatR;
using Microsoft.Extensions.Logging;

namespace Hotline.Application.OrderApp.Handlers.OrderHandler
{
    /// <summary>
    /// 新增工单发送短信
    /// </summary>
    public class AddOrderPushMessageNotifyHandler : INotificationHandler<AddOrderNotify>
    {
        private readonly ICapPublisher _capPublisher;
        private readonly ILogger<AddOrderPushMessageNotifyHandler> _logger;
        private readonly IMediator _mediator;
        private readonly IOrderRepository _orderRepository;

        public AddOrderPushMessageNotifyHandler(ICapPublisher capPublisher,
            ILogger<AddOrderPushMessageNotifyHandler> logger,
            IMediator mediator,
            IOrderRepository orderRepository)
        {
            _capPublisher = capPublisher;
            _logger = logger;
            _mediator = mediator;
            _orderRepository = orderRepository;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="notification"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task Handle(AddOrderNotify notification, CancellationToken cancellationToken)
        {
            try
            {
                if (notification.Order.AcceptSms && !notification.Order.SmsSended)
                {
                    var order = notification.Order;
                    if (order != null && order.AcceptSms)
                    {
                        _logger.LogInformation($"推送短信: orderNo: {order.No}");

                        var messageDto = new Share.Dtos.Push.MessageDto
                        {
                            PushBusiness = EPushBusiness.OrderAccept,
                            ExternalId = order.Id,
                            OrderId = order.Id,
                            PushPlatform = EPushPlatform.Sms,
                            Remark = order.Title,
                            Name = order.FromName,
                            TemplateCode = "1005",
                            Params = new List<string>() { order.No, order.Password },
                            TelNumber = order.Contact,
                        };
                        await _mediator.Publish(new PushMessageNotify(messageDto), cancellationToken);

                        order.SmsSended = true;
                        _orderRepository.Updateable(order).UpdateColumns(p => p.SmsSended).ExecuteCommand();
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogError("新增工单发送短信失败，Error：{err}", e.Message);
            }
        }

    }
}
