using System.Security.Claims;
using GxPress.Common.Tools;
using GxPress.EnumConst;
using Microsoft.AspNetCore.Http;

namespace GxPress.Auth
{
    /// <summary>
    ///     登录用户上下文
    /// </summary>
    public class LoginContext : ILoginContext
    {
        private readonly IHttpContextAccessor _contextAccessor;

        public LoginContext(IHttpContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
        }

        /// <summary>
        ///     账户id
        /// </summary>
        public int AccountId
        {
            get
            {
                var value = _contextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier);
                if (int.TryParse(value?.Value, out var accountId))
                {
                    return accountId;
                }
                return -1;
            }
        }

        public int DepartmentId
        {
            get
            {
                var value = _contextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.GroupSid);
                if (int.TryParse(value?.Value, out var departmentId))
                {
                    return departmentId;
                }
                return -1;
            }
        }

        /// <summary>
        ///     账号类型
        /// </summary>
        public AccountTypeConst AccountType
        {
            get
            {
                var ty = _contextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.Role);

                return StringUtils.ToEnum(ty?.Value, AccountTypeConst.UnKnown);
            }
        }

        /// <summary>
        ///     获取当前用户IP
        /// </summary>
        public string Ip => _contextAccessor?.HttpContext?.Connection == null
            ? string.Empty
            : _contextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();

        public string Name
        {
            get
            {
                var value = _contextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.Actor);

                return value.Value;
            }
        }

        //TODO 其他用户相关信息获取?

    }
}