using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraNavBar;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraTabbedMdi;
using System.Reflection;
//using DeiNiu.wms.Logical;
using DeiNiu.wms.Data;
using DeiNiu.wms.Data.Model;
using DevExpress.LookAndFeel;
using System.Xml;
using System.Runtime.InteropServices;
using DeiNiu.Utils;
using DeiNiu.wms.win.ServiceReferencePortal;
namespace DeiNiu.wms.win
{
    public partial class main : BasicRibbonForm
    {
        [DllImport("kernel32.dll")]
        public static extern Boolean AllocConsole();
        [DllImport("kernel32.dll")]
        public static extern Boolean FreeConsole();  
        public main()
        {
          //  initialConsole();
            InitializeComponent();
         //   InitSkinGallery();
           // UserLookAndFeel.Default.SetSkinStyle(defaultSkinName);
            initialControles();
            showLogin();
         
            
        }
        private void initialConsole(){
            #if DEBUG
                        AllocConsole();
                        Shell.WriteLine("注意:启动程序..."); 
                        Shell.WriteLine("");
            #endif  
        
        }
        private void initialControles()
        {
            this.ribbonControl1.ShowToolbarCustomizeItem = false; // hide top left menu
            this.ribbonControl1.Minimized = true;
            showRibbonEditPage();
            dockPanel1.Options.ShowCloseButton = false;
           // dockPanel1.Visibility = DevExpress.XtraBars.Docking.DockVisibility.AutoHide;
             
        }
        private void showRibbonEditPage()
        {
           int cnt = xtraTabbedMdiManager1.Pages.Count;
            ribbonPageEdit.Visible = xtraTabbedMdiManager1.Pages.Count > 0; //hide editPage when no subform exist.
            ribbonControl1.SelectedPage = ribbonControl1.Pages[0];
        }
         
        private void ribbonControl1_Merge(object sender, DevExpress.XtraBars.Ribbon.RibbonMergeEventArgs e)
        {
            //RibbonControl parentRRibbon = sender as RibbonControl;
            //RibbonControl childRibbon = e.MergedChild;
            //parentRRibbon.StatusBar.MergeStatusBar(childRibbon.StatusBar);
        }
        private void ribbonControl1_UnMerge(object sender, DevExpress.XtraBars.Ribbon.RibbonMergeEventArgs e)
        {
            //RibbonControl parentRRibbon = sender as RibbonControl;
            //parentRRibbon.StatusBar.UnMergeStatusBar();
        }
        private void OpenLink( Form itemForm, string itemHeader)
        {
            //遍历已打开的TabPage,若发现已打开过则不再重复打开并设置为Active
            int itemCount = xtraTabbedMdiManager1.Pages.Count;
            foreach (XtraMdiTabPage itemPage in xtraTabbedMdiManager1.Pages)
            {
                if (itemHeader == itemPage.Text)
                {
                    //MessageBox.Show("the page has been openned");
                    //设置活动Tab Page
                    xtraTabbedMdiManager1.SelectedPage = itemPage;
                    return;
                }
            }
            itemForm.MdiParent = this;
            itemForm.Text = itemHeader;
            itemForm.Show();
            //设置为Active
            xtraTabbedMdiManager1.SelectedPage = xtraTabbedMdiManager1.Pages[itemCount];
        }
        private void navBarControl1_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            String itemHeader = e.Link.Caption;
            //遍历已打开的TabPage,若发现已打开过则不再重复打开并设置为Active
            int itemCount = xtraTabbedMdiManager1.Pages.Count;
            foreach (XtraMdiTabPage itemPage in xtraTabbedMdiManager1.Pages)
            {
                if (itemHeader == itemPage.Text)
                {
                    //MessageBox.Show("the page has been openned");
                    //设置活动Tab Page
                    xtraTabbedMdiManager1.SelectedPage = itemPage;
                    return;
                }
            }
             
            String formName = e.Link.Item.Tag == null ? null : e.Link.Item.Tag.ToString();
            if (formName == null)
            {
                return;
            }
            String fullName = GetType().Namespace + "." + formName;
            Assembly assembly = GetType().Assembly;
            Type type = assembly.GetType(fullName);//AuthorityForm
            Form itemForm = (Form)Activator.CreateInstance(type);
            itemForm.MdiParent = this;
            itemForm.Text = itemHeader;
            itemForm.Show();
            //设置为Active
            xtraTabbedMdiManager1.SelectedPage = xtraTabbedMdiManager1.Pages[itemCount];
            showRibbonEditPage();
             
