using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2010.PowerPoint;
using Hotline.Enterprise;
using Hotline.Orders;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Dtos.Users;
using Hotline.Users;
using SqlSugar;
using XF.Domain.Authentications;
using XF.Domain.Dependency;
using XF.Domain.Repository;

namespace Hotline.Application.Enterprise;

public class EnterpriseApplication : IEnterpriseApplication, IScopeDependency
{
    private readonly IRepository<EnterpriseSpecialist> _enterpriseSpecialistRepository;
    private readonly IRepository<User> _userRepository;
    private readonly IRepository<Order> _orderRepository;
    private readonly ISessionContext _sessionContext;

    public EnterpriseApplication(
        IRepository<EnterpriseSpecialist> enterpriseSpecialistRepository,
        IRepository<User> userRepository,
        IRepository<Order> orderRepository,
        ISessionContext sessionContext)
    {
        _enterpriseSpecialistRepository = enterpriseSpecialistRepository;
        _userRepository = userRepository;
        _orderRepository = orderRepository;
        _sessionContext = sessionContext;
    }
    
    public ISugarQueryable<User> QueryUsersForSpecialist(UserPagedDto request)
    {
        return _userRepository.Queryable()
            .Includes(d=>d.Account)
            .Where(d => SqlFunc.Subqueryable<EnterpriseSpecialist>().Where(x => x.Id == d.Id).NotAny())
            .WhereIF(!string.IsNullOrEmpty(request.PhoneNo), d => d.PhoneNo == request.PhoneNo)
            .WhereIF(!string.IsNullOrEmpty(request.Name), d => d.Name == request.Name);
    }

    public async Task<ISugarQueryable<Order>> QueryEnterpriseSpecialistOrdersAsync(QueryOrderDto dto, CancellationToken cancellationToken)
    {
        var currentId = _sessionContext.RequiredUserId;
        var memberIds = await _enterpriseSpecialistRepository.Queryable()
            .Where(d => d.Id == currentId || d.ParentId == currentId)
            .Select(d => d.Id)
            .ToListAsync(cancellationToken);
        return _orderRepository.Queryable()
                .Where(d => memberIds.Contains(d.CreatorId))
                .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.No.Contains(dto.No!))
                .WhereIF(!string.IsNullOrEmpty(dto.Title), d => d.Title.Contains(dto.Title!))
                .WhereIF(dto.CreationTimeStart.HasValue, d => d.CreationTime >= dto.CreationTimeStart) //受理时间开始
                .WhereIF(dto.CreationTimeEnd.HasValue, d => d.CreationTime <= dto.CreationTimeEnd) //受理时间结束
                .WhereIF(!string.IsNullOrEmpty(dto.NameOrNo), d => d.AcceptorName == dto.NameOrNo! || d.AcceptorStaffNo == dto.NameOrNo!) //受理人/坐席
            ;
    }
}