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

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

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

        public async Task Handle(AnsweredExtToOuterNotification notification, CancellationToken cancellationToken)
        {
            var model = await _callRepository.GetAsync(
                x => x.ConversationId == notification.Outer.Id &&
                     x.FromNo == notification.Outer.From && x.ToNo == notification.Outer.To && x.CreationTime >= DateTime.Now.AddHours(-2), true, x => x.CreationTime, cancellationToken);
            if (model != null)
            {
                model.CallStatus = ECallStatus.Answered;
                model.AnsweredTime = DateTime.Now;
                await _callRepository.UpdateAsync(model, cancellationToken);
                var detail = new CallDetail()
                {
                    CallId = model.Id,
                    CallStatus = ECallStatus.Answered,
                    OMCallId = notification.Outer.CallId,
                    ConversationId = notification.Outer.Id,
                    EventName = notification.Attribute,
                    AnswerNo = notification.TelNo,
                    FromNo = notification.Outer.From,
                    ToNo = notification.Outer.To
                };
                await _callDetailRepository.AddAsync(detail, cancellationToken);

                //调用业务通知 通知前端
                var workModel = _userCacheManager.GetWorkByTel(notification.Outer.From);
                if (workModel != null)
                {
                    await _realtimeService.AnsweredAsync(workModel.UserId, new AnsweredDto() { ConversationId = notification.Outer.Id, From = notification.Outer.From, Id = model.Id, To = notification.Outer.To, CallType = ECallType.ExtToOuter }, cancellationToken);
                }
            }
        }
    }
}
