using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Foresight.Fleet.Services;
using Foresight.Fleet.Services.User;
using Foresight.Fleet.Services.Style;
using Foresight.Fleet.Services.Customer;
using IronIntel.Contractor.Users;
using IronIntel.Contractor.iisitebase;
using Foresight.Standard;
using System.Security.Cryptography;

namespace IronIntel.Contractor.Site
{
    public class ContractorBasePage : IronIntelBasePage
    {
        public const char SPLIT_CHAR175 = (char)175;//\u00af
        public const char SPLIT_CHAR180 = (char)180;//\u00b4
        public const char SPLIT_CHAR181 = (char)181;//'µ'
        public const char SPLIT_CHAR182 = (char)182;//'¶'
        public const char SPLIT_CHAR183 = (char)183;//'·'
        public const char SPLIT_CHAR184 = (char)182;//'\u00b8'
        public static string AppVersion
        {
            get
            {
                return SystemParams.AppVersion;
            }
        }

        new public string PageTitle
        {
            get
            {
                if (MainStyleObj != null && !string.IsNullOrWhiteSpace(MainStyleObj.PageTitle))
                    return MainStyleObj.PageTitle;
                return base.PageTitle;
            }
        }

        private MainStyle _MainStyleObj;
        protected MainStyle MainStyleObj
        {
            get
            {
                if (_MainStyleObj == null)
                {
                    _MainStyleObj = SystemParams.GetMainStyle();
                }
                return _MainStyleObj;
            }
        }

        protected Users.UserInfo GetCurrentUser()
        {
            var session = GetCurrentLoginSession();
            if (session == null)
            {
                return null;
            }
            return UserManagement.GetUserByIID(session.User.UID);
        }

        protected bool IsAdminOrSuper
        {
            get
            {
                var user = GetCurrentUser();
                if (user == null)
                {
                    return false;
                }
                return (user.UserType == Users.UserTypes.Admin || user.UserType == Users.UserTypes.SupperAdmin);
            }
        }
        protected virtual bool AllowCurrentLoginSessionEnter(LoginSession session)
        {
            if (session == null)
                session = GetCurrentLoginSession();
            if (session == null)
            {
                return false;
            }
            if (string.Compare(session.User.CompanyID, SystemParams.CompanyID, true) == 0)
            {
                return true;
            }
            if (string.Compare(session.User.CompanyID, CustomerInfo.FORESIGHT, true) == 0)
            {
                return true;
            }
            return CreateClient<UserQueryClient>().CanEnterSite(session.SessionID, SystemParams.CompanyID);
        }

        protected virtual bool AllowCurrentLoginSessionEnter()
        {
            var session = GetCurrentLoginSession();
            if (session == null)
            {
                return false;
            }
            if (string.Compare(session.User.CompanyID, SystemParams.CompanyID, true) == 0)
            {
                return true;
            }
            if (string.Compare(session.User.CompanyID, CustomerInfo.FORESIGHT, true) == 0)
            {
                return true;
            }
            return CreateClient<UserQueryClient>().CanEnterSite(session.SessionID, SystemParams.CompanyID);
        }

        protected virtual bool ThrowIfNotAllowed { get { return false; } }

        protected virtual bool CanDirectAccess { get { return false; } }

        protected virtual int FeatureID { get { return -1; } }

