using Microsoft.AspNetCore.SignalR;
using OASystem.API.OAMethodLib.Hub.HubClients;
using OASystem.API.OAMethodLib.SignalR.Hubs;
using OASystem.API.OAMethodLib.SignalR.HubService;
using static OASystem.API.OAMethodLib.JWTHelper;

namespace OASystem.API.OAMethodLib.Hub.Hubs
{
    //[Authorize]
    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    public class ChatHub : Hub<IChatClient>
    {
        private readonly ILogger<ChatHub> _logger;
        private readonly CommonService _common;

        /// <summary>
        /// 已登录的用户信息
        /// </summary>
        //public static List<UserModel> OnlineUser { get; set; } = new List<UserModel>();

        public ChatHub(ILogger<ChatHub> logger, CommonService common)
        {
            _logger = logger;
            _common = common;
        }

        /// <summary>
        /// SignalR登录验证
        /// </summary>
        public async Task SignalRLogin(int userId)
        {
            string connid = Context.ConnectionId;
            string result = $"[{connid}]";
            string userId1 = Context.UserIdentifier;

            if (!UserStore.OnlineUser.Exists(u => u.ConnectionId == connid))
            {
                result += "上线成功!";

                UserStore.OnlineUser.Add(new UserModel() { UserId = userId, ConnectionId = connid, GroupName = "FMGJ-OASystem" });
            }
            else
            {
                result += "已上线!";
            }
            //给当前连接返回消息
            await Clients.Client(connid).SendAsync("SignalRLoginResponse", result);
        }

        /// <summary>
        /// </summary>        
        /// /// 客户端连接服务端
        /// <returns></returns>
        public override Task OnConnectedAsync()
        {
            var httpContext = Context.GetHttpContext();

            if (httpContext != null)
            {
                string token = httpContext.Request.Headers["Authorization"]; // 根据实际情况修改 header key

                // 处理 token...
                if (!string.IsNullOrEmpty(token))
                {
                    TokenModelJwt tokenModelJwt = JwtHelper.SerializeJwt(token.ToString().Split(" ")[1]);
                    string result = "";
                    if (tokenModelJwt != null)
                    {
                        var connId = Context.ConnectionId;

                        //UserStore.OnlineUser.RemoveAll(u => u.UserId == tokenModelJwt.UserId);

                        UserStore.OnlineUser.Add(new UserModel() { UserId = tokenModelJwt.UserId, ConnectionId = connId, GroupName = "FMGJ-OASystem" });

                        _logger.LogInformation($"Client ConnectionId=> [[{connId}]] UserId=> [[{tokenModelJwt.UserId}]] Already Connection Server!");

                        //Clients.All.SendAsync("GetOnlineResponse", $"[{tokenModelJwt.UserName}({tokenModelJwt.Role})] 上线");

                        Clients.Clients(connId).ReceiveMessage(_common.ReceiveMessage($"[{tokenModelJwt.UserName}({tokenModelJwt.Role})] 已上线!"));
                        //
                    }
                }
            }

            //给当前连接返回消息
            //await Clients.Client(connid).SendAsync("SignalRLoginResponse", result);

            return base.OnConnectedAsync();
        }

        /// <summary>
        /// 客户端断开连接
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override Task OnDisconnectedAsync(Exception exception)
        {
            var connId = Context.ConnectionId;
            _logger.LogInformation($"Client ConnectionId=> [[{connId}]] Already Close Connection Server!");
            var model = UserStore.OnlineUser.Find(u => u.ConnectionId == connId);
            int count = UserStore.OnlineUser.RemoveAll(u => u.ConnectionId == connId);
            if (model != null)
            {
                var onlineUser = UserStore.OnlineUser.FindAll(u => u.GroupName == model.GroupName);

                Clients.Clients(connId).ReceiveMessage(_common.ReceiveMessage($"[UserID=>{model.UserId} ConnectionId=> {model.ConnectionId} ] 已下线!"));
            }
            return base.OnDisconnectedAsync(exception);
        }


        /**
         * 测试 
         * */
        /// <summary>
        /// 给所有客户端发送消息
        /// </summary>
        /// <returns></returns>
        public async Task SendMessage(string data)
        {
            Console.WriteLine("Have one Data!");
            await Clients.All.SendAll(_common.SendAll(data));
            await Clients.Caller.SendAll(_common.SendCaller(data));
        }

        /// <summary>
        /// 发送消息给指定用户(系统)
        /// </summary>
        /// <param name="id"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendSystemToUser(string id, string message) => await Clients.Client(id).SendAsync("ReceiveMessage", message);

        /// <summary>
        /// 发送消息给所有用户(系统)
        /// </summary>
        /// <param name="id"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendSystemToAllUser(string message) => await Clients.All.SendAsync("ReceiveMessage", message);
    }
}