using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Configuration;
using System.Web;
using Foresight.ServiceModel;
using Foresight.Security;
using IronIntel.Services;
using IronIntel.Services.Users;
using IronIntel.Services.Customers;

namespace IronIntel.Contractor.Site
{
    public class IronIntelBasePage : System.Web.UI.Page
    {
        public const string LOGINSESSION_COOKIENAME = "iiabc_";
        public const string LANGUAGECOOKIENAME = LOGINSESSION_COOKIENAME + "language";        
        public const string APPNAME = "iron-desktop";
        public const string CLIENT_TIMEOFFSET_COOKIENAME = "clienttimeoffset";

        private static int _LOCAL_TIMEOFFSET = 10000;

        private static string _HostName = null;

        private static string _Branch = string.Empty;
        private static string _AboutUrl = string.Empty;
        private static string _Copyrights = string.Empty;
        private static string _PageTitle = string.Empty;
        private static string _ShowTermofuse = string.Empty;

        public static string LocalHostName
        {
            get
            {
                if (_HostName == null)
                {
                    try
                    {
                        _HostName = Dns.GetHostName();
                    }
                    catch
                    {
                        _HostName = string.Empty;
                    }
                }
                return _HostName;
            }
        }

        public static int LocalTimeOffset
        {
            get
            {
                if (_LOCAL_TIMEOFFSET == 10000)
                {
                    DateTime dt = DateTime.Now;
                    DateTime dt1 = dt.ToUniversalTime();
                    TimeSpan sp = dt1 - dt;
                    _LOCAL_TIMEOFFSET = Convert.ToInt32(sp.TotalMinutes);
                }
                return _LOCAL_TIMEOFFSET;
            }
        }

        private static readonly byte[] KEY = new byte[] { 219, 239, 201, 20, 173, 133, 64, 29, 33, 71, 49, 117, 208, 115, 79, 169, 1, 126, 201, 229, 115, 35, 62, 102, 71, 16, 71, 220, 44, 95, 186, 223 };
        private static readonly byte[] IV = new byte[] { 255, 180, 99, 244, 147, 37, 175, 243, 193, 52, 167, 82, 143, 199, 242, 171 };

        public static string EncryptString(string s)
        {
            if (string.IsNullOrWhiteSpace(s))
            {
                return string.Empty;
            }
            byte[] buf = Encoding.UTF8.GetBytes(s);
            byte[] tmp = SecurityHelper.AesEncrypt(buf, KEY, IV);
            return Convert.ToBase64String(tmp);
        }

        public static string DecryptString(string s)
        {
            if (string.IsNullOrWhiteSpace(s))
            {
                return string.Empty;
            }
            byte[] tmp = Convert.FromBase64String(s);
            byte[] buf = SecurityHelper.AesDecrypt(tmp, KEY, IV);
            return Encoding.UTF8.GetString(buf);
        }

        public virtual string GetIronSystemServiceAddress()
        {
            return ConfigurationManager.AppSettings["syssvcaddress"];
        }

        public virtual IronSysServiceClient GetSystemServiceClient()
        {
            LoginSession session = null;
            try
            {
                session = GetCurrentLoginSession();
            }
            catch
            {
            }
            IronSysServiceClient ic = new IronSysServiceClient(GetIronSystemServiceAddress());
            if (session != null)
            {
                ic.AppName = session.AppName;
                ic.LoginSessionID = session.SessionID;
                ic.CurrentUserIID = session.User.UID;
            }
            return ic;
        }

        public virtual CustomerProvider GetCustomerProvider()
        {
            LoginSession session = null;
            try
            {
                session = GetCurrentLoginSession();
            }
            catch
            {
            }
            CustomerProvider ic = new CustomerProvider(GetIronSystemServiceAddress());
            if (session != null)
            {
                ic.AppName = session.AppName;
                ic.LoginSessionID = session.SessionID;
                ic.CurrentUserIID = session.User.UID;
            }
            return ic;
        }

        public virtual LoginProvider GetLoginProvider()
        {
            LoginSession session = null;
            try
            {
                session = GetCurrentLoginSession();
            }
            catch
            {
            }
            LoginProvider ic = new LoginProvider(GetIronSystemServiceAddress());
            if (session != null)
            {
                ic.AppName = session.AppName;
                ic.LoginSessionID = session.SessionID;
                ic.CurrentUserIID = session.User.UID;
            }
            return ic;
        }

        private string GetServerParam(string key)
        {
            IronSysServiceClient ic = new IronSysServiceClient(GetIronSystemServiceAddress());
            StringKeyValue[] kvs = ic.GetServerParams();
            foreach (StringKeyValue kv in kvs)
            {
                if (string.Compare(kv.Key, key, true) == 0)
                {
                    return kv.Value;
                }
            }
            return string.Empty;
        }

