using Hotline.Caching.Interfaces;
using Hotline.Caching.Services;
using Hotline.CallCenter.Devices;
using Hotline.CallCenter.Tels;
using Hotline.Realtimes;
using Hotline.Repository.SqlSugar.CallCenter;
using Hotline.Share.Enums.CallCenter;
using Hotline.Share.Notifications.NewRockCallCenter;
using MediatR;
using XF.Domain.Cache;
using XF.Domain.Exceptions;

namespace Hotline.Application.Handlers.CallCenter.ExtState
{
    public class IdleNotificationHandler : INotificationHandler<IdleNotification>
    {
        private readonly ITelRepository _telRepository;
        private readonly ITelCacheManager _telCacheManager;
        private readonly ITypedCache<Tel> _typedCache;
        private readonly IUserCacheManager _userCacheManager;
        private readonly IRealtimeService _realtimeService;
        private readonly IDeviceManager _deviceManager;
        private readonly ITelRestRepository _telRestRepository;

        public IdleNotificationHandler(ITelRepository telRepository, ITelCacheManager telCacheManager, ITypedCache<Tel> typedCache,IUserCacheManager userCacheManager,IRealtimeService realtimeService,IDeviceManager deviceManager,ITelRestRepository telRestRepository)
        {
            _telRepository = telRepository;
            _telCacheManager = telCacheManager;
            _typedCache = typedCache;
            _userCacheManager = userCacheManager;
            _realtimeService = realtimeService;
            _deviceManager = deviceManager;
            _telRestRepository = telRestRepository;
        }

        public async Task Handle(IdleNotification notification, CancellationToken cancellationToken)
        {
            var telModel = _telCacheManager.GetTel(notification.TelNo);
            telModel.TelStatus = ETelStatus.Ready;
            //await _telRepository.UpdateAsync(telModel, cancellationToken);
            _typedCache.Set(notification.TelNo, telModel);



            var iswork = await _userCacheManager.IsWorkingByTelAsync(notification.TelNo, cancellationToken);


            if (!iswork)
                throw new UserFriendlyException(notification.TelNo + "未查询到工作记录");


            var workModel = _userCacheManager.GetWorkByTel(notification.TelNo);
            if (workModel != null)
            {
                await _realtimeService.IdleAsync(workModel.UserId, cancellationToken);
            }

            var restingTel = await _telRestRepository.GetAsync(d => d.TelId == telModel.Id && !d.EndTime.HasValue && d.ApplyStatus== ETelRestApplyStatus.Resting, cancellationToken);
            if (restingTel == null)
            {
                foreach (var group in telModel.Groups)
                {
                    await _deviceManager.AssginConfigGroupAsync(group.No, group.Distribution, new List<string>() { notification.TelNo }, group.Voice, cancellationToken);
                }
            }
        }
    }
}
