using Hotline.CallCenter.Calls;
using Hotline.Repository.SqlSugar.DataPermissions;
using Hotline.Share.Enums.CallCenter;
using SqlSugar;
using System.Reflection.Metadata.Ecma335;
using XF.Domain.Dependency;

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

        public async Task<IReadOnlyList<Call>> QueryPartAsync(DateTime datetime)
        {
            return await Db.Queryable<Call>()
                .Includes(d => d.CallDetails)
                //.Where(d => d.CallDetails.Any(x => x.EventName == "BYE") 
                .Where(d => d.CallStatus == ECallStatus.Bye
                            && SqlFunc.Subqueryable<CallDetail>().Where(s => s.CallId == d.Id && s.EventName == "BYE" && s.CreationTime > datetime).Any())
                .OrderBy(d => d.CreationTime)
                .Take(10)
                .ToListAsync();
        }

        public async Task<Call> GetLastLOCall(string cpn, string cdpn)
        {
            return await Db.Queryable<Call>().OrderByDescending(x => x.CreationTime).Where(x => x.FromNo == cpn && x.ToNo == cdpn).FirstAsync();
        }
    }
}