             dockPanel1.Visibility = DevExpress.XtraBars.Docking.DockVisibility.AutoHide;
            //AddPageMdi(e.Link.Item);
        }
        public void showLogin()
        {
            Login lg = new Login();
            lg.ShowDialog();
            createMenus();
        }
        /// 
        /// 同步erp 信息
        /// 
        private void initailErpData()
        {
            showWaitForm();
            try
            {
                //同步商品信息
                //lWmsGoods lg = new lWmsGoods();
                //lg.getWmsGoods.syncGoods();
                using (ServiceReferenceGoods.GoodsClient client = new ServiceReferenceGoods.GoodsClient())
                {
                     client.syncGoods();
                }
                
            }catch(Exception e){
                showErrorMsg(e.Message);
            }
            closeWaitForm();
        }
        private void createMenus(){
            if (LoginInfo.UserId == 0)
            {
                return;
            }
           //if (Park.currentUser == null) 
           // {
           //     return;
           // }
           this.InitSkinGallery();
            initailErpData();
            this.navBarControl1.BeginUpdate();
            this.navBarControl1.Groups.Clear(); 
         //   LAuthority la = new LAuthority();
         //   Dictionary> auths = la.getCatedAuthorities(Park.currentUser.GetEmployee.ID);
            Dictionary result = null;
            try
            {
                using (PortalClient pclient = new PortalClient())
                {
                    result = pclient.getCatedAuths(LoginInfo.UserId);
                }
            }
            catch (Exception er)
            {
                return;
            }
            foreach (String cate in result.Keys)
            {
                NavBarGroup group1 = new NavBarGroup(cate);
                foreach (string link in result[cate])
                {
                    string[] rs = link.Split(':');
                    if (string.IsNullOrEmpty(rs[0]))
                    {
                        continue;
                    }
                    NavBarItem nbi = new NavBarItem(rs[0]);
                    nbi.Tag = rs[1];
                    group1.ItemLinks.Add(nbi);
                }
                if (group1.ItemLinks.Count > 0)
                {
                    this.navBarControl1.Groups.Add(group1);
                    group1.Expanded = true;
                }
            }
            this.navBarControl1.EndUpdate();
            this.navBarControl1.LinkClicked += new NavBarLinkEventHandler(navBarControl1_LinkClicked);
            showRibbonEditPage();
            /*
            List auths =   la.getAuthorities(Park.currentUser.GetEmployee.ID);
            foreach (Authority auth in auths)
            {
                if (auth.auth_uplevel == 0) //category
                {
                    NavBarGroup group1 = new NavBarGroup(auth.auth_name);
                    this.navBarControl1.Groups.Add(group1);
                    group1.Expanded = true;
                    foreach (Authority link in auths)
                    {
                        if (link.auth_uplevel == auth.ID)
                        {
                            NavBarItem nbi = new NavBarItem(link.auth_name);
                            nbi.Tag = link.auth_class;
                            group1.ItemLinks.Add(nbi);
                        }
                    }
                }
            }
            */
        
        }
        /**
         * clear mdi,close forms
         * 
         */ 
        private void doClear()
        {
            xtraTabbedMdiManager1.Pages.Clear();
        }
        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            doClear();
            showLogin();
        }
        private void xtraTabbedMdiManager1_PageRemoved(object sender, MdiTabPageEventArgs e)
        {
            showRibbonEditPage();
        }
        private void dockPanel1_ClosingPanel(object sender, DevExpress.XtraBars.Docking.DockPanelCancelEventArgs e)
        {
            dockPanel1.Visibility = DevExpress.XtraBars.Docking.DockVisibility.AutoHide;
        }
        private void dockPanel1_Collapsed(object sender, DevExpress.XtraBars.Docking.DockPanelEventArgs e)
        {
            dockPanel1.Visibility = DevExpress.XtraBars.Docking.DockVisibility.AutoHide;
        }
        private void dockPanel1_VisibilityChanged(object sender, DevExpress.XtraBars.Docking.VisibilityChangedEventArgs e)
        {
            if (dockPanel1.Visibility == DevExpress.XtraBars.Docking.DockVisibility.Hidden)
            {
                dockPanel1.Visibility = DevExpress.XtraBars.Docking.DockVisibility.AutoHide;
            }
        }
        ///   
        /// 与控制台交互  
        ///   
        static class Shell
        {
            ///   
            /// 输出信息  
            ///   
            ///   
            ///   
            public static void WriteLine(string format, params object[] args)
            {
                WriteLine(string.Format(format, args));
            }
            ///   
            /// 输出信息  
            ///   
            ///   
            public static void WriteLine(string output)
            {
                Console.ForegroundColor = GetConsoleColor(output);
                Console.WriteLine(@"[{0}]{1}", DateTimeOffset.Now, output);
            }
            ///   
            /// 根据输出文本选择控制台文字颜色  
            ///   
            ///   
            ///   
            private static ConsoleColor GetConsoleColor(string output)
            {
                if (output.StartsWith("警告")) return ConsoleColor.Yellow;
                if (output.StartsWith("错误")) return ConsoleColor.Red;
                if (output.StartsWith("注意")) return ConsoleColor.Green;
                return ConsoleColor.Gray;
            }
        }  
        //private void xtraTabbedMdiManager1_FloatMDIChildActivated(object sender, EventArgs e)
        //{
            
        //}
        //private void xtraTabbedMdiManager1_SelectedPageChanged(object sender, EventArgs e)
        //{
        //    //RibbonControl subRibbon = ((basicRibbonForm)xtraTabbedMdiManager1.SelectedPage.MdiChild).getRibbon();
        //    //this.ribbonControl1.MergeRibbon(subRibbon);
        //}
         #region 皮肤
        //初始化皮肤
       string defaultSkinName = "Summer Tag";
        void InitSkinGallery()
        {
            DevExpress.XtraEditors.WindowsFormsSettings.DefaultFont = new Font("黑体 常规", 12);
           // gallerySkins.Manager = barManager1;
          //  DevExpress.XtraBars.Helpers.SkinHelper.InitSkinGalleryDropDown(gallerySkins, true);
          //  CheckFile();//检查文件
          //  GetXmlSkin();//获取xml主题  
           // UserLookAndFeel.Default.SetSkinStyle("DevExpress Style"); 
            if (!string.IsNullOrEmpty(LoginInfo.Theme))
            {
                defaultSkinName = LoginInfo.Theme;
               // defaultSkinName = "Summer 2008";
            }
            DevExpress.UserSkins.BonusSkins.Register();
            DevExpress.Skins.SkinManager.EnableFormSkins();
            //This set the style to use skin technology
            DevExpress.LookAndFeel.UserLookAndFeel.Default.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Skin;
            if (!string.IsNullOrEmpty(defaultSkinName))
            {
                UserLookAndFeel.Default.SetSkinStyle(defaultSkinName);//设置主题样式
            }
        }
        /*
        //检查是否有皮肤名称的xml配置文件    
        public void CheckFile()
        {
            try
            {
                if (System.IO.File.Exists("SkinInfo.xml") == false)
                {
                    CreateXml();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        // 创建XML文件
        public void CreateXml()
        {
            XmlDocument doc = new XmlDocument(); //建立xml定义声明
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.AppendChild(dec);
            XmlElement root = doc.CreateElement("SetSkin"); //创建根节点
            XmlElement rootone = doc.CreateElement("Skinstring");//皮肤
            doc.AppendChild(root);//将one,two,插入到root节点下
            root.AppendChild(rootone);
            doc.Save("SkinInfo.xml");//保存皮肤名称文件为xml格式
        }
        //读取Xml节点内容
        public void GetXmlSkin()
        {
            try
            {
                XmlDocument mydoc = new XmlDocument();
                mydoc.Load("SkinInfo.xml");//从xml文件中提取皮肤名称
                XmlNode ressNode = mydoc.SelectSingleNode("SetSkin");//头和尾
                defaultSkinName = ressNode.SelectSingleNode("Skinstring").InnerText;//把提取出来的皮肤名称存到defaultSkinName中
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
     
        */
 
        private void skinRibbonGalleryBarItem1_Gallery_ItemClick(object sender, GalleryItemClickEventArgs e)
        {
        
            if (skinRibbonGalleryBarItem1.Gallery == null)
            {
                return;
            }
            try
            {
                showWaitForm();
                
                /*
                XmlDocument doc = new XmlDocument();
                doc.Load("SkinInfo.xml");
                XmlNodeList nodelist = doc.SelectSingleNode("SetSkin").ChildNodes;
                foreach (XmlNode node in nodelist)
                {
                    XmlElement xe = (XmlElement)node;//将子节点类型转换为XmlElement类型 
                    if (xe.Name == "Skinstring")
                    {
                        xe.InnerText = skinRibbonGalleryBarItem1.Gallery.GetCheckedItems()[0].Caption;//主题的描述,保存所选的主题名称,参见GetCheckedItems()[0]函数的解释,主要用这个函数提取皮肤名称
                    }
                }
                doc.Save("SkinInfo.xml");
                */
                if (LoginInfo.UserId >0)
                {
                    string tag = skinRibbonGalleryBarItem1.Gallery.GetCheckedItems()[0].Tag.ToString();//caption;
                    string caption = skinRibbonGalleryBarItem1.Gallery.GetCheckedItems()[0].Caption;
                    try
                    {
                        using (PortalClient pclient = new PortalClient())
                        {
                           pclient.updateUserTheme(LoginInfo.UserId,skinRibbonGalleryBarItem1.Gallery.GetCheckedItems()[0].Tag.ToString());
                        }
                    }
                    catch  
                    {
                        return;
                    }
                    //Park.currentUser.GetEmployee.em_profile = skinRibbonGalleryBarItem1.Gallery.GetCheckedItems()[0].Tag.ToString();//caption;
                    //Park.currentUser.GetEmployee.Update();
                
                }
              //  System.Threading.Thread.CurrentThread.Join(10);
            }
            catch (Exception er)
            {
                DeiNiu.Utils.LogHelper.WriteLog(typeof(main), er);
            }
            finally
            {
                closeWaitForm();
            }
        }   
      #endregion
        private void main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("真的要退出程序吗?", "退出程序", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                e.Cancel = true;
            }         
        }
        private void main_FormClosed(object sender, FormClosedEventArgs e)
        {
            showWaitForm();
            System.Environment.Exit(0); 
        }
    }   
     
}