using Hotline.Caching.Interfaces;
using Hotline.CallCenter.Devices;
using Hotline.CallCenter.Ivrs;
using Hotline.CallCenter.Tels;
using Hotline.Share.Notifications.NewRockCallCenter;
using MediatR;

namespace Hotline.Application.Handlers.CallCenter.System
{
    public class BootupNotificationHandler : INotificationHandler<BootupNotification>
    {
        private readonly ITelGroupRepository _telGroupRepository;
        private readonly IIvrRepository _ivrRepository;
        private readonly IDeviceManager _deviceManager;
        private readonly IUserCacheManager _userCacheManager;

        public BootupNotificationHandler(ITelGroupRepository telGroupRepository, IDeviceManager deviceManager, IUserCacheManager userCacheManager, IIvrRepository ivrRepository)
        {
            _telGroupRepository = telGroupRepository;
            _deviceManager = deviceManager;
            _userCacheManager = userCacheManager;
            _ivrRepository = ivrRepository;
        }

        public async Task Handle(BootupNotification notification, CancellationToken cancellationToken)
        {
            #region 还原所有分机组配置
            //查询所有分机组
            var list = await _telGroupRepository.QueryExtAsync(d => true, d => d.Includes(x => x.Tels));
            foreach (var groupItem in list)
            {
                List<string> exts = new List<string>();
                foreach (var ext in groupItem.Tels)
                {
                    var iswork = await _userCacheManager.IsWorkingByTelAsync(ext.No, cancellationToken);
                    if (iswork)
                        exts.Add(ext.No);

                }
                //轮循还原设备分机组信息
                await _deviceManager.AssginConfigGroupAsync(groupItem.No, groupItem.Distribution, exts, groupItem.Voice,
                    cancellationToken);
            }

            #endregion

            #region 还原所有语音菜单配置
            //查询所有IVR
            var ivrlist = await _ivrRepository.QueryAsync();
            foreach (var item in ivrlist)
            {
                await _deviceManager.AssginConfigMenuAsync(item.No, item.Voice, item.Repeat.ToString(), item.InfoLength.ToString(), item.Exit, cancellationToken);
            }
            #endregion

            //TODO 有新还原的设置加在后面
        }
    }
}
