using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Linq;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using Model;
using BLL;


namespace FineUIPro.Web
{
    public partial class _default : PageBase
    {
        #region Page_Init

        private string _menuType = "menu";
        private bool _compactMode = false;
        private string _searchText = "";

        /// <summary>
        /// 菜单模块
        /// </summary>
        public string MenuModule
        {
            get
            {
                return (string)ViewState["MenuModule"];
            }
            set
            {
                ViewState["MenuModule"] = value;
            }
        }

        /// <summary>
        /// 系统菜单路径
        /// </summary>
        public string Url
        {
            get
            {
                return (string)ViewState["Url"];
            }
            set
            {
                ViewState["Url"] = value;
            }
        }
        
        #region Page_Init

        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Init(object sender, EventArgs e)
        {
            this.defaultTitle.Text = Funs.SystemName;
            string themeStr = Request.QueryString["theme"];
            string menuStr = Request.QueryString["menu"];
            string https = ConfigurationManager.AppSettings["Https"];
            if (!String.IsNullOrEmpty(themeStr) || !String.IsNullOrEmpty(menuStr))
            {
                if (!String.IsNullOrEmpty(themeStr))
                {
                    if (themeStr == "bootstrap1")
                    {
                        themeStr = "bootstrap_pure";
                    }
                    HttpCookie cookie = new HttpCookie("Theme_Pro", themeStr);
                    cookie.Expires = DateTime.Now.AddYears(1);
                    if (https == "true")
                    {
                        cookie.Secure = true;
                    }
                    Response.Cookies.Add(cookie);
                }

                if (!String.IsNullOrEmpty(menuStr))
                {
                    HttpCookie cookie = new HttpCookie("MenuStyle_Pro", menuStr);
                    cookie.Expires = DateTime.Now.AddYears(1);
                    if (https == "true")
                    {
                        cookie.Secure = true;
                    }
                    Response.Cookies.Add(cookie);
                }

                PageContext.Redirect("~/default.aspx");
                return;
            }
            ////////////////////////////////////////////////////////////////

            // 从Cookie中读取 - 左侧菜单类型
            HttpCookie menuCookie = Request.Cookies["MenuStyle_Pro"];
            if (menuCookie != null)
            {
                _menuType = menuCookie.Value;
            }

            // 从Cookie中读取 - 是否启用紧凑模式
            HttpCookie menuCompactMode = Request.Cookies["EnableCompactMode_Pro"];
            if (menuCompactMode != null)
            {
                _compactMode = Convert.ToBoolean(menuCompactMode.Value);
            }


            // 从Cookie中读取 - 搜索文本
            HttpCookie searchText = Request.Cookies["SearchText"];
            if (searchText != null)
            {
                _searchText = HttpUtility.UrlDecode(searchText.Value);
            }

            if (!IsPostBack)
            {
                this.MenuModule = BLL.Const.System_1;
                MenuLoad(BLL.Const.System_1, null);
            }
                //// 综合平台显示
                //this.MenuModule = BLL.Const.System_1;
                //if (Request.Params["menuModule"] != null)
                //{
                //    this.MenuModule = Request.Params["menuModule"].ToString();
                //}

                //var systemValue = from x in BLL.DropListService.GetSystemList() where x.Value == MenuModule select x;
                //this.lbTitle.Text = systemValue.First().Text;
                //this.CurrUser.LoginProjectId = Request.Params["projectId"];
                //this.CurrUser.LoginSystemId = this.MenuModule;

                //if (!string.IsNullOrEmpty(this.CurrUser.LoginProjectId))
                //{
                //    var projectName = BLL.Base_ProjectService.GetProjectName(this.CurrUser.LoginProjectId);
                //    if (!string.IsNullOrEmpty(projectName))
                //    {
                //        this.lbTitle.Text = projectName;
                //    }
                //}

                //if (_menuType == "accordion")
                //{
                //    InitAccordionMenu();
                //}
                //else
                //{
                //    InitTreeMenu("0");
                //}

                leftPanel.Title = "系统菜单";
        }

        #endregion

        private void InitSearchBox()
        {
            if (!String.IsNullOrEmpty(_searchText))
            {
                ttbxSearch.Text = _searchText;
                ttbxSearch.ShowTrigger1 = true;
            }
        }

