namespace WIDESEAWCS_SignalR;

/// <summary>
/// <inheritdoc cref="ISimpleHub"/>
/// </summary>
//[Authorize]
[MapHub("/hubs/simple")]
public class SimpleHub : Hub<ISimpleHub>
{
    private readonly ICacheService _simpleCacheService;

    public SimpleHub(ICacheService simpleCacheService)
    {
        _simpleCacheService = simpleCacheService;
    }

    /// <summary>
    /// 连接
    /// </summary>
    /// <returns></returns>
    public override async Task OnConnectedAsync()
    {
        var token = Context.GetHttpContext().Request.Query["access_token"];//获取token
        if (!string.IsNullOrEmpty(token))
        {
            var userIdentifier = Context.UserIdentifier;//自定义的Id
            UpdateRedis(userIdentifier, token);//æ›´æ–°redis
        }
    }

    /// <summary>
    /// 断开连接
    /// </summary>
    /// <param name="exception"></param>
    /// <returns></returns>
    public override async Task OnDisconnectedAsync(Exception? exception)
    {
        var userIdentifier = Context.UserIdentifier;//自定义的Id
        UpdateRedis(userIdentifier, null, false);//æ›´æ–°redis
        await base.OnDisconnectedAsync(exception);
    }

    /// <summary>
    /// 退出登录
    /// </summary>
    /// <param name="userId"></param>
    /// <returns></returns>
    public async Task LoginOut(string userId)
    {
        await Clients.User(userId).LoginOut("退出登录");
    }

    #region 方法

    /// <summary>
    /// æ›´æ–°redis
    /// </summary>
    /// <param name="userIdentifier">用户id</param>
    /// <param name="token">token</param>
    /// <param name="ifConnect">是否是上线</param>
    private void UpdateRedis(string userIdentifier, string token, bool ifConnect = true)
    {
        var userId = userIdentifier.Split("_")[0];//分割取第一个
        if (!string.IsNullOrEmpty(userId))
        {
            //获取缓存当前用户的token信息列表
            var tokenInfos = _simpleCacheService.Get<List<UserInfo>>("Cache_UserToken");
            if (tokenInfos != null)
            {
                if (ifConnect)
                {
                    //获取redis中当前token
                    var tokenInfo = tokenInfos.Where(it => it.Token == token).FirstOrDefault();
                    if (tokenInfo != null)
                    {
                        tokenInfos.Remove(tokenInfo);//删除原来的(一个用户只能有一个token)
                        tokenInfo.Token_ID = userIdentifier;//添加到客户端列表
                        tokenInfo.Token = token;//添加到客户端列表
                        tokenInfo.UserId = userId.ToInt32(); //添加到客户端列表
                        tokenInfos.Add(tokenInfo);
                        _simpleCacheService.Remove("Cache_UserToken");//删除Redis
                        _simpleCacheService.AddObject("Cache_UserToken", tokenInfos);//æ›´æ–°Redis
                    }
                    else
                    {
                        tokenInfos.Add(new UserInfo() { Token = token, Token_ID = userIdentifier ,UserId = userId.ToInt32() });
                        _simpleCacheService.AddObject("Cache_UserToken", tokenInfos);//æ›´æ–°Redis
                    }
                }
                else
                {
                    //获取当前客户端ID所在的token信息
                    var tokenInfo = tokenInfos.Where(it => it.Token == token).FirstOrDefault();
                    if (tokenInfo != null)
                    {
                        tokenInfos.Remove(tokenInfo);//删除原来的(一个用户只能有一个token)
                        _simpleCacheService.Remove("Cache_UserToken");//删除Redis
                        _simpleCacheService.AddObject("Cache_UserToken", tokenInfos);//æ›´æ–°Redis
                    }
                }
            }
            else
            {
                if (ifConnect)
                {
                    tokenInfos = new List<UserInfo>
                    {
                        new UserInfo() { Token = token, Token_ID = userIdentifier ,UserId = userId.ToInt32()  }
                    };
                    _simpleCacheService.AddObject("Cache_UserToken", tokenInfos);//æ›´æ–°Redis
                }
            }
        }
    }

    #endregion 方法
}