using Hotline.Orders;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Enums.Order;
using Hotline.Share.Tools;
using SqlSugar;
using XF.Domain.Dependency;

namespace Hotline.Application.Orders;

/// <summary>
/// 回访服务
/// </summary>
public class OrderVisitApplication : IOrderVisitApplication, IScopeDependency
{
    private readonly IOrderVisitRepository _orderVisitRepository;

    public OrderVisitApplication(IOrderVisitRepository orderVisitRepository)
    {
        _orderVisitRepository = orderVisitRepository;
    }

    public async Task<List<OrderVisitQuantityOutDto>> QueryOrderVisitQuantityAsync(QueryOrderVisitQuantity dto, CancellationToken cancellationToken)
    {
        var query = _orderVisitRepository
            .Queryable()
            .WhereIF(dto.EmployeeName.NotNullOrEmpty(), m => m.Employee.Name.Contains(dto.EmployeeName))
            .Where(m => m.VisitTime >= dto.StartTime && m.VisitTime <= dto.EndTime && m.VisitType != null && m.EmployeeId != "" && m.EmployeeId != null)
            .GroupBy(m => m.EmployeeId)
            .Select(m => new OrderVisitQuantityOutDto
            {
                EmployeeId = m.EmployeeId,
                EmployeeName = m.Employee.Name,
                CallVisitCount = SqlFunc.AggregateSum(SqlFunc.IIF(m.VisitType == EVisitType.CallVisit, 1, 0)), // 电话回访量
                DefaultVisitCount = SqlFunc.AggregateSum(SqlFunc.IIF(m.VisitType == EVisitType.ArtificialVisit, 1, 0)), // 默认回访量(人工回访)
                SmsVisitCount = SqlFunc.AggregateSum(SqlFunc.IIF(m.VisitType == EVisitType.SmsVisit, 1, 0)), // 短信回访量
                // TotalVisitCount = SqlFunc.AggregateSum(SqlFunc.IIF(m.VisitType != null, 1, 0)) // 总回访量
            });


        return await query.ToListAsync(cancellationToken);
    }
}
