using DotNetCore.CAP;
using Hotline.Orders;
using Hotline.Push.FWMessage;
using Hotline.Push.Notifies;
using Hotline.Settings;
using Hotline.Share.Dtos.Push;
using Hotline.Share.Enums.Push;
using Hotline.Share.Mq;
using MediatR;
using XF.Domain.Dependency;
using XF.Domain.Repository;

namespace Hotline.Application.OrderApp.Handlers.OrderHandler;
public class OrderVisitSmsHandler : INotificationHandler<ReceiveMessageNotify>
{
    private readonly IOrderVisitDomainService _orderVisitDomainService;
    private readonly IRepository<Message> _messageRepository;
    private readonly ISystemLogRepository _logRepository;

    public OrderVisitSmsHandler(IOrderVisitDomainService orderVisitDomainService, IRepository<Message> messageRepository, ISystemLogRepository logRepository)
    {
        _orderVisitDomainService = orderVisitDomainService;
        _messageRepository = messageRepository;
        _logRepository = logRepository;
    }

    public async Task Handle(ReceiveMessageNotify notification, CancellationToken cancellationToken)
    {
        if (notification.NotifyDto.Type != "2")
        {
            _logRepository.Add("短信回访-不处理", notification, "Type=2才处理,现在Type:" + notification.NotifyDto.Type, "OrderVisitSmsHandler", 0);
            return;
        }

        var msg = await _messageRepository
            .Queryable()
            .Where(m => m.TelNumber == notification.NotifyDto.TelNumber)
            .Where(m => m.PushBusiness == EPushBusiness.VisitSms || m.PushBusiness == EPushBusiness.SearchSms)
            .Where(m => m.SendState == ESendState.Success)
            .OrderByDescending(m => m.CreationTime)
            .FirstAsync(cancellationToken);
        if (msg != null)
        {
            if (msg.SendTime!.Value.AddDays(2) < DateTime.Now)
            {
                _logRepository.Add("短信回访-不处理", notification, "msg.SendTime 已经超过2天, 不处理", "OrderVisitSmsHandler", 0);
                return;
            }
            await _orderVisitDomainService.UpdateSmsReplyAsync(notification.NotifyDto);
        }
    }
}

public class OrderVisitSmsDelay : ICapSubscribe, ITransientDependency
{
    private readonly IOrderVisitDomainService _orderVisitDomainService;

    public OrderVisitSmsDelay(IOrderVisitDomainService orderVisitDomainService)
    {
        _orderVisitDomainService = orderVisitDomainService;
    }

    /// <summary>
    /// 超过48小时未回复短信,修改短信回访记录为默认满意
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [CapSubscribe(EventNames.UpdateVisitDelaySms)]
    public async Task UpdateVisitDelaySms(MessageDto dto)
    {
        await _orderVisitDomainService.UpdateSmsReplyDefaultAsync(dto);
    }
}