        #region InitAccordionMenu
        private Accordion InitAccordionMenu(string menuModule)
        {
            leftPanel.Items.Clear();
            Accordion accordionMenu = new Accordion();
            accordionMenu.ID = "accordionMenu";
            accordionMenu.EnableFill = false;
            accordionMenu.ShowBorder = false;
            accordionMenu.ShowHeader = false;
            leftPanel.Items.Add(accordionMenu);

            var dt = GetNewMenu("0", menuModule);
            foreach (var dr in dt)
            {
                AccordionPane accordionPane = new AccordionPane();
                accordionPane.Title = dr.MenuName;
                //accordionPane.Layout = Layout.Fit;
                accordionPane.ShowBorder = false;
                accordionPane.BodyPadding = "2px 0 0 0";
                accordionMenu.Items.Add(accordionPane);

                Tree innerTree = new Tree();
                innerTree.ShowBorder = false;
                innerTree.ShowHeader = false;
                innerTree.EnableIcons = true;
                innerTree.AutoScroll = true;
                innerTree.EnableSingleClickExpand = true;
                accordionPane.Items.Add(innerTree);
                
                
                BoundTree(innerTree.Nodes, dr.MenuId, menuModule);
              
            }
           
            return accordionMenu;
        }

 

        /// <summary>
        /// 加载树
        /// </summary>
        /// <param name="nodes"></param>
        /// <param name="menuId"></param>
        private void BoundTree(TreeNodeCollection nodes, string menuId,string menuModule)
        {
            var dt = GetNewMenu(menuId, menuModule);
            if (menuId == "0")
            {
                if (dt.Count() > 0)
                {
                    TreeNode tn = null;
                    foreach (var dr in dt)
                    {
                        tn = new TreeNode();
                        
                        tn.Text = dr.MenuName;
                        tn.NodeID = dr.MenuId;
                        if (this.GetLanguage == "en-US")
                        {
                            tn.Text = dr.MenuEnName;
                        }
                        
                        if (dr.SuperMenu != "0" && !string.IsNullOrEmpty(dr.Url))
                        {
                            tn.NavigateUrl = dr.Url;
                        }
                        nodes.Add(tn);
                        BoundTree(tn.Nodes, dr.MenuId, menuModule);
                    }
                }
            }
            else
            {
                if (dt.Count() > 0)
                {
                    TreeNode tn = null;
                    foreach (var dr in dt)
                    {
                        tn = new TreeNode();
                        tn.Text = dr.MenuName;
                        tn.NodeID = dr.MenuId;
                        if (this.GetLanguage == "en-US")
                        {
                            tn.Text = dr.MenuEnName;
                        }
                        
                        if (dr.SuperMenu != "0" && !string.IsNullOrEmpty(dr.Url))
                        {
                            
                            if (dr.Url.Contains("default.aspx"))
                            {
                               //tn.NavigateUrl=ResolveUrl("~/"+dr.Url);
                            }
                            else
                            {
                                tn.NavigateUrl = dr.Url;
                            }
                        }               
                        nodes.Add(tn);
                        BoundTree(tn.Nodes, dr.MenuId, menuModule);
                    }
                }
            }
        }

        /// <summary>
        /// 我的快捷菜单
        /// </summary>
        /// <param name="nodes"></param>
        /// <param name="userId"></param>
        private void BoundShortCutTree(TreeNodeCollection nodes, string userId, string menuModule)
        {
            var myMenu = from x in Funs.DB.Sys_MyShortcut
                         join y in Funs.DB.Sys_Menu on x.MenuId equals y.MenuId
                         where x.UserId == userId
                         select y;

            if (!String.IsNullOrEmpty(_searchText))
            {
                myMenu = myMenu.Where(x => x.MenuName.Contains(_searchText));
            }

            if (myMenu.Count() > 0)
            {
                TreeNode tn = null;
                foreach (var menu in myMenu)
                {
                    tn = new TreeNode();
                    tn.Text = menu.MenuName;
                    tn.NodeID = menu.MenuId;
                    if (Request.Cookies["SelectLan"] != null)
                    {
                        HttpCookie lanCookie = Request.Cookies["SelectLan"];
                        if (lanCookie["lan"] != null)
                        {
                            if (lanCookie["lan"] == "en-US")
                            {
                                tn.Text = menu.MenuEnName;
                            }
                        }
                    }
                    if (menu.SuperMenu != "0" && !string.IsNullOrEmpty(menu.Url))
                    {
                        tn.NavigateUrl = menu.Url;
                    }
                    nodes.Add(tn);
                    BoundTree(tn.Nodes, menu.MenuId, menuModule);
                }
            }
        }