        public string Branch
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_Branch))
                {
                    _Branch = GetServerParam("Branch");
                }
                return _Branch;
            }
        }

        public string AboutUrl
        {
            get
            {
                if (string.IsNullOrEmpty(_AboutUrl))
                {
                    _AboutUrl = GetServerParam("AboutUrl");
                }
                return _AboutUrl;
            }
        }

        public string Copyrights
        {
            get
            {
                if (string.IsNullOrEmpty(_Copyrights))
                {
                    _Copyrights = GetServerParam("Copyrights");
                }
                return _Copyrights;
            }
        }


        public string PageTitle
        {
            get
            {
                if (string.IsNullOrEmpty(_PageTitle))
                {
                    _PageTitle = GetServerParam("PageTitle");
                }
                return _PageTitle;
            }
        }

        public bool ShowTermofuse
        {
            get
            {
                if (string.IsNullOrEmpty(_ShowTermofuse))
                {
                    _ShowTermofuse = GetServerParam("ShowTermofuse");
                }
                return string.Compare(_ShowTermofuse, "True", true) == 0 || string.Compare(_ShowTermofuse, "Yes", true) == 0 || string.Compare(_ShowTermofuse, "1", true) == 0;
            }
        }

        public static string GetLoginSessionID(HttpRequest request)
        {
            HttpCookie cookie = request.Cookies[LOGINSESSION_COOKIENAME];
            if (cookie == null)
            {
                return string.Empty;
            }
            if (string.IsNullOrWhiteSpace(cookie.Value))
            {
                return string.Empty;
            }
            return DecryptString(cookie.Value);
        }

        public LoginSession GetCurrentLoginSession()
        {
            string sessionid = GetLoginSessionID(Request);
            if (string.IsNullOrWhiteSpace(sessionid))
            {
                return null;
            }
            try
            {
                LoginProvider ic = new LoginProvider(GetIronSystemServiceAddress());
                return ic.GetLoginSession(sessionid);
            }
            catch
            {
                return null;
            }
        }

        protected void RedirectToLoginPage()
        {
            Response.Redirect(LoginPageUrl);
        }

        protected string LoginPageUrl
        {
            get
            {
                IronSysServiceClient ic = new IronSysServiceClient(GetIronSystemServiceAddress());
                return ic.GetPortalLoginUrl();
            }
        }

        /// <summary>
        /// 当用户登录成功后，跳转到用户的默认主界面, 也即是各公司的主界面
        /// </summary>
        /// <param name="user"></param>
        protected void RedirectToUsersDefaultEntryPage(UserInfo user)
        {
            Response.Redirect(GetUserDefaultEntryPageUrl(user), true);
        }

        protected string GetUserDefaultEntryPageUrl(UserInfo user)
        {
            IronSysServiceClient ic = new IronSysServiceClient(GetIronSystemServiceAddress());
            return ic.GetCompanyPortalEntryUrl(user.CompanyID);
        }

        protected void ClearLoginSessionCookie()
        {
            HttpCookie cookie = new HttpCookie(LOGINSESSION_COOKIENAME);
            cookie.Value = string.Empty;
            cookie.Expires = DateTime.Now.AddDays(-3);
            Response.Cookies.Add(cookie);
        }

        protected void SetLoginSessionCookie(string sessionid)
        {
            HttpCookie cookie = new HttpCookie(LOGINSESSION_COOKIENAME);
            cookie.Value = EncryptString(sessionid);

            string path = ConfigurationManager.AppSettings["sessioncookiepath"];
            if (!string.IsNullOrWhiteSpace(path))
            {
                cookie.Path = path;
            }
            string domain = ConfigurationManager.AppSettings["sessioncookiedomain"];
            if (!string.IsNullOrWhiteSpace(domain))
            {
                cookie.Domain = domain;
            }
            Response.Cookies.Add(cookie);
        }

        protected void SetClientTimeOffset(int offset)
        {
            HttpCookie cookie = new HttpCookie(CLIENT_TIMEOFFSET_COOKIENAME);
            cookie.Value = offset.ToString();
            cookie.Expires = DateTime.Now.AddYears(1);
            Response.Cookies.Add(cookie);
        }

        protected int GetClientTimeOffset()
        {
            HttpCookie cookie = Request.Cookies[CLIENT_TIMEOFFSET_COOKIENAME];
            if (cookie == null)
            {
                return LocalTimeOffset;
            }
            if (string.IsNullOrWhiteSpace(cookie.Value))
            {
                return LocalTimeOffset;
            }
            int n = 0;
            if (int.TryParse(cookie.Value, out n))
            {
                return n;
            }
            else
            {
                return LocalTimeOffset;
            }
        }

        public static DateTime UtcTimeToClientTime(DateTime dt, int clienttimeoffset)
        {
            return dt.AddMinutes(-1 * clienttimeoffset);
        }

        public static Int64 GetSiteFileDateTime(string url)
        {
            string fn = HttpContext.Current.Server.MapPath(url);
            if (System.IO.File.Exists(fn))
            {
                try
                {
                    return System.IO.File.GetLastWriteTimeUtc(fn).Ticks;
                }
                catch
                {
                    return 0;
                }
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 用于构造js/css或图片文件的url，在其最后加上版本标识，解决浏览器缓存问题
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetFileUrlWithVersion(string url)
        {
            string fn = HttpContext.Current.Server.MapPath(url);
            if (System.IO.File.Exists(fn))
            {
                try
                {
                    Int64 n = System.IO.File.GetLastWriteTimeUtc(fn).Ticks;
                    return url + "?sn=" + n.ToString();
                }
                catch
                {
                    return url;
                }
            }
            else
            {
                return url;
            }
        }

        public static string ReadTextFromStream(System.IO.Stream stream)
        {
            using (System.IO.StreamReader sr = new System.IO.StreamReader(stream))
            {
                return sr.ReadToEnd();
            }
        }

        public static string GetUserHostAddress(HttpRequest request)
        {
            const string CLIENT_IP = "client-ip";
            if (request == null)
            {
                return string.Empty;
            }

            string rst = request.Headers[CLIENT_IP];
            if (string.IsNullOrWhiteSpace(rst))
            {
                rst = request.UserHostAddress;
            }
            if (rst == null)
            {
                rst = string.Empty;
            }
            return rst;
        }

        protected string UserHostAddress
        {
            get
            {
                return GetUserHostAddress(Request);
            }
        }
    }
}
