using Hotline.Caching.Interfaces;
using Hotline.CallCenter.Calls;
using Hotline.DI;
using Hotline.Realtimes;
using Hotline.Share.Enums.CallCenter;
using Hotline.Share.Notifications.NewRockCallCenter;
using MediatR;

namespace Hotline.Application.Handlers.CallCenter.CallState
{
    [Injection(EventHandlerType = EEventHandlerType.CallCenter, Label = AppDefaults.CallCenterType.XunShi)]
    public class RingVisitorToExtNotificationHandler : INotificationHandler<RingVisitorToExtNotification>
    {
        private readonly ICallRepository _callRepository;
        private readonly ICallDetailRepository _callDetailRepository;
        private readonly IRealtimeService _realtimeService;
        private readonly IUserCacheManager _userCacheManager;

        public RingVisitorToExtNotificationHandler(ICallRepository callRepository, ICallDetailRepository callDetailRepository, IRealtimeService realtimeService, IUserCacheManager userCacheManager)
        {
            _callRepository = callRepository;
            _callDetailRepository = callDetailRepository;
            _realtimeService = realtimeService;
            _userCacheManager = userCacheManager;
        }


        public async Task Handle(RingVisitorToExtNotification notification, CancellationToken cancellationToken)
        {
            var model = await _callRepository.GetAsync(
                x => x.ConversationId == notification.Visitor.Id &&
                     x.FromNo == notification.Visitor.From && x.CreationTime >= DateTime.Now.AddHours(-2), true, x => x.CreationTime, cancellationToken);

            if (model != null)
            {
                model.CallStatus = ECallStatus.Ring;
                model.RingTime = DateTime.Now;
                await _callRepository.UpdateAsync(model, cancellationToken);
                var detail = new CallDetail()
                {
                    CallId = model.Id,
                    CallStatus = ECallStatus.Ring,
                    OMCallId = notification.Visitor.CallId,
                    ConversationId = notification.Visitor.Id,
                    EventName = notification.Attribute,
                    FromNo = notification.Visitor.From,
                    ToNo = notification.Visitor.To
                };
                await _callDetailRepository.AddAsync(detail, cancellationToken);

                //调用业务弹屏 通知前端
                var workModel = _userCacheManager.GetWorkByTel(notification.TelNo);
                if (workModel != null)
                {
                    await _realtimeService.RingAsync(workModel.UserId, new Share.Dtos.Realtime.RingDto() { From = notification.Visitor.From, Id = model.Id, To = notification.TelNo, CallType = ECallType.VisitorCallIn }, cancellationToken);
                }
            }
        }
    }
}
