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

namespace Hotline.Application.Handlers.CallCenter.Transient
{
    [Injection(EventHandlerType = EEventHandlerType.CallCenter, Label = AppDefaults.CallCenterType.XunShi)]
    public class TransientOuterNotificationHandler : INotificationHandler<TransientOuterNotification>
    {
        private readonly ICallRepository _callRepository;
        private readonly ICallDetailRepository _callDetailRepository;
        private readonly IUserCacheManager _userCacheManager;
        public TransientOuterNotificationHandler(ICallRepository callRepository, ICallDetailRepository callDetailRepository, IUserCacheManager userCacheManager)
        {
            _callRepository = callRepository;
            _callDetailRepository = callDetailRepository;
            _userCacheManager = userCacheManager;
        }
        public async Task Handle(TransientOuterNotification notification, CancellationToken cancellationToken)
        {
            if (!string.IsNullOrEmpty(notification.Outer.Id))
            {
                var workModel = _userCacheManager.GetWorkByTel(notification.Outer.From);
                var isp = PhoneIspTool.GetPhoneIsp(notification.Outer.To);
                var callModel = new Call()
                {
                    CallStatus = ECallStatus.ExtOuterReady,
                    CallDirection = ECallDirection.Out,
                    CallType = ECallType.ExtToOuter,
                    ConversationId = notification.Outer.Id,
                    FromNo = notification.Outer.From,
                    ToNo = notification.Outer.To,
                    Trunk = notification.Outer.Trunk,
                    UserId = workModel.UserId,
                    UserName = workModel.UserName,
                    PhoneIsp = isp
                };
                callModel.Modified();
                var callId = await _callRepository.AddAsync(callModel, cancellationToken);
                //写入明细
                var detail = new CallDetail()
                {
                    CallId = callId,
                    CallStatus = ECallStatus.ExtOuterReady,
                    ConversationId = notification.Outer.Id,
                    OMCallId = notification.Outer.CallId,
                    EventName = "ExtOuterReady", //去电
                    FromNo = notification.Outer.From,
                    ToNo = notification.Outer.To,
                };
                await _callDetailRepository.AddAsync(detail, cancellationToken);
            }
        }
    }
}
