namespace WIDESEAWCS_SignalR;
/// 
/// 用户ID提供器
/// 
public class UserIdProvider : IUserIdProvider
{
    public string GetUserId(HubConnectionContext connection)
    {
        var token = connection.GetHttpContext().Request.Query["access_token"];//获取token
        var userId = JwtHelper.GetUserId(token);//解析token
        if (userId > 0)//如果不为空
            return $"{userId}_{CreateLetterAndNumber(5)}";//返回用户ID
        else
            return connection.ConnectionId;
    }
    /// 
    /// 生成随机字母和数字随机数
    /// 
    /// 生成长度
    /// 
    public static string CreateLetterAndNumber(int Length)
    {
        char[] array = new char[62]
        {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
            'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
            'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
            'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
            'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9'
        };
        string text = "";
        int maxValue = array.Length;
        Random random = new Random((int)(~DateTime.Now.Ticks));
        for (int i = 0; i < Length; i++)
        {
            int num = random.Next(0, maxValue);
            text += array[num];
        }
        return text;
    }
}