using YBEE.EQM.Core;

namespace YBEE.EQM.Application;

/// <summary>
/// 角色成员管理服务
/// </summary>
public class SysRoleUserService : ISysRoleUserService, ITransient
{
    private readonly IRepository<SysRoleUser> _roleUserRep;
    private readonly ISysRoleService _roleService;
    private readonly ISysRoleMenuService _roleMenuService;
    private readonly ICacheService _cacheService;

    public SysRoleUserService(IRepository<SysRoleUser> roleUserRep, ISysRoleService roleService, ISysRoleMenuService roleMenuService, ICacheService cacheService)
    {
        _roleUserRep = roleUserRep;
        _roleService = roleService;
        _roleMenuService = roleMenuService;
        _cacheService = cacheService;
    }

    /// <summary>
    /// 获取用户的角色Id集合
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="checkRoleStatus"></param>
    /// <returns></returns>x\
    public async Task<List<int>> GetUserRoleIdList(int userId, bool checkRoleStatus = true)
    {
        return await _roleUserRep
            // 检查role状态，跳过全局tenantId&delete过滤器，超级管理员使用
            .Where(!checkRoleStatus, u => u.SysRole.Status == CommonStatus.ENABLE && !u.SysRole.IsDeleted, ignoreQueryFilters: true)
            // 当不是超级管理员的时候检查role状态和全局tenantId&delete过滤器
            .Where(checkRoleStatus, u => u.SysRole.Status == CommonStatus.ENABLE)
            .Where(u => u.SysUserId == userId)
            .Select(u => u.SysRoleId)
            .ToListAsync();
    }

    /// <summary>
    /// 获取用户拥有角色列表
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="checkRoleStatus"></param>
    /// <returns></returns>
    public async Task<List<SysRoleOutput>> GetUserRoleList(int userId, bool checkRoleStatus = true)
    {
        var ids = await GetUserRoleIdList(userId, checkRoleStatus);
        return await _roleService.GetListByIds(ids);
    }

    /// <summary>
    /// 获取登录用户拥有角色列表
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="checkRoleStatus"></param>
    /// <returns></returns>
    public async Task<List<SysRoleOutput>> GetLoginUserRoleList(int userId, bool checkRoleStatus = true)
    {
        var items = await _cacheService.GetRoleDataScope(userId);
        if (items == null || items.Count < 1)
        {
            var ids = await GetUserRoleIdList(userId, checkRoleStatus);
            items = await _roleService.GetListByIds(ids);
            // 缓存结果
            await _cacheService.SetRoleDataScope(userId, items);
        }
        return items;
    }

    /// <summary>
    /// 添加用户到角色
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task AddRoleUser(SysRoleUserInput input)
    {
        var roleUserIds = await _roleUserRep.Where(t => t.SysRoleId == input.SysRoleId).Select(t => t.SysUserId).ToListAsync();
        var addUserIds = from it in input.SysUserIdList where !(from rid in roleUserIds select rid).Contains(it) select it;

        var roles = addUserIds.Select(u => new SysRoleUser
        {
            SysRoleId = input.SysRoleId,
            SysUserId = u,
        }).ToList();
        await _roleUserRep.InsertAsync(roles);
    }

    /// <summary>
    /// 移出角色中的用户
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task RemoveRoleUser(SysRoleUserInput input)
    {
        var roleUsers = await _roleUserRep.Where(t => t.SysRoleId == input.SysRoleId && input.SysUserIdList.Contains(t.SysUserId)).ToListAsync();
        await _roleUserRep.DeleteNowAsync(roleUsers);
    }

    /// <summary>
    /// 判断用户是否为超级管理员
    /// </summary>
    /// <param name="userId"></param>
    /// <returns></returns>
    public async Task<bool> IsSuperAdmin(int userId)
    {
        var roles = await GetUserRoleList(userId);
        return roles.Any(t => t.RoleType == RoleType.SUPER_ADMIN);
    }