        private void SearchMenuTree(TreeNodeCollection nodes,string menuModule)
        {
            var menuList = BLL.CommonService.GetMenu(this.CurrUser.UserId, menuModule);
            var searchMenu = from x in Funs.DB.Sys_Menu
                         where x.MenuName.Contains(_searchText) && x.MenuModule == menuModule
                               && (x.Url!=null || x.Url!=string.Empty)
                         select x;
            if (searchMenu.Count() > 0)
            {
                TreeNode tn = null;
                foreach (var menu in searchMenu)
                {
                    if (menuList.Contains(menu))
                    {
                        tn = new TreeNode();
                        tn.Text = menu.MenuName;
                        tn.NodeID = menu.MenuId;
                        if (Request.Cookies["SelectLan"] != null)
                        {
                            HttpCookie lanCookie = Request.Cookies["SelectLan"];
                            if (lanCookie["lan"] != null)
                            {
                                if (lanCookie["lan"] == "en-US")
                                {
                                    tn.Text = menu.MenuEnName;
                                }
                            }
                        }
                        if (menu.SuperMenu != "0" && !string.IsNullOrEmpty(menu.Url))
                        {
                            tn.NavigateUrl = menu.Url;
                        }
                        nodes.Add(tn);
                        BoundTree(tn.Nodes, menu.MenuId, menuModule);
                    }
                }
            }
        }


        #endregion

        #region InitTreeMenu
        private Tree InitTreeMenu(string parentId,string menuModule)
        {
            leftPanel.Items.Clear();
            Tree treeMenu = new Tree();
            treeMenu.ID = "treeMenu";
            treeMenu.ShowBorder = false;
            treeMenu.ShowHeader = false;
            treeMenu.EnableIcons = true;
            treeMenu.AutoScroll = true;
            treeMenu.EnableSingleClickExpand = true;
            leftPanel.Items.Add(treeMenu);
            treeMenu.Nodes.Clear();
            if (menuModule != BLL.Const.System_4)
            {
                if (string.IsNullOrEmpty(_searchText))
                {
                    BoundTree(treeMenu.Nodes, parentId, menuModule);
                }
                else
                {
                    SearchMenuTree(treeMenu.Nodes, menuModule);
                }
            }
            else
            {
                BoundShortCutTree(treeMenu.Nodes, this.CurrUser.UserId, menuModule);
            }
            return treeMenu;
        }

        /// <summary>
        /// 得到菜单方法
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private List<Model.Sys_Menu> GetNewMenu(string parentId, string menuModule)
        {
            List<Model.Sys_Menu> menu = new List<Model.Sys_Menu>();
            var menuList = BLL.CommonService.GetMenu(this.CurrUser.UserId, menuModule);
            if (menuList.Count() > 0)
            {
                menu = menuList.Where(x => x.SuperMenu == parentId).ToList();
            }
            return menu;
        }

        #endregion

        #region 获取用户系统权限
        /// <summary>
        /// 用户ID
        /// </summary>
        /// <param name="userId"></param>
        private void GetUserLoginSystem(string userId)
        {
            var user = BLL.Sys_UserService.GetUsersByUserId(userId);
            this.btnCommon.Visible = false;
            this.btnHjgl.Visible = false;

            if (user != null && user.AllowLoginSystem != null)
            {
                string[] systems = user.AllowLoginSystem.Split('|');

                foreach (string sys in systems)
                {
                    if (sys == BLL.Const.System_2)
                    {
                        btnCommon.Visible = true;
                    }

                    if (sys == BLL.Const.System_3)
                    {

                        btnHjgl.Visible = true;
                    }

                    if (sys == BLL.Const.System_4)
                    {

                        btnMyShortcut.Visible = true;
                    }
                }
            }

        }

      
        #endregion
        #endregion

        #region Page_Load
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitSearchBox();
                InitMenuStyleButton();
                //InitLangMenuButton();

                cbxEnableCompactMode.Checked = _compactMode;
                
                InitOnlineUserCount();
                //this.GetUserLoginSystem(this.CurrUser.UserId);
                this.InitMainPage();

