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 Microsoft.Data.ConnectionUI;
using System.Data.SqlClient;
using DeiNiu.Utils;
using System.Configuration;
using DevExpress.LookAndFeel;
using System.Xml;
using System.Runtime.InteropServices;
using DeiNiu.Utils;
using DeiNiu.wms.win.utils;
 
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();
            if (!validSn())
            {
                showErrorMsg("程序已过期");
                return;
            }
            showWaitForm();
            showLogin();
            closeWaitForm();
         
            
        }
        private bool validSn()
        {
            DateTime dt =   DateTime.Now;
            DateTime endate = new DateTime(2020, 09, 1);
         //  DateTime endate2 = new DateTime(2019, 8, 1);
            int resut =DateTime.Compare(dt, endate);
          //  int resut2 = DateTime.Compare(dt, endate2);
         //   TimeSpan ts = endate.Subtract(dt);
         //   int day = ts.Days;
           //   ts = endate2.Subtract(dt);
          //    day = ts.Days;
            return resut < 0;
        }
        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;
            this.WindowState = FormWindowState.Maximized; 
        }
        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 (string.IsNullOrEmpty(formName))
            {
                return;
            }
            showWaitForm();
            String fullName = GetType().Namespace + "." + formName;
            Assembly assembly = GetType().Assembly;
            Type type = assembly.GetType(fullName);//AuthorityForm
            if (type == null)
            {
                closeWaitForm();
                showErrorMsg(e.Link.Item.Name + "窗体打开失败");
                return;
            }
            Form itemForm = (Form)Activator.CreateInstance(type);
            itemForm.MdiParent = this;
            itemForm.Text = itemHeader;
            itemForm.Show();
            closeWaitForm();
            //设置为Active
            xtraTabbedMdiManager1.SelectedPage = xtraTabbedMdiManager1.Pages[itemCount];
            showRibbonEditPage();
             
             dockPanel1.Visibility = DevExpress.XtraBars.Docking.DockVisibility.AutoHide;
            //AddPageMdi(e.Link.Item);
        }
        private new void showLogin()
        {   
            createMenus();
          
        }
        /// 
        /// 同步erp 信息
        /// 
        private void initailErpData()
        {
        
 
             
        }
        private void createMenus(){
            this.navBarControl1.BeginUpdate();
            this.navBarControl1.Groups.Clear();
            //   LAuthority la = new LAuthority();
            //   Dictionary> auths = la.getCatedAuthorities(Park.currentUser.GetEmployee.ID);
            Dictionary result = new Dictionary();
           // string[] locations ={"货位设置:LocationmgrForm"};
            string[] lights = { "波次亮灯:GoodsOutForm" ,"货位设置:LocationmgrForm"};
            result["摘果拣选"] = lights;
          //   result["货位设置"] = locations;
            result["二次分播"] = new string[] { 
                "播种设置:DeskCustomer",
                "任务控制:SeedsImport",
                "分播操作:SeedsOut" 
               // ,"播种服务:LightSeviceHostForm",
               // "服务测试:LightSeviceTestForm" 
            };
           
           
#if DEBUG 
            result["测试服务"] = new string[] { 
                "播种服务:LightSeviceHostForm",
                "服务测试:LightSeviceTestForm" 
            };  
          //  result["硬件测试"] = new string[] {"测试工具:basicFuncs" };  
#endif
            int i = 0;
            foreach (String cate in result.Keys)
            {
                i++;
                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);
                } 
                this.navBarControl1.Groups.Add(group1);
                if (group1.ItemLinks.Count > 0 && i>1)
                {
                  
                    group1.Expanded = true;
                }
            }
            this.navBarControl1.EndUpdate();
            this.navBarControl1.LinkClicked += new NavBarLinkEventHandler(navBarControl1_LinkClicked);
            showRibbonEditPage();
        }
        /**
         * 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 = "Blue";
        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);//设置主题样式
                return;
            }
            UserLookAndFeel.Default.SetSkinStyle("Blue");//设置主题样式
        }
         
        //检查是否有皮肤名称的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].Tag.ToString();//主题的描述,保存所选的主题名称,参见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;
                    
                    //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); 
        }
        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (MessageBox.Show("真的要退出程序吗?", "退出程序", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }         
            showWaitForm();
            System.Environment.Exit(0); 
        }
        private void skinRibbonGalleryBarItem1_Gallery_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
        }
        private void btnConn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            openConnectionWindow();
        }
        private void openConnectionWindow()
        {
            DataConnectionDialog dialog = new DataConnectionDialog();
            String conn =System.Configuration.ConfigurationManager.AppSettings["SqlConnWMS"];
            
            dialog.DataSources.Clear();
            /*
             #region//mdb
              dialog.DataSources.Add(DataSource.AccessDataSource);
             dialog.SelectedDataProvider = DataProvider.OleDBDataProvider;
             dialog.SelectedDataSource = DataSource.AccessDataSource;
             #endregion
             */
            #region //Sql Server
            dialog.DataSources.Add(DataSource.SqlDataSource);//Sql Server
            dialog.SelectedDataSource = DataSource.SqlDataSource;
            dialog.SelectedDataProvider = DataProvider.SqlDataProvider;
            #endregion
             dialog.ConnectionString = conn;
            
            /*
            #region//Oracle
            dialog.DataSources.Add(DataSource.OdbcDataSource);
            dialog.SelectedDataSource = DataSource.OracleDataSource;
            dialog.SetSelectedDataProvider = DataProvider.OracleDataProvider;
            #endregion
            */
            if (DataConnectionDialog.Show(dialog) == DialogResult.OK)
            {
                if (!String.IsNullOrEmpty(conn) && conn.Equals(dialog.ConnectionString))
                {
                    return;
                }
                try
                {
                    // string strCom = " SELECT * FROM JQ_Info";
                    ////创建一个 DataSet对象   
                    DataSet ds = new DataSet();
                    //#region//(1)连接mdb
                    //OleDbConnection dbConn = new OleDbConnection(dialog.ConnectionString);
                    //dbConn.Open();
                    //OleDbDataAdapter dbAdapter = new OleDbDataAdapter(strCom, dbConn);
                    //dbAdapter.Fill(ds);
                    //dbConn.Close();
                    //#endregion
                    #region//(2)连接Sql Server
                    String connString = dialog.ConnectionString +";Pooling=true;Max Pool Size = 300; Min Pool Size=0; Connection Lifetime = 300;packet size=1000 ";
                    SqlConnection sqlConn = new SqlConnection(connString);
                    sqlConn.Open();
                    sqlConn.Close();
                    WriteConfig("SqlConnWMS",connString);
                    WmsConstants.SQL_CONN_WMS = connString;
                    #endregion
                    MessageBox.Show("连接数据库成功。", "成功");
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("连接数据库发生错误:" + ex.Message, "错误!");
                    openConnectionWindow();
                }
                finally
                {
                }
            }
        }
       
        
    }   
     
}