using Hotline.Orders;
using Hotline.Share.Dtos.Order.CarbonCopy;
using SqlSugar;
using XF.Domain.Authentications;
using XF.Domain.Dependency;
using XF.Domain.Repository;

namespace Hotline.Application.OrderApp;

public class OrderCarbonCopyApplication : IOrderCarbonCopyApplication, IScopeDependency
{
    private readonly ISessionContext _sessionContext;
    private readonly IRepository<OrderCarboncopy> _orderccRepository;

    public OrderCarbonCopyApplication(
        ISessionContext sessionContext,
        IRepository<OrderCarboncopy> orderccRepository)
    {
        _sessionContext = sessionContext;
        _orderccRepository = orderccRepository;
    }

    public ISugarQueryable<OrderCarboncopy> Query(QueryCarbonCopyRequest dto)
    {
        return _orderccRepository.Queryable()
            .Includes(d => d.Order)
            .Where(d => (!string.IsNullOrEmpty(d.UserId) && d.UserId == _sessionContext.UserId)
                        || (!string.IsNullOrEmpty(d.OrgId) && d.OrgId == _sessionContext.OrgId)
                        || (!string.IsNullOrEmpty(d.RoleId) && _sessionContext.Roles.Contains(d.RoleId)))
            .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.Order.No.Contains(dto.No))//工单编码
            .WhereIF(!string.IsNullOrEmpty(dto.Title), d => d.Order.Title.Contains(dto.Title!)) //标题
            .WhereIF(!string.IsNullOrEmpty(dto.AcceptType), d => d.Order.AcceptTypeCode == dto.AcceptType) //受理类型
            .WhereIF(!string.IsNullOrEmpty(dto.Hotspot), d => d.Order.HotspotSpliceName != null && d.Order.HotspotSpliceName.Contains(dto.Hotspot))
            .WhereIF(!string.IsNullOrEmpty(dto.ActualHandleOrgName), d => d.Order.ActualHandleOrgName.Contains(dto.ActualHandleOrgName)) //接办部门（综合查询模糊）
            .WhereIF(dto.CreationTimeStart.HasValue, d => d.Order.CreationTime >= dto.CreationTimeStart) //受理时间开始
            .WhereIF(dto.CreationTimeEnd.HasValue, d => d.Order.CreationTime <= dto.CreationTimeEnd) //受理时间结束
            .WhereIF(dto.ExpiredTimeStart.HasValue, d => d.Order.ExpiredTime >= dto.ExpiredTimeStart) //超期时间开始
            .WhereIF(dto.ExpiredTimeEnd.HasValue, d => d.Order.ExpiredTime <= dto.ExpiredTimeEnd) //超期时间结束
        ;
    }
}