    /// <summary>
    /// 获取指定角色中的用户列表
    /// </summary>
    /// <param name="roleId"></param>
    /// <returns></returns>
    public async Task<List<SysUserOutput>> GetInRoleUserList(int roleId)
    {
        var items = await _roleUserRep.DetachedEntities
                                       .Include(t => t.SysUser)
                                       .Where(t => t.SysRoleId == roleId)
                                       .OrderByDescending(u => u.Id)
                                       .Select(t => t.SysUser)
                                       .ProjectToType<SysUserOutput>()
                                       .ToListAsync();

        foreach (var item in items)
        {
            item.SysRoles = await GetUserRoleList(item.Id);
        }

        return items;
    }

    /// <summary>
    /// 分页查询角色用户列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<PageResult<SysUserOutput>> QueryInRoleUserPageList(SysRoleUserPageInput input)
    {
        var ret = await _roleUserRep.DetachedEntities
                                       .Include(t => t.SysUser)
                                       .Where(t => t.SysRoleId == input.SysRoleId)
                                       .Where(input.SysOrgId.HasValue, t => t.SysUser.SysOrgId == input.SysOrgId)
                                       .OrderByDescending(u => u.Id)
                                       .Select(t => t.SysUser)
                                       .ProjectToType<SysUserOutput>()
                                       .ToADPagedListAsync(input.PageIndex, input.PageSize);

        foreach (var item in ret.Items)
        {
            item.SysRoles = await GetUserRoleList(item.Id);
        }

        return ret;
    }

    /// <summary>
    /// 获取未在指定角色中的用户列表
    /// </summary>
    /// <param name="roleId"></param>
    /// <returns></returns>
    public async Task<List<SysUserOutput>> GetNotInRoleUserList(int roleId)
    {
        var roleUsers = await _roleUserRep.DetachedEntities.Where(t => t.SysRoleId == roleId).Select(t => t.SysUserId).ToListAsync();
        var items = await _roleUserRep.Change<SysUser>().DetachedEntities
                                       .Where(t => t.Id > 1 && !roleUsers.Contains(t.Id))
                                       .OrderByDescending(u => u.Name)
                                       .ProjectToType<SysUserOutput>()
                                       .ToListAsync();
        return items;
    }

    /// <summary>
    /// 根据角色Id删除对应的用户-角色表关联信息
    /// </summary>
    /// <param name="roleId"></param>
    /// <returns></returns>
    public async Task DeleteRoleUserByRoleId(int roleId)
    {
        var userRoles = await _roleUserRep.Where(u => u.SysRoleId == roleId).ToListAsync();
        await _roleUserRep.DeleteAsync(userRoles);
    }

    /// <summary>
    /// 根据用户Id删除对应的用户-角色表关联信息
    /// </summary>
    /// <param name="userId"></param>
    /// <returns></returns>
    public async Task DeleteUserRoleListByUserId(int userId)
    {
        var surList = await _roleUserRep.AsQueryable(m => m.SysUserId == userId, false).ToListAsync();
        await _roleUserRep.DeleteAsync(surList);
    }

    /// <summary>
    /// 通过权限标识获取人员列表
    /// </summary>
    /// <param name="permission">权限标识</param>
    /// <returns></returns>
    public async Task<List<SysUserLiteOutput>> GetUserListByPermission(string permission)
    {
        var roleIds = await _roleMenuService.GetRoleIdListByMenuPermissionCode(permission);
        var items = await _roleUserRep.DetachedEntities
                                        .Include(t => t.SysRole)
                                        .Where(t => roleIds.Contains(t.SysRoleId) && t.SysUser.Status == CommonStatus.ENABLE && t.SysUser.IsDeleted == false)
                                        .OrderByDescending(u => u.Id)
                                        .Select(t => t.SysUser)
                                        .ProjectToType<SysUserLiteOutput>()
                                        .ToListAsync();
        return items;
    }
}