        protected bool CheckUserToken()
        {
            var session = GetCurrentLoginSession();
            if (session != null)//已经登录
            {
                return true;
            }
            string tkstring = Request.Params["tk"];
            if (string.IsNullOrEmpty(tkstring))
                return false;

            try
            {
                var sc = new FI.FIC.Models.Security.SymmetricCrypt(FI.FIC.Models.Security.CryptType.DES);
                tkstring = sc.Decrypt(tkstring,
                    FI.FIC.DataProviders.ChartDataProvider.DES_Key,
  FI.FIC.DataProviders.ChartDataProvider.DES_IV);

                string[] temps = tkstring.Split('|');
                if (temps.Length != 2)
                    return false;

                string timestring = temps[0];
                DateTime time = DateTime.MinValue;
                if (!DateTime.TryParse(timestring, out time)
                    || time < DateTime.UtcNow.AddMinutes(-5))
                    return false;

                var sessionid = temps[1];
                var c = CreateClient<UserQueryClient>();
                //通过手机SessionID获取新的Web Session
                var newsession = c.GetNewLoginSession(sessionid, APPNAME);
                SetLoginSessionCookie(newsession.SessionID);
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;
        }

        protected bool CheckLoginSession()
        {
            var session = GetCurrentLoginSession();
            if (session == null)
            {
                if (CanDirectAccess)
                    RedirectToLoginPageWithUrl();
                else
                    RedirectToLoginPage();
                return false;
            }
            if (!session.User.AllowLoginIntoPC)
            {
                RedirectToErrorPage();
                return false;
            }
            if (!AllowCurrentLoginSessionEnter(session) || !CheckRight(FeatureID))
            {
                if (ThrowIfNotAllowed)
                {
                    throw new Exception("The user was not allowed to enter this page.");
                }
                else
                {
                    RedirectToErrorPage();
                }
                return false;
            }
            return true;
        }

        protected void RedirectToLoginPageWithUrl()
        {
            string url = Request.Url.ToString();
            url = HttpUtility.UrlEncode(url);
            Response.Redirect(LoginPageUrl + "?f=" + url);
        }

        protected void RedirectToEntryPage()
        {
            var session = GetCurrentLoginSession();
            string entry = GetUserDefaultEntryPageUrl(session.User);
            //if (!user.IsForesightUser)
            //{
            //    string pageurl = UserParams.GetStringParameter(user.UID, "LandingPage");//如果LandingPage没有权限会现成跳转死循环
            //    if (!string.IsNullOrEmpty(pageurl))
            //    {
            //        string url = entry.Substring(0, entry.LastIndexOf('/') + 1);
            //        entry = url + pageurl;
            //    }
            //}
            if (!string.IsNullOrEmpty(entry))
                Response.Redirect(entry, true);
            else
                Response.Redirect(LoginPageUrl, true);
        }

        protected void RedirectToErrorPage()
        {
            var url = Request.Url;
            var addr = string.Format("{0}://{1}:{2}{3}/ErrorPage.aspx?code=403", url.Scheme, url.Host, url.Port, Request.ApplicationPath);
            Response.Redirect(addr, true);
        }

        protected void DoLogout()
        {
            string sid = null;
            try
            {
                var session = GetCurrentLoginSession();
                if (session != null)
                {
                    sid = session.SessionID;
                }
            }
            catch { }
            try
            {
                ClearLoginSessionCookie();
            }
            catch { }
            if (sid != null)
            {
                try
                {
                    CreateClient<Foresight.Fleet.Services.User.UserQueryClient>().LogoutWithSessionID(sid);
                }
                catch
                {
                    // nothing
                }
            }

            //RedirectToLoginPage();
            RedirectToLoginPageAndClearCookie();
        }

        protected void RedirectToLoginPageAndClearCookie()
        {//由于登录站点和Contractor站得Webconfig的sessioncookiedomain配置不一样导致ClearLoginSessionCookie无法清除Sessionid的cookie
            //增加tp=c，在登录页面清除Sessionid的cookie
            Response.Redirect(LoginPageUrl + "?tp=c");
        }

        protected void AddLog(string type, string source, string message, string detail)
        {
            try
            {
                SystemParams.WriteLog(type, source, message, detail);
            }
            catch
            {
                // nothing
            }
        }

        protected string GenerateUrl(string file)
        {
            string url;
            System.Web.UI.Page page = System.Web.HttpContext.Current.Handler as System.Web.UI.Page;
            if (page != null)
            {
                // Use page instance.
                url = page.ResolveUrl("~/") + file;
            }
            else
            {
                // avoid duplicate operation
                url = System.Web.HttpContext.Current.Request.ApplicationPath + "/" + file;
            }
            try
            {
                var path = System.IO.Path.Combine(System.Web.HttpContext.Current.Request.PhysicalApplicationPath, file);
                if (System.IO.File.Exists(path))
                {
                    url += "?t=" + System.IO.File.GetLastWriteTimeUtc(path).Ticks;
                }
            }
            catch (Exception)
            {
                // cant read file
            }
            return url;
        }

        protected byte[] ConvertFile2bytes(HttpPostedFile uploadFile)
        {
            byte[] dataBuffer = new byte[uploadFile.InputStream.Length];
            uploadFile.InputStream.Position = 0;
            uploadFile.InputStream.Read(dataBuffer, 0, dataBuffer.Length);
            uploadFile.InputStream.Close();
            return dataBuffer;
        }

        public virtual string JQueryVersion
        {
            get { return "3.6.0"; }
        }

        protected T CreateClient<T>(string companyid = null) where T : RemoteClientBase
        {
            var session = GetCurrentLoginSession();
            var client = FleetServiceClientHelper.CreateClient<T>(string.IsNullOrEmpty(companyid) ? SystemParams.CompanyID : companyid, session == null ? "" : session.SessionID);
            client.Timeout = 300;
            return client;
        }
        protected bool CheckRight(int featureid)
        {
            if (featureid < 0)
                return true;
            return CheckRight(SystemParams.CompanyID, featureid);
        }

        protected bool CheckRight(string custid, int featureid, Permissions per = Permissions.ReadOnly)
        {
            var user = GetCurrentUser();
            if (user == null)
                return false;

            if (user.UserType == Users.UserTypes.SupperAdmin)
                return true;

            if (user.UserType == Users.UserTypes.Common || user.UserType == Users.UserTypes.Admin)
            {
                var client = FleetServiceClientHelper.CreateClient<PermissionProvider>();
                Tuple<Feature, Permissions>[] pmss = client.GetUserPermissions(custid, user.IID);
                if (pmss.Length > 0)
                {
                    Tuple<Feature, Permissions> permission = pmss.FirstOrDefault(m => m.Item1.Id == featureid);
                    if (permission != null && permission.Item2 >= per)
                        return true;
                }
            }
            return false;
        }

        protected bool CheckReadonly(string custid, int featureid)
        {
            var user = GetCurrentUser();
            if (user == null)
                return false;

            if (user.UserType == Users.UserTypes.SupperAdmin || user.UserType == Users.UserTypes.Admin)
                return false;

            if (user.UserType == Users.UserTypes.Common)
            {
                var client = FleetServiceClientHelper.CreateClient<PermissionProvider>();
                Tuple<Feature, Permissions>[] pmss = client.GetUserPermissions(custid, user.IID);
                if (pmss.Length > 0)
                {
                    Tuple<Feature, Permissions> permission = pmss.FirstOrDefault(m => m.Item1.Id == featureid);
                    if (permission != null && permission.Item2 == Permissions.ReadOnly)
                        return true;
                }
            }
            return false;
        }

        protected bool CanEdit(string custid, int featureid, Permissions per = Permissions.FullControl)
        {
            var user = GetCurrentUser();
            if (user == null)
                return false;

            if (user.UserType == Users.UserTypes.SupperAdmin || user.UserType == Users.UserTypes.Admin)
                return true;

            if (user.UserType == Users.UserTypes.Common)
            {
                var client = FleetServiceClientHelper.CreateClient<PermissionProvider>();
                Tuple<Feature, Permissions>[] pmss = client.GetUserPermissions(custid, user.IID);
                if (pmss.Length > 0)
                {
                    Tuple<Feature, Permissions> permission = pmss.FirstOrDefault(m => m.Item1.Id == featureid);
                    if (permission != null && permission.Item2 >= per)
                        return true;
                }
            }
            return false;
        }
    }
}
