using Hotline.Api.Realtimes;
using Hotline.Application.Jobs;
using Hotline.Caching.Interfaces;
using Hotline.CallCenter.Calls;
using Hotline.Orders;
using Hotline.Realtimes;
using Hotline.Settings;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Tr.Sdk;
using XF.Domain.Repository;

namespace Hotline.Api.Controllers
{
    public class CorsJobController: BaseController
    {
        private readonly IOrderDomainService _orderDomainService;
        private readonly IRepository<TrCallRecord> _trcallrecordRepoository;
        private readonly IRealtimeService _realtimeService;
        private readonly ISystemSettingCacheManager _systemSettingCacheManager;
        private readonly ITrClient _trClient;
        private readonly ILogger<CorsJobController> _logger;

        public CorsJobController(IOrderDomainService orderDomainService, IRepository<TrCallRecord> trcallrecordRepoository, IRealtimeService realtimeService, ISystemSettingCacheManager systemSettingCacheManager, ITrClient trClient, ILogger<CorsJobController> logger)
        {
            _orderDomainService = orderDomainService;
            _trcallrecordRepoository = trcallrecordRepoository;
            _realtimeService = realtimeService;
            _systemSettingCacheManager = systemSettingCacheManager;
            _trClient = trClient;
        }

        /// <summary>
        /// 定时发送超期短信
        /// 0 30 09,14 * * ?
        /// </summary>
        /// <returns></returns>
        [HttpPost("send-overtime-sms")]
        [AllowAnonymous]
        public async Task SendOverTimeSms()
        {
            await _orderDomainService.SendOverTimeSms(HttpContext.RequestAborted);
        }

        /// <summary>
        /// 推送当天等待（1分钟一次）
        /// 0 0/1 * * * ?
        /// </summary>
        /// <returns></returns>
        [HttpPost("send-todaywaitnum")]
        [AllowAnonymous]
        public async Task SendToDayWaitNum()
        {
            try
            {
                int count = await _trcallrecordRepoository.Queryable()
                    .Where(x => x.CreatedTime.Date == DateTime.Now.Date)
                    .Where(x => x.QueueTims > 0 && x.Duration == 0)
                    .CountAsync();
                await _realtimeService.TodayWaitNumAsync(count, HttpContext.RequestAborted);
            }
            catch { }
        }

        /// <summary>
        /// 推送当前排队数（5秒一次）
        /// 0/5 * * * * ?
        /// </summary>
        /// <returns></returns>
        [HttpPost("send-currentwaitnum")]
        [AllowAnonymous]
        public async Task SendCurrentWaitNum()
        {
            var callinQueueIds = _systemSettingCacheManager.GetSetting(SettingConstants.CallInQueueId)?.SettingValue.ToList();
            try
            {
                int count = 0;
                foreach (var id in callinQueueIds)
                {
                    var rsp = await _trClient.QueryQueueWaitNumAsync(new Tr.Sdk.Tels.QueryQueueWaitNumRequest() { QueueId = id }, HttpContext.RequestAborted);
                    count += Convert.ToInt32(rsp.Count);
                }

                await _realtimeService.CurrentWaitNumAsync(count, HttpContext.RequestAborted);
            }
            catch(Exception ex) {
                _logger.LogError(ex.Message);
            }
        }
    }
}
