
using FactorySystemModel.BusinessModel;
using Microsoft.Owin;
using System;
using System.Net.Http;
using System.ServiceModel.Channels;
using System.Text.RegularExpressions;
using System.Web;

namespace FactorySystemCommon
{
    /// <summary>
    /// 客户端帮助类
    /// </summary>
    public class HttpContextHelp
    {
        /// <summary>
        /// 取得客户端真实IP。如果有代理则取第一个非内网地址
        /// </summary>
        public static string GetBrowserInfo(HttpRequestMessage request)
        {
            try
            {
                if (HttpContext.Current == null)
                {
                    if (request != null) return request.Headers.UserAgent.ToString();
                }
                else
                {
                    HttpBrowserCapabilities hbc = HttpContext.Current.Request.Browser;
                    string browserType = hbc.Browser.ToString(); //获取浏览器类型
                    string browserVersion = hbc.Version.ToString(); //获取版本号
                    string browserVersions = browserType + browserVersion;
                    return browserVersions;
                }
            }
            catch (Exception) { }
            return "";
        }

        /// <summary>
        /// 获取用户ID
        /// </summary>
        public static int GetUserId(HttpRequestMessage request)
        {
            try
            {
                if (request != null)
                {
                    var token = request.Properties["token"];
                    if (token != null)
                    {
                        ApiAuthInfo authInfo = token as ApiAuthInfo;
                        return authInfo.FID;
                    }
                    else
                    {
                        token = HttpContext.Current.Request["token"];
                        ApiAuthInfo authInfo = token as ApiAuthInfo;
                        return authInfo.FID;
                    }
                }
            }
            catch (Exception) { }
            return -1;
        }

        /// <summary>
        /// 取得客户端真实IP。如果有代理则取第一个非内网地址
        /// </summary>
        public static string GetIPAddress(HttpRequestMessage request)
        {
            try
            {
                if (HttpContext.Current == null) return GetIPAddress2(request);
                string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (!string.IsNullOrEmpty(result))
                {
                    if (result.IndexOf(".") == -1) result = null;
                    else
                    {
                        if (result.IndexOf(",") != -1)
                        {
                            result = result.Replace(" ", "").Replace("'", "");
                            string[] temparyip = result.Split(",;".ToCharArray());
                            for (int i = 0; i < temparyip.Length; i++)
                            {
                                if (IsIPAddress(temparyip[i]) && temparyip[i].Substring(0, 3) != "10." &&
                                    temparyip[i].Substring(0, 7) != "192.168" && temparyip[i].Substring(0, 7) != "172.16.")
                                {
                                    return temparyip[i];
                                }
                            }
                        }
                        else if (IsIPAddress(result)) return result;
                        else result = null;
                    }
                }
                if (string.IsNullOrEmpty(result)) result = HttpContext.Current.Request.ServerVariables["HTTP_X_REAL_IP"];
                if (string.IsNullOrEmpty(result)) result = HttpContext.Current.Request.UserHostAddress;
                if (!string.IsNullOrEmpty(result)) return result;
            }
            catch (Exception) { }
            return GetIPAddress2(request);
        }

        public static string GetIPAddress2(HttpRequestMessage request)
        {
            string ip = "";
            try
            {
                if (request != null)
                {
                    if (request.Properties.ContainsKey("MS_OwinContext"))
                    {
                        ip = ((OwinContext)request.Properties["MS_OwinContext"]).Request.RemoteIpAddress;
                    }
                    else if (request.Properties.ContainsKey("MS_HttpContext"))
                    {
                        ip = ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
                    }
                    else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
                    {
                        ip = ((RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name]).Address;
                    }
                }
            }
            catch (Exception) { }
            return ip ?? "";
        }

        /// <summary>
        /// 判断是否是IP地址格式 0.0.0.0
        /// </summary>
        public static bool IsIPAddress(string str1)
        {
            if (string.IsNullOrEmpty(str1) || str1.Length < 7 || str1.Length > 15) return false;
            const string regFormat = @"^d{1,3}[.]d{1,3}[.]d{1,3}[.]d{1,3}$";
            var regex = new Regex(regFormat, RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }
    }
}
