using Hotline.CallCenter.Calls;
using Hotline.CallCenter.Tels;
using Hotline.Repository.SqlSugar.DataPermissions;
using SqlSugar;
using XF.Domain.Dependency;

namespace Hotline.Repository.SqlSugar.CallCenter
{
    public class TelHoldRepository : BaseRepository<TelHold>, ITelHoldRepository, IScopeDependency
    {
        public TelHoldRepository(ISugarUnitOfWork<HotlineDbContext> uow, IDataPermissionFilterBuilder dataPermissionFilterBuilder, IServiceProvider serviceProvider) : base(uow, dataPermissionFilterBuilder, serviceProvider)
        {
        }

        /// <summary>
        /// 通话是否保持
        /// </summary>
        /// <param name="telId"></param>
        /// <param name="userId"></param>
        /// <param name="callId"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<bool> IsHoldingAsync(string telId, string userId, string callId, CancellationToken cancellationToken)
        {
            return Db.Queryable<TelHold>().AnyAsync(x => x.TelId == telId && x.UserId == userId && x.CallId == callId && !x.EndTime.HasValue);
        }

        /// <summary>
        /// 处理Hold时间计算
        /// </summary>
        /// <param name="callId"></param>
        /// <param name="endTime"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task HandleHoldTime(string callId, string endTime, CancellationToken cancellationToken)
        {
            var model = await Db.Queryable<Call>().FirstAsync(x => x.Id == callId);
            if (model!=null)
            {
                var list = await Db.Queryable<TelHold>().Where(x => x.CallId == callId && !x.EndTime.HasValue).ToListAsync();
                if (list.Any())
                {
                    foreach (var item in list)
                    {
                        item.EndHold();
                        Db.Updateable<TelHold>(item);
                    }
                }
                var duration = await Db.Queryable<TelHold>().Where(x => x.CallId == callId).SumAsync(x=>x.HoldDuration);
                model.HoldDuration = Convert.ToInt32(duration);
                Db.Updateable<Call>(model);
            }
        }
    }
}
