using Hotline.Caching.Interfaces;
using Hotline.Settings;
using Hotline.Share.Tools;
using Hotline.Snapshot.Notifications;
using MediatR;
using XF.Domain.Authentications;

namespace Hotline.Application.OrderApp.Handlers.SnapshotHandler
{
    /// <summary>
    /// 需求：坐席派给网格员的安全隐患工单若未推送成功超过4小时或者网格员超过4小时没回复，则自动流转到标注节点待标注列表
    /// </summary>
    public class GuiderSystemTimeoutHandler : INotificationHandler<GuiderSystemTimeOutBackNotification>
    {
        private readonly ISystemSettingCacheManager _systemSettingCacheManager;
        private readonly IOrderApplication _orderApplication;
        private readonly ISystemLogRepository _systemLogRepository;
        private readonly ISessionContext _sessionContext;

        public GuiderSystemTimeoutHandler(
            ISystemSettingCacheManager systemSettingCacheManager,
            IOrderApplication orderApplication
,
            ISystemLogRepository systemLogRepository,
            ISessionContext sessionContext)
        {
            _systemSettingCacheManager = systemSettingCacheManager;
            _orderApplication = orderApplication;
            _systemLogRepository = systemLogRepository;
            _sessionContext = sessionContext;
        }

        /// <summary>Handles a notification</summary>
        /// <param name="notification">The notification</param>
        /// <param name="cancellationToken">Cancellation token</param>
        public async Task Handle(GuiderSystemTimeOutBackNotification notification, CancellationToken cancellationToken)
        {
            try
            {
                if (_systemSettingCacheManager.Snapshot)
                {
                    await _orderApplication.HandleFromWanggeyuanToMaskAsync(notification.OrderId, "超时4小时12345自动退回。", cancellationToken);
                }
            }
            catch (Exception e)
            {
                _systemLogRepository.Add("网格员超时未回复", notification.OrderId, "方法异常", status: 0, executeResult: e.ToJson());
                if (e.Message.StartsWith("网格员节点已办理完"))
                    return;
                else
                    throw;
            }
            _systemLogRepository.Add("网格员超时未回复", notification.OrderId, "收到事件", "", 1);
        }
    }
}