                if (Request.Cookies["SelectLan"] != null)
                {
                    HttpCookie lanCookie = Request.Cookies["SelectLan"];
                    if (lanCookie["lan"] != null)
                    {
                        drpSelectLan.SelectedValue = lanCookie["lan"];
                    }
                }
                //this.btnProjectSet.OnClientClick = "parent.removeActiveTab();";
                //this.btnCommon.OnClientClick = "parent.removeActiveTab();";
                //this.btnHjgl.OnClientClick = "parent.removeActiveTab();";
                //this.btnMyShortcut.OnClientClick = "parent.removeActiveTab();";
            }
        }


        /// <summary>
        /// 根据不同系统加载首页导航界面
        /// </summary>
        private void InitMainPage()
        {
            if (MenuModule == BLL.Const.System_3)
            {
                Tab1.IFrameUrl = "~/common/MainSupervision.aspx";
            }
            else
            {
                Tab1.IFrameUrl = "~/common/mainFullViews.aspx";
            }
        }


        private void InitMenuStyleButton()
        {
            string menuStyleID = "MenuStyleTree";

            HttpCookie menuStyleCookie = Request.Cookies["MenuStyle_Pro"];
            if (menuStyleCookie != null)
            {
                switch (menuStyleCookie.Value)
                {
                    case "menu":
                        menuStyleID = "MenuStyleTree";
                        break;
                    case "accordion":
                        menuStyleID = "MenuStyleAccordion";
                        break;
                }
            }


            SetSelectedMenuID(MenuStyle, menuStyleID);
        }

        private void SetSelectedMenuID(MenuButton menuButton, string selectedMenuID)
        {
            foreach (MenuItem item in menuButton.Menu.Items)
            {
                MenuCheckBox checkBox = (item as MenuCheckBox);
                if (checkBox != null && checkBox.ID == selectedMenuID)
                {
                    checkBox.Checked = true;
                }
                else
                {
                    checkBox.Checked = false;
                }
            }
        }

        #endregion

        private void InitOnlineUserCount()
        {
            //litOnlineUserCount.Text = Application["OnlineUserCount"].ToString();
            liUser.Text = this.CurrUser.UserName;
        }

        protected void btnProjectSet_Click(object sender, EventArgs e)
        {
            string projectId = string.Empty;
            if (Request.Cookies["SelectProject"] != null)
            {
                HttpCookie ProjectCookie = Request.Cookies["SelectProject"];
                //从Cookie里面读取
                projectId = ProjectCookie["projectId"];
            }
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("common/BaseInfo/SelectProject.aspx?projectId=" + projectId, "编辑 - ")));
        }

        protected void btnHjglClick(object sender, EventArgs e)
        {
            if (Request.Cookies["SelectProject"] != null)
            {
                HttpCookie ProjectCookie = Request.Cookies["SelectProject"];
                //bool isLogin = false;
                //从Session或Cookie里面读取
                string projectId = ProjectCookie["projectId"];
                var puser = from x in Funs.DB.Project_User where x.UserId == CurrUser.UserId select x.ProjectId;
                if ((puser.Count() > 0 && puser.ToList().Contains(projectId)) || CurrUser.Account == Const.Gly)
                {
                    this.CurrUser.LoginProjectId = projectId;
                    this.MenuModule = BLL.Const.System_3;
                    MenuLoad(BLL.Const.System_3, projectId);
                }
                else
                {
                    ShowNotify("请选择项目!");
                }
                //var puser = from x in Funs.DB.Project_User
                //            join y in Funs.DB.Base_Project on x.ProjectId equals y.ProjectId
                //            where y.ProjectArea == CurrUser.LoginProjectArea
                //            select x;
                //if (puser.Count() > 0)
                //{
                //    if (CurrUser.Account == Const.Gly && puser.Select(x=>x.ProjectId).Contains(projectId))
                //    {
                //        isLogin = true;
                //    }
                //    else
                //    {
                //        var p = from x in puser where x.UserId == CurrUser.UserId select x.ProjectId;
                //        if (p.Count() > 0 && p.ToList().Contains(projectId))
                //        {
                //            isLogin = true;
                //        }

                //    }

                //    if (isLogin)
                //    {
                //        this.CurrUser.LoginProjectId = projectId;
                //        this.MenuModule = BLL.Const.System_3;
                //        MenuLoad(BLL.Const.System_3, projectId);
                //    }
                //    else
                //    {
                //        ShowNotify("请选择项目!");
                //    }
                //}
                //else
                //{
                //    ShowNotify("请选择项目!");
                //}
                
                //Response.Redirect(ResolveUrl("~/default.aspx?menuModule=3&projectId=" + projectId));
            }
            else
            {
                ShowNotify("请选择项目!");
            } 
        }

        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            this.CurrUser.LoginProjectId = null;
            if (Request.Cookies["SelectProject"] != null)
            {
                HttpCookie ProjectCookie = Request.Cookies["SelectProject"];

                //从Session或Cookie里面读取
                string projectId = ProjectCookie["projectId"];
                this.CurrUser.LoginProjectId = projectId;
                this.MenuModule = BLL.Const.System_3;
                MenuLoad(BLL.Const.System_3, projectId);
                //Response.Redirect(ResolveUrl("~/default.aspx?menuModule=3&projectId=" + projectId));
            }
            else
            {
                ShowNotify("请选择项目!");
            }
        }

        protected void btnCommon_Click(object sender, EventArgs e)
        {
            this.CurrUser.LoginProjectId = null;
            this.MenuModule = BLL.Const.System_2;
            MenuLoad(BLL.Const.System_2, null);
            //Response.Redirect(ResolveUrl("~/default.aspx?menuModule=2"));
        }

        protected void btnMyShortcut_Click(object sender, EventArgs e)
        {
            this.CurrUser.LoginProjectId = null;
            this.MenuModule = BLL.Const.System_4;
            MenuLoad(BLL.Const.System_4, null);
            //Response.Redirect(ResolveUrl("~/default.aspx?menuModule=4"));
        }

        protected void drpSelectLan_SelectedIndexChanged(object sender, EventArgs e)
        {
            string https = ConfigurationManager.AppSettings["Https"];
            HttpCookie lanCookie = Request.Cookies["SelectLan"];
            lanCookie["lan"] = drpSelectLan.SelectedValue;
            lanCookie.Expires = DateTime.Now.AddDays(1);
            if (https == "true")
            {
                lanCookie.Secure = true;
            }
            Response.Cookies.Add(lanCookie);
            //MenuLoad(this.MenuModule, this.CurrUser.LoginProjectId);
            Response.Redirect(Request.UrlReferrer.ToString());//刷新当前页面
        }

        protected void MenuLoad(string menuModule,string projectId)
        {
            string lan = string.Empty;
            if (this.GetLanguage == "en-US")
            {
                lan = "en";
            }
            else
            {
                lan = "zh";
            }
            var systemValue = from x in BLL.DropListService.GetSystemList(lan) where x.Value == menuModule select x;
            this.lbTitle.Text = systemValue.First().Text;
            //if (menuModule == BLL.Const.System_1)
            //{
            //    this.lbTitle.Text = systemValue.First().Text + "-" + GetProjectArea(CurrUser.LoginProjectArea);
            //}
            //else
            //{
            //    this.lbTitle.Text = systemValue.First().Text;
            //}


            if (menuModule == BLL.Const.System_3)
            {
                if (!string.IsNullOrEmpty(projectId))
                {
                    var project = BLL.Base_ProjectService.GetProjectByProjectId(projectId);
                    if (project != null)
                    {
                        if (!string.IsNullOrEmpty(project.ProjectCode))
                        {
                            this.lbTitle.Text = "[" + project.ProjectCode + "]" + project.ProjectName;
                        }
                        else
                        {
                            this.lbTitle.Text = project.ProjectName;
                        }

                        if (this.lbTitle.Text.Length > 48)
                        {
                            this.lbTitle.Text = this.lbTitle.Text.Substring(0, 48) + "...";
                        }
                    }
                }
            }
           
            if (_menuType == "accordion")
            {
                InitAccordionMenu(menuModule);
            }
            else
            {
                InitTreeMenu("0", menuModule);
            }
            InitMainPage();
        }

        //private string GetProjectArea(string id)
        //{
        //    string area = string.Empty;
        //    if (id == "1")
        //    {
        //        area = "烟台";
        //    }
        //    if (id == "2")
        //    {
        //        area = "宁波";
        //    }
        //    if (id == "3")
        //    {
        //        area = "福建";
        //    }
        //    return area;
        //}

    }
}