using Hotline.Orders;
using Hotline.SeedData;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.Bi;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Enums.Order;
using SqlSugar;
using XF.Domain.Authentications;
using XF.Domain.Dependency;
using XF.Domain.Repository;

namespace Hotline.Application.Orders
{
    public class OrderSendBackAuditApplication : IOrderSendBackAuditApplication, IScopeDependency
    {
        private readonly IRepository<OrderSendBackAudit> _orderSendBackAuditRepository;
        private readonly ISessionContext _sessionContext;
        public OrderSendBackAuditApplication(IRepository<OrderSendBackAudit> orderSendBackAuditRepository, ISessionContext sessionContext)
        {
            _orderSendBackAuditRepository = orderSendBackAuditRepository;
            _sessionContext = sessionContext;
        }

        public ISugarQueryable<OrderSendBackAudit> AuditList(SendBackListDto dto)
        {
            return _orderSendBackAuditRepository.Queryable()
                .Includes(x => x.Order)
                .WhereIF(!string.IsNullOrEmpty(dto.Keyword),
                    d => d.Order.Title.Contains(dto.Keyword!) || d.Order.No.Contains(dto.Keyword!))
                .WhereIF(!string.IsNullOrEmpty(dto.Title), d => d.Order.Title.Contains(dto.Title!))
                .WhereIF(!string.IsNullOrEmpty(dto.No), d => d.Order.No.Contains(dto.No!))
                .WhereIF(!string.IsNullOrEmpty(dto.AcceptTypeCode), d => d.Order.AcceptTypeCode == dto.AcceptTypeCode)
                .WhereIF(!string.IsNullOrEmpty(dto.OrgName), d => d.ApplyOrgName == dto.OrgName)
                .WhereIF(dto.DataScope is 1, d => d.CreatorId == _sessionContext.RequiredUserId)
                .WhereIF(dto.StartTime.HasValue, d => d.CreationTime >= dto.StartTime)
                .WhereIF(dto.EndTime.HasValue, d => d.CreationTime <= dto.EndTime)
                .WhereIF(dto.AuditState == 1, d => d.State == ESendBackAuditState.Apply)
                .WhereIF(dto is { AuditState: 2, State: null }, d => d.State > ESendBackAuditState.Apply)
                .WhereIF(dto.AuditState is 2 or 3 && dto.State.HasValue && dto.State != ESendBackAuditState.All, d => d.State == dto.State)
                .WhereIF(dto.AuditState == 3 && _sessionContext.RequiredOrgId != OrgSeedData.CenterId, x => x.ApplyOrgId.StartsWith(_sessionContext.OrgId))
                .WhereIF(_sessionContext.Roles.Contains("role_sysadmin") == false && dto.AuditState != 3, x => x.SendBackOrgId == _sessionContext.OrgId) // 123 系统管理员;
                .WhereIF(dto.ExpiredTimeStart.HasValue, x => x.Order.ExpiredTime >= dto.ExpiredTimeStart)
                .WhereIF(dto.ExpiredTimeEnd.HasValue, x => x.Order.ExpiredTime <= dto.ExpiredTimeEnd)

            .OrderByDescending(x => x.CreationTime);
        }
    }
}
