using Hotline.CallCenter.Calls;
using Hotline.CallCenter.Tels;
using Hotline.Realtimes;
using Hotline.Share.Enums.CallCenter;
using Hotline.Users;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Tr.Sdk;
using XF.Domain.Cache;
using XF.Domain.Dependency;
using XF.Domain.Repository;

namespace Hotline.Application.CallCenter.Calls
{
    public class TelsStatusRefreshService : BackgroundService, IIgnoreDependency
    {
        private readonly IServiceScopeFactory _serviceScopeFactory;
        public TelsStatusRefreshService(IServiceScopeFactory serviceScopeFactory)
        {
            _serviceScopeFactory = serviceScopeFactory;
        }


        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            using var scope = _serviceScopeFactory.CreateScope();
            var realtimeService = scope.ServiceProvider.GetRequiredService<IRealtimeService>();
            var _trClient = scope.ServiceProvider.GetRequiredService<ITrClient>();
            var _workRepository = scope.ServiceProvider.GetRequiredService<IRepository<Work>>();
            var _telRestRepository = scope.ServiceProvider.GetRequiredService<IRepository<TelRest>>();
            var _cacheWork = scope.ServiceProvider.GetRequiredService<ITypedCache<Work>>();
            var _telActionRecordRepository = scope.ServiceProvider.GetRequiredService<IRepository<TelActionRecord>>();
            int times = 300000;
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    //var list = await _workRepository.Queryable().Where(x => !x.EndTime.HasValue).ToListAsync();
                    var list = await _workRepository.Queryable().Where(x => 1 == 1 && !x.EndTime.HasValue).ToListAsync();
                    //var list = await _workRepository.Queryable().Where(x => x.EndTime is null).ToListAsync();
                    var tellist = await _trClient.QueryTelStateAsync(new Tr.Sdk.Tels.QueryTelStateRequest { }, stoppingToken);
                    foreach (var item in list)
                    {
                        var telmodel = tellist.AgentList.First(x => x.TelNo == item.TelNo);
                        if (telmodel != null)
                        {
                            if (telmodel.State == "logout")
                            {
                                var telRest = await _telRestRepository.GetAsync(x => x.TelNo == item.TelNo && !x.EndTime.HasValue, stoppingToken);
                                if (telRest is not null)
                                {
                                    telRest.EndRest();
                                    await _telRestRepository.UpdateAsync(telRest, stoppingToken);
                                }

                                item.OffDuty();
                                await _workRepository.UpdateAsync(item, stoppingToken);
                                _cacheWork.Remove(item.GetKey(KeyMode.UserId));
                                _cacheWork.Remove(item.GetKey(KeyMode.TelNo));


                                var listx = await _telActionRecordRepository.Queryable().Where(x => x.TelNo == item.TelNo && !x.EndTime.HasValue).ToListAsync();
                                foreach (var itemx in listx)
                                {
                                    itemx.EndAction();
                                    await _telActionRecordRepository.UpdateAsync(itemx);
                                }


                                //#region 小休状态
                                //var telAction = await _telActionRecordRepository.GetAsync(x => x.TelNo == item.TelNo && x.ActionType == EActionType.TelRest && !x.EndTime.HasValue, stoppingToken);
                                //if (telAction != null)
                                //{
                                //    telAction.EndAction();
                                //    await _telActionRecordRepository.UpdateAsync(telAction);
                                //}
                                //#endregion
                                //#region 话后整理

                                //var telarrangeAction = await _telActionRecordRepository.GetAsync(x => x.TelNo == item.TelNo && x.ActionType == EActionType.CallEndArrange && !x.EndTime.HasValue,stoppingToken);
                                //if (telarrangeAction != null)
                                //{
                                //    telarrangeAction.EndAction();
                                //    await _telActionRecordRepository.UpdateAsync(telarrangeAction);
                                //}

                                //#endregion
                            }
                        }
                    }
                }
                catch
                {

                }
                await Task.Delay(times);
            }
        }
    }
}
