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;
using System.ServiceModel; 
using System.ServiceModel.Description;
using System.Net;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Threading;
using elelab;
using dn_wms;
using Model;
using System.Deployment.Application;
using DeiNiu.wms.Data.Model;
using Newtonsoft.Json;
using System.Timers;
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();
        bool isPending = false;
        public enumOnlineStatus validStatus = enumOnlineStatus.试用;
        public string jsonOnline;
        public WcfOnline wonline;
        int maxLoop = 30*24;//最大30天试用期
        string vcnt = "";
        int loop = 0;
        int  custId = 100 ;
        public main()
        {
           
#if DEBUG
            isPending = false;
#endif
          //  initialConsole();
            InitializeComponent();
            InitSkinGallery();
          //  UserLookAndFeel.Default.SetSkinStyle(defaultSkinName);
            initialControles();
           // hideDb();
            showWaitForm();
            if (validSn())
            {
                //showErrorMsg("程序已过期");
                createMenus(); 
            }
            
            closeWaitForm(); 
           // startLightService();
            lbvsersion.Text = getVersiion();
        }
        /// 
        /// 获取客户端发布版本号
        /// 
        /// 当前版本号
        private static string getVersiion()
        {
            var version = "1.80";
            if (ApplicationDeployment.IsNetworkDeployed)//是否已连接
            {
                ApplicationDeployment currDeployment = ApplicationDeployment.CurrentDeployment;
                DateTime lastCheck = currDeployment.TimeOfLastUpdateCheck.ToLocalTime();
                var lastDay = lastCheck.Date.ToShortDateString();
                var lastTime = lastCheck.TimeOfDay.ToString();
                var majorVersion = currDeployment.CurrentVersion.Major.ToString();//主版本
                var minorVersion = currDeployment.CurrentVersion.Minor.ToString(); //次版本
                var revisionVersion = currDeployment.CurrentVersion.Revision.ToString();//内部版本号
                var blildVersion = currDeployment.CurrentVersion.Build.ToString();//修订号
                version = majorVersion + "." + minorVersion + "." + blildVersion + "." + revisionVersion;
            }
            return "v" + version;
        }
        void hideDb(bool isHide = true)
        {
           if (isHide)
            {
               WmsConstants.SQL_CONN_WMS = "Data Source=www.deiniusoft.com;Initial Catalog=epick;Persist Security Info=True;User ID=ePicker;Password=hello123;Pooling=true;Max Pool Size = 300; Min Pool Size=0; Connection Lifetime = 300;packet size=1000 ";
                ribbonPageSystem.Visible = false;
                ribbonPageSkin.Visible = false;
               // ribbonPageGroup2.Visible = false;
                WriteConfig("SqlConnWMS", "");
                return;
            }
            WmsConstants.SQL_CONN_WMS = "";
           // ribbonPageGroup2.Visible = true;
            ribbonPageSystem.Visible = true;
            ribbonPageSkin.Visible = true;
        }
       
        private bool validSn()
        {
            initialTimer1();
            vcnt = System.Configuration.ConfigurationManager.AppSettings["vcnt"]; 
            
            checkOnline();
            try {
                loop = Convert.ToInt32(vcnt); 
                
            }
            catch { loop = 0; } 
           
            if (loop >= maxLoop)
            {
                return false;
            }
           
            DateTime dt =   DateTime.Now;
            DateTime endate = new DateTime(2022, 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;
              if (isPending)
              {
                    return resut < 0;
              }
         
            return  true;
        }
        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()
        {
          
          
        }
        /// 
        /// 同步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();
          
            result["系统设置"] = new string[] {
                "货位设置:LocationmgrForm",
             //   "标签测试:basicFuncs",
                "打印设置:ConfigPrint",
                "店铺设置:DeskCustomer",
              
            };
           
            result["播种拣选"] = new string[] {                 
                "任务控制:SeedsImport",
                "一次分播:SeedsDeskOut" ,
                "二次分播:SeedsOut"  
            }; 
            
           // result["摘果拣选"] = new string[] {"波次亮灯:GoodsOutForm" };
           
#if DEBUG 
            
#endif
            int i = 0;
            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);
                } 
                this.navBarControl1.Groups.Add(group1);
                if (group1.ItemLinks.Count > 0 && i>0)
                {
                  
                    group1.Expanded = true;
                }
                else
                {
                    group1.Expanded = false;
                }
                i++;
            }
            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
                {
                    if (isPending)
                    {
                        throw new Exception("数据库不支持");
                    }
                    // 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
                {
                }
            }
        }
       
        //-------------------------service host-----------
        static log4net.ILog log = log4net.LogManager.GetLogger("light");
        private ServiceHost host = null;
        public static List labelPool = new List();
        string svrUrl = "http://127.0.0.1:9998/DNLight";
        delegate void showStatus();
        private void startLightService()
        {
            elelab.pick.init_port(enumLabelPickType.seed);
            Thread threadPreProcess = new Thread(startHost2);
            threadPreProcess.IsBackground = true;
            threadPreProcess.Start();
        }
        void startHost2()
        {
            //  lbStatus.Text = "服务启动失败";
            try
            {
                svrUrl = System.Configuration.ConfigurationManager.AppSettings["BaseUri"];
                Uri baseAddress = new Uri(svrUrl);
                ServiceLight service = new ServiceLight();
                service.newLabels += this.newLabels;
                service.lightUp += this.lightUp;
                service.turnOff += this.turnOff;
                service.turnOnLts += this.turnOnLights;
                service.turnOffLts += this.turnOffLights;
                host = new ServiceHost(service, baseAddress);
                elelab.pick.lightOffEvent += testPicked;
                WebHttpBinding binding = new WebHttpBinding();
                ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IServiceLight), binding, baseAddress);
                WebHttpBehavior httpBehavior = new WebHttpBehavior();
                endpoint.Behaviors.Add(httpBehavior);
                host.Opened += delegate
                {
                    if (InvokeRequired)
                    {
                        this.Invoke(new showStatus(delegate()
                        {
                           // lbStatus.Text = "服务已启动";
                           // lbUrl.Text = svrUrl;
                        }));
                    }
                    else
                    {
                       // lbStatus.Text = "服务已启动";
                       // lbUrl.Text = svrUrl;
                        // lbStatus.Text = "服务启动失败";
                        //  lbUrl.Text ="";
                    }
                };
                host.Open();
            }
            catch (Exception e)
            {
                MessageBox.Show("启动服务失败:  " + e.Message);
            }
        }
        void testPicked(int eleId, int port, int eleAddress, int count)
        {
            if (InvokeRequired)
            {
                this.Invoke(new showStatus(delegate()
                {
                    showResult(eleId, port, eleAddress, count);
                }));
            }
            else
            {
                showResult(eleId, port, eleAddress, count);
            }
        }
        void showResult(int eleId, int color, int eleAddress, int count)
        {
           // lbreturn.Text = string.Format("标签ID:{0} \n\n 端口:{1} \n\n 地址:{2} \n\n 数量:{3}", eleId, color, eleAddress, count);
        }
        void newLabels(List lables)
        {
            labelPool = labelPool.Union(lables).ToList();
            labelPool = labelPool.Concat(lables).ToList();
        }
        System.Timers.Timer timer = new System.Timers.Timer();//实例化Timer类 
        private void initialTimer()
        {
            int intTime = 5000;
            timer.Interval = intTime;//设置间隔时间,为毫秒;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(lightUp);//到达时间的时候执行事件;
            timer.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
            timer.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
            timer.Start();
        }
        void lightUp(object source, System.Timers.ElapsedEventArgs e)
        {
            if (labelPool.Count == 0)
            {
                return;
            }
            ELabel lb = labelPool[0];
            int[] ids = new int[] { lb.labelId };
            string[] ele_address = new string[] { lb.address.ToString() };
            elelab.pick.init_port(enumLabelPickType.seed);
            //  string result = elelab.pick.send_data_pick(null, enumLabelPickType.pick);
            bool result = elelab.pick.lightLabels2(labelPool, 1, 1, enumLabelPickType.seed);
            if (result)
            {
                labelPool.Remove(lb);
            }
        }
        void lightUp(List lables, int portNo)
        {
            //to lightup
#if DEBUG
            // portNo = 13;
#endif
            int[] ids = new int[lables.Count];
            string[] ele_address = new string[lables.Count];
            for (int i = 0; i < lables.Count; i++)
            {
                ids[i] = lables[i].labelId;
                ele_address[i] = lables[i].address.ToString();
            }
            elelab.pick.init_port(enumLabelPickType.seed);
            elelab.pick.lightLabels2(lables, portNo, 1, enumLabelPickType.seed);
        }
        #region a
        private void insertTestData()
        {
            string url = svrUrl + "/uploadSeeds";
            try
            {
                //    #region JosnPost
                List seeds = new List();
                int maxLbId = 1;
                int k = 0;
                for (int i = 401; i < 800; i++)
                {
                    SeedsItem si = new SeedsItem();
                    si.count = i * 9 + 1;
                    si.custOrder = "CO" + i * 100 / 3 + 1;
                    si.seedsNo = "seedsNo0" + (i / maxLbId + 1);
                    if (k >= maxLbId)
                    {
                        k = 0;
                    }
                    k++;
                    si.elabId = k;
                    si.barcode = k / 5 + 1 + "";
                    si.deskId = 1;
                    si.itemName = "name" + si.barcode;
                    si.port = si.deskId;
                    si.unit = "each";
                    seeds.Add(si);
                }
                DataContractJsonSerializer dcSerializer = new DataContractJsonSerializer(typeof(List));
                MemoryStream stream = new MemoryStream();
                dcSerializer.WriteObject(stream, seeds);
                string data = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length);
                //HttpClient client = new HttpClient();
                //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                string link = url;
                //HttpResponseMessage respondse = await client.PostAsync(link, new StringContent(data));
                //string dataWithJason = await respondse.Content.ReadAsStringAsync();
                var request = (HttpWebRequest)WebRequest.Create(new Uri(link));
                request.ContentType = "application/json";
                request.Method = "POST";
                var requestStream = request.GetRequestStream();
                using (var writer = new StreamWriter(requestStream))
                {
                    writer.Write(data);
                    writer.Flush();
                }
                /*using (var resp = request.GetResponse())
                {
                    using (var responseStream = resp.GetResponseStream())
                    {
                        var reader = new StreamReader(responseStream);
                        var result = reader.ReadToEnd();
                    }
                }*/
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string json = null;
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8")))
                {
                    json = reader.ReadToEnd();
                }
                // WebResponse response = request.GetResponse();
                // string json = null;
                //   using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8")))
                {
                    //       json = reader.ReadToEnd();
                }
                /*   
                using (var requestStream = await  request.GetRequestStreamAsync())
                {
                    var writer = new StreamWriter(requestStream);
                    writer.Write(data);
                    writer.Flush();
                }
                using (var resp = await request.GetResponseAsync())
                {
                    using (var responseStream = resp.GetResponseStream())
                    {
                        var reader = new StreamReader(responseStream);
                        var result = reader.ReadToEnd();
                    }
                }*/
                /*
             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@url);
            request.ContentType = "application/json";
            request.Method = "POST";
            string inputString = data;//"{\"Key\":\"ABCDEFG\"}";
            Byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(inputString);
            request.ContentLength = byteArray.Length;
            Stream rstream = request.GetRequestStream();
            rstream.Write(byteArray, 0, byteArray.Length);
            rstream.Close();
 
 
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streams = response.GetResponseStream();
            StreamReader SR = new StreamReader(streams);
            String info = SR.ReadToEnd();
            SR.Dispose();
           */
                MessageBox.Show("导入成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion
        private void btnLightSeeds_Click(object sender, EventArgs e)
        {
        }
        private void LightSeviceHostForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            turnOffLights();
            if (host != null)
            {
                host.Close();
            }
        }
        void turnOff(int portNo)
        {
            if (unart_manage.com_manage[portNo] == null)
            {
                return;
            }
            Model.dis_id id;
            //id.ele_id = Convert.ToInt16(new_id.Text);
            id.order = 1;
            id.ele_id = 65535;
            id.state = 1;
            unart_manage.com_manage[portNo].init_port.write_clear_comment(id);
        }
        void turnOffLights()
        {
            Model.dis_id id;
            //id.ele_id = Convert.ToInt16(new_id.Text);
            id.order = 1;
            id.ele_id = 65535;
            id.state = 1;
            //id.
            foreach (int port in pick.activeComports)//WmsConstants.WAVE_CURRENT_LIGHTS_PORT_STATUS.Keys)
            {
                if (port == 0)
                {
                    continue;
                }
                //  unart_manage.com_manage[port].write_reset_device(); 复位各个硬件,通道灯,标签。。。
                unart_manage.com_manage[port].init_port.write_clear_comment(id);
            }
        }
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            insertTestData();
        }
        private void simpleButton1_Click_1(object sender, EventArgs e)
        {
            insertTestData();
        }
        /*
        void turnOnLights( int portNo,List lights )
        {
            foreach(ELight el in lights){
                
                     channel_led id =new channel_led();
                    id.channel_id = el.lightId;
                    //id.config_word = led_rgb;
                    id.color = el.color;
                    id.state = 1;
                  bool rt=  pick.turnOnLight(portNo, id);
               
            }
        }
        void turnOffLights(int portNo, List lights)
        {
            foreach (ELight el in lights)
            {
                channel_led id = new channel_led();
                id.channel_id = el.lightId;
                //id.config_word = led_rgb;
                id.state = 1;
                pick.turnOffLight(portNo, id);
                 
            }
        }
        */
        int baseLightId = 5000;
        int currentPort = 11;
        bool turnOnLights(int portNo, List lights)
        {
            if (portNo == 0)
            {
                portNo = currentPort;
            }
            // bool rt=false;
            List fail = new List();
            log.Debug("start light on request ------>");
            foreach (ELight el in lights)
            {
                channel_led id = new channel_led();
                id.channel_id = baseLightId + el.lightId;
                //id.config_word = led_rgb;
                id.color = el.which;
                id.state = 1;
                if (el.port == 0)
                {
                    el.port = portNo;
                }
                if (!pick.turnOnLight(el.port, id))
                {
                    log.Debug(getJson(el) + " light on failed. redo...");
                    fail.Add(el);
                }
                else
                {
                    log.Debug(getJson(el));
                }
                Thread.Sleep(50);
            }
            if (fail.Count > 0)
            {
                turnOnLights(portNo, fail);
            }
            log.Debug("<----------- end light on request ");
            return fail.Count == 0;
        }
        bool turnOffLights(int portNo, List lights)
        {
            if (portNo == 0)
            {
                portNo = currentPort;
            }
            bool rt = false;
            List fail = new List();
            log.Debug("start light off request ------>");
            foreach (ELight el in lights)
            {
                channel_led id = new channel_led();
                id.channel_id = baseLightId + el.lightId;
                //id.config_word = led_rgb;
                id.color = el.which;
                id.state = 1;
                if (el.port == 0)
                {
                    el.port = portNo;
                }
                if (!pick.turnOffLight(el.port, id))
                {
                    log.Debug(getJson(el) + " light off failed. redo...");
                    fail.Add(el);
                }
                else
                {
                    log.Debug(getJson(el));
                }
                Thread.Sleep(50);
            }
            if (fail.Count > 0)
            {
                turnOffLights(portNo, fail);
            }
            log.Debug("<----------- end light off  request ");
            return fail.Count == 0;
        }
        public string getJson(ELight light)
        {
            string json = "";
            json = String.Format("\"lightId\":{0},\"which\":{1}, \"port\":{2}"
              , light.lightId, light.which, light.port);
            return "{" + json + "}";
        }
        //---valid on line
        
        
        void getOnline(Object id)
        {
            /*
             svrUrl = System.Configuration.ConfigurationManager.AppSettings["onLineUri"];
             svrUrl = svrUrl + "T_ONLINE.svc/getobj?id={0}"; 
             string custId = System.Configuration.ConfigurationManager.AppSettings["custId"];
             svrUrl = string.Format(svrUrl, custId);
             //this.lbOffLight.Text = svrUrl;
             jsonOnline = HttpGet(svrUrl, null);
             wonline =   new WcfOnline();
             try
             {
                 wonline = JsonConvert.DeserializeObject(jsonOnline);
             }
             catch (Exception ex)
             {
                 log.Error(ex);
             }
            */
            validSvr();
            // string json2 = JsonConvert.SerializeObject(wonline);
            string msg = "";
            loop++;
            if (wonline.id>0)
            {
                validStatus = (enumOnlineStatus)wonline.state;
                msg = string.Format("尊敬的{0},授权状态:【{1}】, {2}", wonline.custName, validStatus,wonline.msg);
                msg = wonline.msg;
                //this.navBarControl1.BeginUpdate();
                //this.navBarControl1.Groups.Clear();
                //this.navBarControl1.EndUpdate();
              
              
                if (validStatus == enumOnlineStatus.正常)
                {
                    //createMenus();
                    loop = 0;
                }
                else if(validStatus == enumOnlineStatus.试用)
                {
                    //createMenus();
                   
                }
                else if (validStatus == enumOnlineStatus.过期)
                {
                    loop = loop>maxLoop?loop:maxLoop; 
                    msg = string.Format("尊敬的{0},授权状态:【{1}】, {2}", wonline.custName, validStatus, wonline.msg);
                } 
            } 
            
            vcnt = loop + "";
            if (loop > maxLoop)
            {
                validStatus = enumOnlineStatus.过期;
                msg = string.Format("尊敬的客户{0} 授权状态:【{1}】  {2}", wonline.custName, validStatus, wonline.msg);
            }
            if (InvokeRequired)
            {
            WriteConfig("vcnt", vcnt);
                  this.Invoke(new showStatus(delegate ()
                  {
                    lbOnline.Text = msg;
                   }));
            }
            else
            {
                lbOnline.Text = msg;
            }
            
        }
        private void checkOnline()
        {
             
            try {
                Thread threadPreProcess = new Thread(new ParameterizedThreadStart(getOnline));
                threadPreProcess.IsBackground = true;
                threadPreProcess.Start(0);
            }
            catch(Exception ex)
            {
                showErrorMsg(ex.Message);
            }
        }
       System.Timers.Timer timer1 = new System.Timers.Timer();//实例化Timer类 
        private void initialTimer1()
        {
            int minute = 1000 * 60;
            int intTime = 60 * minute;  
            timer1.Interval = intTime;//设置间隔时间, 1小时
            timer1.Elapsed += new System.Timers.ElapsedEventHandler(validHost);//到达时间的时候执行事件;
            timer1.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
            timer1.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
            timer1.Start();
        }
        private void validHost(object sender, ElapsedEventArgs e)
        {
            checkOnline();
        }
        private void btnValid_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            validSvr(true);  
           
        }
        void validSvr(bool isValid=false)
        {
           // svrUrl = System.Configuration.ConfigurationManager.AppSettings["onLineUri"];
            svrUrl = "http://www.deiniusoft.com:36990/T_ONLINE.svc/getobj?id={0}"; 
          
            svrUrl = string.Format(svrUrl, custId);
            //this.lbOffLight.Text = svrUrl;
            jsonOnline = HttpGet(svrUrl, null);
            wonline = new WcfOnline();
            try
            {
                wonline = JsonConvert.DeserializeObject(jsonOnline);
                
            }
            catch (Exception ex)
            {
                if (isValid)
                {
                    showErrorMsg(ex.Message);
                }
                log.Error(ex);
            }
            if (isValid)
            {
                string str = "验证错误:" + custId;
                if (wonline.id > 0)
                {
                    validStatus = (enumOnlineStatus)wonline.state;
                    str = string.Format("尊敬的客户 {0},您当前的服务状态是: 【{1}】时间{2}", wonline.custName, validStatus,wonline.endDate);
                }
                
                showInfoMsg(str);
            }
        }
    }
}