using System;
using System.Collections;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using DeiNiu.wms.Logical;
namespace ajax
{
    public partial class DeiNiuMasterPage : System.Web.UI.MasterPage
    {
        public LEmployee lem; 
        protected void Page_Load(object sender, EventArgs e)
        { 
            if (!string.IsNullOrEmpty(Request.QueryString["___command"]))
            {
                string cmd = Request.QueryString["___command"];
                if (cmd == "ClearSession")
                {
                    if ((Session["CurrentUser"] != null))
                    { 
                     
                       if( System.Configuration.ConfigurationManager.AppSettings["sessionstate"] != "InProc")
                           if (Session["CurrentUserId"] != null)
                        {
                        //   ((ArrayList)Application["userlst"]).Remove(Session["CurrentUserAccount"].ToString());
                            DeiNiu.RequestLog logobj = new DeiNiu.RequestLog();
                            logobj.LogoutLog(int.Parse(Session["CurrentUserId"].ToString()));
                        }
                    }  
                    Session.Abandon(); //清空Session, all sessions will be clear ? no kiding, it will obsolete the current session.
                }
            }
            //页面不允许返回操作。
            Response.Buffer = true;
            Response.ExpiresAbsolute = DateTime.Now.AddMinutes(-1);
            Response.Expires = 0;
            Response.CacheControl = "no-cache";
            try
            {
             //   if (Session["CurrentUser"] != null)
                    InitializeUserUi();
            }catch(Exception){}
           
        }
        /// 
        /// 当前用户有没有登录
        /// 
        void ShowLogin()
        {
          //  login.Visible = lem == null;
            lbWelcome.Text =  lem != null  ? "欢迎您:" + lem.GetEmployee.em_name +",": "";
            lkbtnLogin.Text = lem != null ? "退出" : "登录";
           // lkIndex.Visible = lem != null;
            divAuhtority.Visible = lem != null;
            lkDesktop.Visible = lem != null;
            leftMenu.Visible = lem!=null;
            lkkanban.Visible = lem != null;
             ImageBtnHelp.Visible = leftMenu.Visible;
        }
 
        /// 
        /// 根据用户权限,初始化用户界面,菜单等
        /// 
        public void InitializeUserUi()
        { 
            lem = (LEmployee)Session["CurrentUser"];
            if (lem != null) setTree(); else treeMenu.Nodes.Clear();  
            ShowLogin();
           
           
        }
        public UpdatePanel UpdatePanelMaster
        {
            get
            {
                return UpdatePanel1;
            }
        }
        /// 
        /// 构建普通权限列表
        /// 
        private void setTree()
        {
            treeMenu.Nodes.Clear();
            BindAuthTree2("0", null, new LAuthority().getAllActiveData().Tables[0].DefaultView);
            if (lem != null)
            {
             // if( lem.GetEmployee.em_account !="Root") 
                
                {
                    ArrayList al = new LRoleAuthority().GetPublicAuthorityList();
                     
                   removeUnAuthoritedMenu(lem.AuthList ,al ,treeMenu.Nodes);
                }
            }
            /* else
        {
            BindAuthTree2("0", null, new LRoleAuthority().GetPublicAuthorityTable().DefaultView);
        }*/
        }
        void removeUnAuthoritedMenu(ArrayList toKeepAuthority,ArrayList toKeepPublic, TreeNodeCollection nd)
        {
           // foreach (TreeNode node in nd)
            for (int i = 0; i < nd.Count;i++ )
            {
                TreeNode node = nd[i];
          //      foreach (TreeNode cnd in node.ChildNodes)
                for (int j = 0; j < node.ChildNodes.Count; j++)
                {
                    TreeNode cnd = node.ChildNodes[j];
                    if (cnd.ChildNodes.Count > 0)
                    {
                        removeUnAuthoritedMenu(toKeepAuthority, toKeepPublic,cnd.ChildNodes);
                    }
                    else
                        if (string.IsNullOrEmpty(cnd.NavigateUrl) || lem.GetEmployee.em_account !="Root" && !(toKeepAuthority.Contains(cnd.NavigateUrl.ToUpper()) || toKeepPublic.Contains(cnd.NavigateUrl.ToUpper())))
                        {
                            node.ChildNodes.Remove(cnd);
                            j--;
                        }
                }
                if (node.ChildNodes.Count == 0)
                {
                    nd.Remove(node);
                    i--;
                }
            }
        }
   
