using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotNetCore.CAP;
using Hotline.FlowEngine.Workflows;
using Hotline.Orders;
using Hotline.Orders.Notifications;
using Hotline.Push.FWMessage;
using Hotline.Push.Notifies;
using Hotline.Share.Dtos.Push;
using Hotline.Share.Enums.Push;
using Hotline.Share.Mq;
using Hotline.Share.Tools;
using MediatR;
using XF.Domain.Repository;

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

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

    public async Task Handle(ReceiveMessageNotify notification, CancellationToken cancellationToken)
    {
        if (notification.NotifyDto.Type != "2") return;

        var msg = await _messageRepository
            .Queryable()
            .Where(m => m.TelNumber == notification.NotifyDto.TelNumber)
            .Where(m => m.PushBusiness == EPushBusiness.VisitSms)
            .Where(m => m.SendState == ESendState.Success)
            .OrderByDescending(m => m.CreationTime)
            .FirstAsync();
        if (msg.SendTime!.Value.AddDays(2) < DateTime.Now) return;
        await _orderVisitDomainService.UpdateSmsReplyAsync(notification.NotifyDto);
    }
}

public class OrderVisitSmsDelay : ICapSubscribe
{
    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);
    }
}
