using Hotline.SeedData;
using Hotline.Share.Dtos.Users;
using Hotline.Share.Enums.Identity;
using Hotline.Users;
using SqlSugar;
using XF.Domain.Authentications;
using XF.Domain.Dependency;
using XF.Domain.Repository;

namespace Hotline.Application.Users
{
    public class UserApplication : IUserApplication, IScopeDependency
    {
        private readonly IRepository<User> _userRepository;
        private readonly ISessionContext _sessionContext;

        public UserApplication(IRepository<User> userRepository, ISessionContext sessionContext)
        {
            _userRepository = userRepository;
            _sessionContext = sessionContext;
        }

        /// <summary>
        /// 查询用户数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public ISugarQueryable<User> QueryPaged(UserPagedDto dto)
        {
            return _userRepository.Queryable(includeDeleted: true)
             .Includes(d => d.Account)
             .Includes(d => d.Roles)
             .Includes(d => d.Organization)
             .Where(d => d.Account.AccountType == EAccountType.Personal && d.Id != SysAccountSeedData.Id)
             .WhereIF(_sessionContext.OrgIsCenter == false, d => d.OrgId.StartsWith(_sessionContext.RequiredOrgId))
             .WhereIF(!string.IsNullOrEmpty(dto.Keyword),
                 d => d.Name.Contains(dto.Keyword!) || d.PhoneNo.Contains(dto.Keyword!) ||
                      d.Account.UserName.Contains(dto.Keyword))
             .WhereIF(!string.IsNullOrEmpty(dto.OrgCode), d => d.OrgId == dto.OrgCode)
             .WhereIF(!string.IsNullOrEmpty(dto.Role), d => d.Roles.Any(x => x.Id == dto.Role))
             .WhereIF(!string.IsNullOrEmpty(dto.Name), d => d.Name.Contains(dto.Name))
             .WhereIF(!string.IsNullOrEmpty(dto.PhoneNo), d => d.PhoneNo.Contains(dto.PhoneNo))
             .WhereIF(!string.IsNullOrEmpty(dto.OrgName), d => d.Organization.Name.Contains(dto.OrgName))
             .OrderBy(d => d.Account.Status)
             .OrderBy(d => d.Organization.OrgType)
             .OrderByDescending(d => d.CreationTime);
        }
    }
}
