using Hotline.Ai.Visit;
using Hotline.Share.Dtos.Ai;
using SqlSugar;
using XF.Domain.Dependency;
using XF.Domain.Repository;

namespace Hotline.Application.OrderApp
{
    public class AiOrderVisitApplication : IAiOrderVisitApplication, IScopeDependency
    {
        private readonly IRepository<AiOrderVisit> _aiOrderVisitRepository;
        private readonly IRepository<AiOrderVisitDetail> _aiOrderVisitDetailRepository;

        public AiOrderVisitApplication(IRepository<AiOrderVisit> aiOrderVisitRepository, IRepository<AiOrderVisitDetail> aiOrderVisitDetailRepository)
        {
            _aiOrderVisitRepository = aiOrderVisitRepository;
            _aiOrderVisitDetailRepository = aiOrderVisitDetailRepository;

        }
        public ISugarQueryable<AiOrderVisit> QuerysAiOrderVisit(AiVisitListDto dto)
        {
            return _aiOrderVisitRepository.Queryable()
                .Includes(x=>x.AiOrderVisitDetails)
                .WhereIF(!string.IsNullOrEmpty(dto.No),x=>x.AiOrderVisitDetails.Any(d=>d.Order.No.Contains(dto.No)))
                .WhereIF(!string.IsNullOrEmpty(dto.Keyword), x => x.Name.Contains(dto.Keyword))
                .WhereIF(dto.AiOrderVisitTaskState != null, x => x.TaskState == dto.AiOrderVisitTaskState)
                .WhereIF(dto.StartTime.HasValue, x => x.CreationTime >= dto.StartTime)
                .WhereIF(dto.EndTime.HasValue, x => x.CreationTime <= dto.EndTime)
                .WhereIF(dto.AiVisitTimeBeginStart.HasValue,x=>x.BeginTime>= dto.AiVisitTimeBeginStart)
                .WhereIF(dto.AiVisitTimeBeginEnd.HasValue,x=>x.BeginTime<= dto.AiVisitTimeBeginEnd)
                .WhereIF(dto.AiVisitTimeEndStart.HasValue,x=>x.EndTime>= dto.AiVisitTimeEndStart)
                .WhereIF(dto.AiVisitTimeEndEnd.HasValue,x=>x.EndTime<= dto.AiVisitTimeEndEnd)
                .OrderByDescending(x => x.CreationTime);
        }

        public ISugarQueryable<AiOrderVisitDetail> QueryAiOrderVisitDetail(AiVisitDetailListDto dto)
        {
            return _aiOrderVisitDetailRepository.Queryable()
                //.Includes(x => x.OrderVisit, x => x.OrderVisitDetails)
                .Includes(x => x.Order)
                .Where(x => x.AiOrderVisitId == dto.Id)
                .WhereIF(dto.AiOrderVisitState.HasValue, x => x.AiOrderVisitState == dto.AiOrderVisitState)
                .WhereIF(!string.IsNullOrEmpty(dto.Keyword), x => x.Order.No.Contains(dto.Keyword) || x.Order.Title.Contains(dto.Keyword))
                .OrderByDescending(x => x.CreationTime);
        }
    }
}
