using BLL;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.UI;
using static FineUIPro.Web.CQMS.Performance.Performance;
using AspNet = System.Web.UI.WebControls;
namespace FineUIPro.Web
{
    //必须要修改form传过来的F_STATE,否则加了__hook的base64编码无效识别
    public static class GlobalValues
    {
        public static PropertyInfo NameObjectCollectionBaseIsReadOnly;
        static GlobalValues()
        {
            Type type = typeof(NameObjectCollectionBase);
            NameObjectCollectionBaseIsReadOnly = type.GetProperty(
                "IsReadOnly",
                BindingFlags.Instance | BindingFlags.NonPublic);
        }
    }
    public class PageBase : System.Web.UI.Page
    {
        protected override void OnPreRenderComplete(EventArgs e)
        {
            base.OnPreRenderComplete(e);
            foreach (var t in Assembly.GetAssembly(this.GetType()).GetTypes())
            {
                if (t.IsSubclassOf(typeof(PageBase)))
                {
                    var fi = t.GetField("mainFrame", BindingFlags.NonPublic | BindingFlags.Instance);
                    if (fi != null)
                    {
                        var f = fi.GetValue(this) as System.Web.UI.HtmlControls.HtmlForm;
                        if (f != null)
                        {
                            Label l = new Label
                            {
                                Text = ""
                            };
                            f.Controls.Add(l);
                        }
                    }
                }
            }
        }
        ///  
        /// 当前登录人信息。
        /// 
        public Model.Sys_User CurrUser
        {
            get
            {
                if (Session["CurrUser"] == null)
                {
                    string account = string.Empty;
                    string password = string.Empty;
                    if (Request.Cookies["u"] != null)
                    {
                        account = HttpUtility.UrlDecode(Request.Cookies["u"].Value);
                    }
                    if (Request.Cookies["p"] != null)
                    {
                        password = Request.Cookies["p"].Value;
                    }
                    Session["CurrUser"] = BLL.Funs.DB.Sys_User.FirstOrDefault(x => x.Account == account && x.Password == Funs.EncryptionPassword(password));
                }
                return (Model.Sys_User)Session["CurrUser"];
            }
        }
        protected override void OnPreInit(EventArgs e)
        {
            //增加修改权限 
            GlobalValues.NameObjectCollectionBaseIsReadOnly.SetValue(Request.QueryString, false, null);
            GlobalValues.NameObjectCollectionBaseIsReadOnly.SetValue(Request.Form, false, null);
            //修复__hook头标识
            if (Request.Form["F_STATE"] != null)
            {
                var fs = Request.Form["F_STATE"];
                if (fs.StartsWith("__hook"))
                {
                    fs = fs.Substring(6);
                    Request.Form["F_STATE"] = fs;
                }
            }
        }
        #region OnInit
        protected override void OnInit(EventArgs e)
        {
            string url = HttpContext.Current.Request.Path;
            string a = Request.ServerVariables["HTTP_REFERER"];
            string Referer = Request.Headers["Referer"];
            if (a == null)
            {
                bool IsDataShowPage = ConstValue.drpConstItemList(ConstValue.Group_InterfacePopup).FirstOrDefault(x => url.Contains(x.ConstValue)) != null;
                bool IsSafeReferer = ConstValue.drpConstItemList(ConstValue.Group_SafeReferer).FirstOrDefault(x => x.ConstValue == url) != null;
                if (!IsDataShowPage && !IsSafeReferer)
                {
                    if (this.Page.Request.AppRelativeCurrentExecutionFilePath != "~/Login.aspx")
                        Response.Redirect("~/Login.aspx");
                    return;
                }
            }
            var pm = PageManager.Instance;
            if (pm != null)
            {
                HttpCookie themeCookie = Request.Cookies["Theme"];
                if (themeCookie != null)
                {
                    string themeValue = themeCookie.Value;
                    if (themeValue != "Cupertino")
                    {
                        themeValue = "Cupertino";
                        Response.Cookies.Remove("Theme");
                        HttpCookie cookie = new HttpCookie("Theme", themeValue)
                        {
                            Expires = DateTime.Now.AddYears(1)
                        };
                        Response.Cookies.Add(cookie);
                    }
                    // 是否为内置主题
                    if (IsSystemTheme(themeValue))
                    {
                        pm.CustomTheme = String.Empty;
                        pm.Theme = (Theme)Enum.Parse(typeof(Theme), themeValue, true);
                    }
                    else
                    {
                        pm.CustomTheme = themeValue;
                    }
                }
                HttpCookie langCookie = Request.Cookies["Language"];
                if (langCookie != null)
                {
                    string langValue = langCookie.Value;
                    try
                    {
                        // 是否为内置语言
                        pm.Language = (Language)Enum.Parse(typeof(Language), langValue, true);
                    }
                    catch (Exception)
                    {
                        pm.CustomLanguage = langValue;
                    }
                }
                // 1. 仅显示基础版示例, 2. 基础版 
                // 上述两种情况都要禁用EnableAnimation、DisplayMode、MobileAdaption
                bool showOnlyBase = false;
                HttpCookie menuShowOnlyBase = Request.Cookies["ShowOnlyBase"];
                if (menuShowOnlyBase != null)
                {
                    showOnlyBase = Convert.ToBoolean(menuShowOnlyBase.Value);
                }
                if (showOnlyBase || Constants.IS_BASE)
                {
                    pm.EnableAnimation = false;
                    pm.DisplayMode = DisplayMode.Normal;
                    pm.MobileAdaption = false;
                }
                else
                {
                    HttpCookie modeCookie = Request.Cookies["DisplayMode"];
                    if (modeCookie != null)
                    {
                        string modeValue = modeCookie.Value;
                        try
                        {
                            pm.DisplayMode = (DisplayMode)Enum.Parse(typeof(DisplayMode), modeValue, true);
                        }
                        catch (Exception)
                        {
                            pm.DisplayMode = DisplayMode.Normal;
                        }
                    }
                }
                HttpCookie loadingCookie = Request.Cookies["Loading"];
                if (loadingCookie != null)
                {
                    int loadingNumber = Convert.ToInt32(loadingCookie.Value);
                    pm.LoadingImageNumber = loadingNumber;
                }
                // SaveFStateToServer是页面上自定义的一个属性
                if (SaveFStateToServer)
                {
                    //// FState保存到服务器文件
                    //pm.EnableFStatePersistence = true;
                    //pm.LoadFStateFromPersistenceMedium = LoadFStateFromPersistenceMedium;
                    //pm.SaveFStateToPersistenceMedium = SaveFStateToPersistenceMedium;
                    //FState保存到服务器缓存
                    pm.EnableFStatePersistence = true;
                    pm.LoadFStateFromPersistenceMedium = LoadFStateFromPersistenceMedium_Cache;
                    pm.SaveFStateToPersistenceMedium = SaveFStateToPersistenceMedium_Cache;
                }
                // 为所有页面添加公共CSS:
                System.Web.UI.HtmlControls.HtmlGenericControl linkCtrl = new System.Web.UI.HtmlControls.HtmlGenericControl("link");
                linkCtrl.Attributes["rel"] = "stylesheet";
                linkCtrl.Attributes["type"] = "text/css";
                linkCtrl.Attributes["href"] = ResolveClientUrl("~/res/css/common.css?v" + GlobalConfig.ProductVersion);
                Header.Controls.AddAt(GetHeadStyleCSSIndex(), linkCtrl);
                // 为所有页面添加公共JS:
                var commonJSPath = String.Format("", ResolveClientUrl("~/res/js/common.js?v" + GlobalConfig.ProductVersion));
                PageContext.RegisterStartupScript("FineUIPro_Examples_common_js", commonJSPath, false);
                //var jqueryMigrateJSPath = String.Format("", ResolveClientUrl("~/res/js/jquery-migrate-3.0.1.js?v" + GlobalConfig.ProductVersion));
                //PageContext.RegisterPreStartupScript("FineUIPro_Examples_jquery-migrate_js", jqueryMigrateJSPath, false);
                // 禁用表单的自动完成功能
                // v5.4.0 - 无需手工设置,每个表单字段的autoComplete默认为false
                //Form.Attributes["autocomplete"] = "off";
            }
            this.Load += new EventHandler(this.PageBase_Load);
            this.Unload += new EventHandler(this.PageBase_UNLoad);
            base.OnInit(e);
        }
        /// 
        /// 页面登录成功
        /// 
        /// 
        /// 
        protected void PageBase_Load(object sender, EventArgs e)
        {
            //这是后置式的权限管理策略.
            //页面装载完成以后才检查是否有权限打开此页....
            //anyway,its ok.
            this.Title = BLL.Funs.SystemName;
            //if (CurrUser == null)
            //{
            //    if (this.Page.Request.AppRelativeCurrentExecutionFilePath != "~/Login.aspx")
            //        Response.Redirect("~/Login.aspx");
            //}
        }
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            //var u = Request.ApplicationPath.TrimStart('/');
            //u=u.TrimEnd('/');
            //if (!string.IsNullOrEmpty(u)) { u = "/" + u; }
            //try
            //{
            //    MainForm.InnerHtml += "";
            //}
            //catch { }
        }
        /// 
        /// UNLOAD事件,发生在页面装载顺序的最后。
        /// 在这里处理的是DBLIST,数据库连接字典。
        /// 
        /// S
        /// E
        protected void PageBase_UNLoad(object sender, EventArgs e)
        {
            if (BLL.Funs.DBList.ContainsKey(System.Threading.Thread.CurrentThread.ManagedThreadId))
            {
                BLL.Funs.DBList.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId);
            }
            if (BLL.SQLHelper.GetConn().State == ConnectionState.Open)
            {
                BLL.SQLHelper.GetConn().Close();
            }
        }
        private bool IsSystemTheme(string themeName)
        {
            themeName = themeName.ToLower();
            string[] themes = Enum.GetNames(typeof(Theme));
            foreach (string theme in themes)
            {
                if (theme.ToLower() == themeName)
                {
                    return true;
                }
            }
            return false;
        }
        private int GetHeadStyleCSSIndex()
        {
            var theIndex = 0;
            for (var i = 0; i < Header.Controls.Count; i++)
            {
                var ctrl = Header.Controls[i];
                if (ctrl is LiteralControl)
                {
                    if ((ctrl as LiteralControl).Text.Trim().ToLower().StartsWith("