        public void BindAuthTree2(string id, TreeNode pNode, DataView dv)
        {
            dv.RowFilter = "auth_uplevel = '" + id + "' and auth_publicinfomation=0";
            foreach (DataRowView row in dv)
            {
                TreeNode node = new TreeNode();
                string authLink = row["auth_link"].ToString();
                node.Value = row["ID"].ToString();
                node.Expanded = true;
                if (authLink == string.Empty || authLink.Trim().Length < 6) //not *.aspx
                {
                    node.Text = "" + row["auth_name"] + "";
                    node.SelectAction = TreeNodeSelectAction.None;
                    node.ShowCheckBox = false;
                }
                else
                {
                    node.Text = row["auth_name"].ToString();
                    node.NavigateUrl = authLink;
                }
                if (pNode == null)
                    //说明是根节点
                {
                    treeMenu.Nodes.Add(node);
                }
                else
                {
                    pNode.ChildNodes.Add(node);
                }
                BindAuthTree2(node.Value, node, new DataView(dv.Table));
            }
        }
        public void BindAuthTree(string id, TreeNode pNode, DataView dv)
        {
            dv.RowFilter = "auth_uplevel = '" + id + "'";
            foreach (DataRowView row in dv)
            {
                TreeNode node;
                string authLink = row["auth_link"].ToString();
           
           
                if (authLink == string.Empty || authLink.Trim().Length < 6) //not *.aspx
                {
                    //  node = new TreeNode("" + row["auth_name"] + "",  row["ID"].ToString()  ,"","","");
                    node = new TreeNode();
                    node.Text = "" + row["auth_name"] + "";
                    node.Value = row["ID"].ToString(); 
                }
                else
                {
                    node = new TreeNode(row["auth_name"].ToString(), row["ID"].ToString(), "", authLink, "");
                }
                node.Expanded = true;
                if (pNode == null)
                    //说明是根节点
                {
                    treeMenu.Nodes.Add(node);
                }
                else
                {
                    pNode.ChildNodes.Add(node);
                }
                BindAuthTree(node.Value, node, new DataView(dv.Table));
            }
        }
     
   
    
        void Login()
        {
            if (Session["CurrentUser"]==null) //not login
            { 
                
                Response.Redirect("~/login.aspx");
            }
            else
            { 
                ((ArrayList)Application["userlst"]).Remove(lem.GetEmployee.em_account);
                DeiNiu.RequestLog logobj = new DeiNiu.RequestLog();
                logobj.LogoutLog(int.Parse(Session["CurrentUserId"].ToString()));
              
                Application["usercnt"] = Convert.ToInt32(Application["usercnt"].ToString()) - 1;
              
                Session.RemoveAll();
                Session.Abandon();
                Response.Redirect("~/login.aspx");
            }
         
  
        }
        protected void lkbtnLogin_Click(object sender, EventArgs e)
        {
            Login();
         
        }
        public ScriptManager ScriptMgr 
        {
            get
            {
                return this.ScriptManager1;
            }
        }
        protected void lkIndex_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/index.aspx");
        }
        protected void lkDesktop_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/desktop.aspx");
        }
        protected void lklogin_Click(object sender, EventArgs e)
        {
            Login();
        }
        protected void LinkHelp_Click(object sender, EventArgs e)
        {
        
        }
        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            string requestPage = Request.AppRelativeCurrentExecutionFilePath;
 
             string helpDoc =  Request.ApplicationPath+ "/ug/"+ requestPage.Substring(2, requestPage.IndexOf(".aspx")-2)+".html";
          //  string helpDoc = siteName + requestPage.Substring(2, requestPage.IndexOf(".aspx") - 2) + ".html";
        //    if (!System.IO.File.Exists(Server.MapPath(helpDoc)))
            //        helpDoc = siteName+ "/nohelpdoc.html"; //        helpDoc =  Request.ApplicationPath+ "/ug/nohelpdoc.html";
            
            string newWindow = "openwin('" + helpDoc + "');";
            ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "alert", newWindow, true);
        }
        protected void lkkanban_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/wms/Charts.aspx");
        }
}
}