using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CommLayerFactory;
using ICommLayer;
using DBFactory;
using System.Configuration;
using DotNetSAPI;
using Microsoft.Win32;//20110602
using System.Diagnostics;//20110602
using System.IO;//20110602
namespace ControlSystem
{
    /// <summary>
    /// Creator:Richard.liu
    /// 程序主界面
    /// </summary>
    public partial class FrmMain : Form
    {
        #region 窗体显示
        [ System.Runtime.InteropServices.DllImport("user32")]
        private static extern bool AnimateWindow(IntPtr hwnd, int dwTime, int dwFlags);
        private const int AW_HOR_POSITIVE = 0x0001;//自左向右显示窗口，该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志
        private const int AW_HOR_NEGATIVE = 0x0002;//自右向左显示窗口，该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志
        private const int AW_VER_POSITIVE = 0x0004;//自顶向下显示窗口，该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志
        private const int AW_VER_NEGATIVE = 0x0008;//自下向上显示窗口，该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志该标志
        private const int AW_CENTER = 0x0010;//若使用了AW_HIDE标志，则使窗口向内重叠；否则向外扩展
        private const int AW_HIDE = 0x10000;//隐藏窗口
        private const int AW_ACTIVE = 0x20000;//激活窗口，在使用了AW_HIDE标志后不要使用这个标志
        private const int AW_SLIDE = 0x40000;//使用滑动类型动画效果，默认为滚动动画类型，当使用AW_CENTER标志时，这个标志就被忽略
        private const int AW_BLEND = 0x80000;//使用淡入淡出效果
        private static FrmMain _formInstance;
 
        #endregion

        public static FrmMain FormInstance
        {
            get
            {
                if (_formInstance == null)
                {
                    _formInstance = new FrmMain();
                }
                return _formInstance;
            }
            set { _formInstance = value; }
        }
        SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
        public SpVoice Voice = new SpVoice();
        DBOperator dbo;
        DBOperator dboM;
        string systemname = "自动化物流监控调度系统";

        public FrmMain()
        {
            InitializeComponent();
            _formInstance = this;
            
            dbo = CStaticClass.dbo;
            dboM = CStaticClass.dboM;
            if (dbo.Open() == false)
            {
                MMMonitorControl.Enabled = false;
                MIDeviceState.Enabled = false;
                FrmConnectDB.FormInstance.ConnectType = "Monitor";
                FrmConnectDB.FormInstance.ShowDialog();
                
                return;
            }
            if (dboM.Open() == false)
            {
                MIStartRetrieveTask.Enabled = false;
                FrmConnectDB.FormInstance.ConnectType = "Manage";
                DialogResult dr= FrmConnectDB.FormInstance.ShowDialog();
                //20100726
                if (dr != DialogResult.Cancel)
                {
                    return;
                }
            }
            //20100726
                CommonClassLib.CCarryConvert.NeatenDarkCasket();

                #region 系统配置文件初始化

                CStaticClass.RouteSearchMode = CommonClassLib.AppSettings.GetValue("RouteSearchMode");
                CStaticClass.DoubleForkWaitTime = CommonClassLib.AppSettings.GetValue("DoubleForkWaitTime");
                CStaticClass.AGVAllowSingleFork = CommonClassLib.AppSettings.GetValue("AGVAllowSingleFork");
                CStaticClass.SaveDays = CommonClassLib.AppSettings.GetValue("SaveDays");
                //20100607管理数据库类工厂初始化
                CStaticClass.ManDBFactory = dboM.GetValue("ManDBFactory");
                //20091107
                #region 调度优化设置
                CStaticClass.MovedDeviceAheadTrigger = CommonClassLib.AppSettings.GetValue("MovedDeviceAheadTrigger");
                CStaticClass.OutDetectArrowIdleGoods = CommonClassLib.AppSettings.GetValue("OutDetectArrowIdleGoods");
                CStaticClass.DeviceErrorAutoModifyRoutePath = CommonClassLib.AppSettings.GetValue("DeviceErrorAutoModifyRoutePath");
                #endregion

                //20100108
                #region 摄像头登陆设置
                CStaticClass.CameraIP = CommonClassLib.AppSettings.GetValue("CameraIP");
                CStaticClass.CameraUsername = CommonClassLib.AppSettings.GetValue("CameraUsername");
                CStaticClass.CameraPassword = CommonClassLib.AppSettings.GetValue("CameraPassword");
                #endregion
            

                #endregion

            //20100726

            //初始化管理和调度交互状态
            Model.CGetInfo.AddIOControlStatus();
            //初始化错误信息
            Model.CGetInfo.AddDeviceErrors();
            //初始化设备静态信息
            Model.CGetInfo.AddDeviceInfo();
            CStaticClass.devinfo28 = Model.CGetInfo.GetDeviceInfo(65534);

            

            #region 清理垃圾数据


            //string sql = string.Format("Delete  from T_Manage_Task_BAK where FBEGTIME ='-' or ABS(datediff(day,FBEGTIME,getdate()))>{0}", CStaticClass.SaveDays);
            //dbo.ExceSQL(sql);
            string sql = string.Format("Delete  from T_Base_Device_Error_Log where ABS(datediff(day,F_DateTime,getdate()))>{0}", CStaticClass.SaveDays);
            dbo.ExceSQL(sql);
            //判断是否有垃圾数据（调度表存在的任务，在本地管理表中不存在的）
            DataView dv = dbo.ExceSQL("SELECT F_ManageTaskIndex, F_ManageTASKKINDINDEX FROM T_Monitor_Task").Tables[0].DefaultView;
            for (int i = 0; i < dv.Count; i++)
            {
                DataView dvm = dbo.ExceSQL("SELECT FID, F_ManageTaskKindIndex FROM T_Manage_Task WHERE (FID = " + dv[i]["F_ManageTaskIndex"]
                    + ") AND (F_ManageTaskKindIndex = " + dv[i]["F_ManageTASKKINDINDEX"] + ")").Tables[0].DefaultView;
                if (dvm.Count <= 0)
                {
                    dbo.ExceSQL("DELETE FROM T_Monitor_Task WHERE (F_ManageTaskIndex = " + dv[i]["F_ManageTaskIndex"]
                    + ") AND (F_ManageTaskKindIndex = " + dv[i]["F_ManageTASKKINDINDEX"] + ")");
                }

            }
            #endregion

            #region 初始化获取任务
            
            
            //ToolStripMenuItem aa;
            //aa = new ToolStripMenuItem();
            //aa.Name = "MCAll" ;
            //aa.Text = "全部巷道";
            //MIStartRetrieveTask.DropDown.Items.Add(aa);
            //aa.Click += new EventHandler(ToolStripMenu_Click);

            //dv = dbo.ExceSQL("select distinct flaneway from st_cell order by flaneway asc").Tables[0].DefaultView;
            //for (int i = 0; i < dv.Count; i++)
            //{
            //    aa = new ToolStripMenuItem();
            //    aa.Name = "MCRetrieve"+ i.ToString();
            //    aa.Text = "巷道:" + dv[i][0].ToString();
            //    MIStartRetrieveTask.DropDown.Items.Add(aa);
            //    aa.Click += new EventHandler(ToolStripMenu_Click);
              
            //}
            #endregion

            //20100726
           // if (FrmLogin.FormInstance.ShowDialog() != DialogResult.OK) return;
          
            //20101129
            FrmControlMonitor.FormInstance.Show(this.dockPanel1);
            FrmControlMonitor.FormInstance.DockTo(this.dockPanel1, DockStyle.Fill);

            FrmTaskList Frmlist = new FrmTaskList();

            Frmlist.Show(this.dockPanel1);

            Frmlist.DockTo(this.dockPanel1, DockStyle.Bottom);
            Frmlist.DockState = WeifenLuo.WinFormsUI.Docking.DockState.DockBottomAutoHide;
            //Frmlist.AutoHidePortion = 0.125;// (double)Frmlist.Height / (double)this.dockPanel1.Height;
            Frmlist.CloseButton = false;

			//Added by DingXiaoxu on 20110104
			FrmErrorMessage frmErrorMessage = new FrmErrorMessage();
            frmErrorMessage.Show(this.dockPanel1);
            frmErrorMessage.DockTo(this.dockPanel1, DockStyle.Bottom);
            frmErrorMessage.DockState = WeifenLuo.WinFormsUI.Docking.DockState.DockBottomAutoHide;
            //Frmlist.AutoHidePortion = 0.125;// (double)Frmlist.Height / (double)this.dockPanel1.Height;
            frmErrorMessage.CloseButton = false;

            FrmHelp frmHelp = new FrmHelp();

            frmHelp.Show(this.dockPanel1);

            frmHelp.DockTo(this.dockPanel1, DockStyle.Bottom);
            frmHelp.DockState = WeifenLuo.WinFormsUI.Docking.DockState.DockBottomAutoHide;
            //Frmlist.AutoHidePortion = 0.125;// (double)Frmlist.Height / (double)this.dockPanel1.Height;
            frmHelp.CloseButton = false;
            CommonClassLib.CCarryConvert.WriteDarkCasket("Login", "UserID：" + CStaticClass.UserID + "的操作日志", "成功登录系统", "", "");

        }
        void ToolStripMenu_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem tsm; bool ifget = false;
            
            DataView dv;
            char[] cc=new char[1]{':'};
            int laneway = 0; StringBuilder minz = new StringBuilder(); StringBuilder maxz = new StringBuilder(); 
            StringBuilder wherez = new StringBuilder();
            ToolStripMenuItem aa =(ToolStripMenuItem)sender ;
            
            if (aa.Name == "MCAll")
            {
                if (aa.Checked == true)
                {
                    aa.Checked = false;
                    CStaticClass.ManZWhere.Remove(0, CStaticClass.ManZWhere.Length);
                    
                }
                else
                {
                    aa.Checked = true;
                    CStaticClass.ManZWhere.Remove(0, CStaticClass.ManZWhere.Length);
                    CStaticClass.ManZWhere.Append(" or (1=1) ");

                }
                //20100625修正不能获取站台到站台的任务

                for (int i = 0; i < MIStartRetrieveTask.DropDown.Items.Count; i++)
                {
                    
                    tsm = (ToolStripMenuItem)MIStartRetrieveTask.DropDown.Items[i];
                    if (tsm.Name != "MCAll")
                    {

                        tsm.Checked = aa.Checked;
                        
                    }
                    
                }
                
                //20100625修正不能获取站台到站台的任务

            }
            else
            {
                laneway = Convert.ToInt32(aa.Text.Split(cc)[1]);
                dv = dbo.ExceSQL("select min(f_z) as minZ from st_cell where flaneway=" + laneway + "").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    if (dv[0]["minZ"].ToString().Length == 1)
                    {
                        minz = minz.Append("'0").Append(dv[0]["minZ"].ToString()).Append("-00-00'");
                    }
                    else
                    {
                        minz = minz.Append("'"+dv[0]["minZ"].ToString()).Append("-00-00'");
                    }

                }
                dv = dbo.ExceSQL("select max(f_z) as maxZ from st_cell where flaneway=" + laneway + "").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    if (dv[0]["maxZ"].ToString().Length == 1)
                    {
                        maxz = maxz.Append("'0").Append(dv[0]["maxZ"].ToString()).Append("-99-99'");
                    }
                    else
                    {
                        maxz = maxz.Append("'"+dv[0]["maxZ"].ToString()).Append("-99-99'");
                    }
                }
                wherez.Append(" or ((START_DEVICE_CODE between ").Append(minz).Append(" and ").Append(maxz).Append(" ) or  (END_DEVICE_CODE between ").Append(minz).Append(" and ").Append(maxz).Append("))");
                if (aa.Checked == true)
                {
                    aa.Checked = false;
                    //20100625修正不能获取站台到站台的任务
                    CStaticClass.ManZWhere.Replace(wherez.ToString(), "");
                    
                    ToolStripMenuItem cm = new ToolStripMenuItem();
                    ToolStripMenuItem all = (ToolStripMenuItem)MIStartRetrieveTask.DropDown.Items["MCAll"];
                    CStaticClass.ManZWhere.Replace(" or (1=1) ", "");
                    all.Checked = false;
                    StringBuilder wherez1 = new StringBuilder();
                    minz.Remove(0, minz.Length);
                    maxz.Remove(0, maxz.Length);
                    for (int ii = 0; ii < MIStartRetrieveTask.DropDown.Items.Count; ii++)
                    {
                       
                        cm = (ToolStripMenuItem)MIStartRetrieveTask.DropDown.Items[ii];
                        if ((cm.Checked == true) && (cm.Name != aa.Name) && (cm.Name != "MCAll"))
                        {
                            laneway = Convert.ToInt32(cm.Text.Split(cc)[1]);
                            dv = dbo.ExceSQL("select min(f_z) as minZ from st_cell where flaneway=" + laneway + "").Tables[0].DefaultView;
                            if (dv.Count > 0)
                            {
                                if (dv[0]["minZ"].ToString().Length == 1)
                                {
                                    minz = minz.Append("'0").Append(dv[0]["minZ"].ToString()).Append("-00-00'");
                                }
                                else
                                {
                                    minz = minz.Append("'" + dv[0]["minZ"].ToString()).Append("-00-00'");
                                }

                            }
                            dv = dbo.ExceSQL("select max(f_z) as maxZ from st_cell where flaneway=" + laneway + "").Tables[0].DefaultView;
                            if (dv.Count > 0)
                            {
                                if (dv[0]["maxZ"].ToString().Length == 1)
                                {
                                    maxz = maxz.Append("'0").Append(dv[0]["maxZ"].ToString()).Append("-99-99'");
                                }
                                else
                                {
                                    maxz = maxz.Append("'" + dv[0]["maxZ"].ToString()).Append("-99-99'");
                                }
                            }
                            wherez1.Append(" or ((START_DEVICE_CODE between ").Append(minz).Append(" and ").Append(maxz).Append(" ) or  (END_DEVICE_CODE between ").Append(minz).Append(" and ").Append(maxz).Append("))");
                
                        }
                        
                    }
                    if (CStaticClass.ManZWhere.ToString().IndexOf(wherez1.ToString()) < 0)
                    {
                        CStaticClass.ManZWhere = CStaticClass.ManZWhere.Append(wherez1);
                    }
                    //20100625修正不能获取站台到站台的任务
                }
                else
                {
                    aa.Checked = true;
                    if (CStaticClass.ManZWhere.ToString().IndexOf(wherez.ToString()) < 0)
                    {
                        CStaticClass.ManZWhere = CStaticClass.ManZWhere.Append(wherez);
                    }
                }
            }

            MIStartRetriveTask_Click(sender, e);

            for (int i = 0; i < MIStartRetrieveTask.DropDown.Items.Count; i++)
            {
                tsm = (ToolStripMenuItem)MIStartRetrieveTask.DropDown.Items[i];
                if (tsm.Checked == true)
                {
                    ifget = true;
                }
            }
            if (ifget == false)
            {
                MIStopRetriveTask_Click(sender, e);

            }
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            //this.Visible = false;
            
            
            MIStopRetrieveTask.Enabled = false;
            MITurnOff.Enabled = false;
            this.notifyIcon1.Visible = true;//20100807zl
            //20100726
            
        }

        private void MIStartRetriveTask_Click(object sender, EventArgs e)
        {
            
            if (MITurnOn.Checked == true)
            {
                this.Text = systemname + "--【开始获取任务！】" + "--【正在执行自动命令！】";
            }
            else
            {
                this.Text = systemname + "--【开始获取任务！】";
            }
            MIStopRetrieveTask.Enabled = true;
            
            MIStartRetrieveTask.Checked = true;
            MIStopRetrieveTask.Checked = false;
            FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "", false);
            CStaticClass.ObtainManageTask = true;
        }

        private void MIStopRetriveTask_Click(object sender, EventArgs e)
        {
            if (MITurnOn.Checked == true)
            {
                this.Text = systemname + "--【正在执行自动命令！】";
            }
            else
            {
                this.Text = systemname;
            }
            CStaticClass.ManZWhere.Remove(0, CStaticClass.ManZWhere.Length);
            
            ToolStripMenuItem tsm;
            for(int i=0;i<MIStartRetrieveTask.DropDown.Items.Count;i++)
            {
                tsm =(ToolStripMenuItem) MIStartRetrieveTask.DropDown.Items[i];
                tsm.Checked = false;
            }
            MIStartRetrieveTask.Checked = false;

            CStaticClass.ObtainManageTask = false;
            MIStopRetrieveTask.Enabled =false ;
            MIStopRetrieveTask.Checked =true ;
        }

        private void MITurnOn_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确认要“打开命令开关”吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                if (MIStartRetrieveTask.Checked == true)
                {
                    this.Text = systemname + "--【开始获取任务！】";
                }
                else
                {
                    this.Text = systemname;
                }
                return;
            }
            if (MIStartRetrieveTask.Checked != true)
            {

                if (MessageBox.Show("“开始获取任务”没有选中，\r\n您确认要同时“开始获取任务”吗？", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    MIStartRetriveTask_Click(sender, e);
                }
            }
            toolStripMenuItem13.Checked = true;
            toolStripMenuItem14.Checked = false;
            toolStripMenuItem14.Enabled = true;
            toolStripMenuItem13.Enabled = false;
            MMDarketManage.Enabled = true;
            MMUserManage.Enabled = true;
            MIUserInfoManage.Enabled = true;
            //toolStripMenuItem13_Click(sender, e);
            CStaticClass.Order = true;
            MITurnOff.Enabled = true;
            MITurnOn.Enabled = false;
            
            MITurnOff.Checked =false ;
            MITurnOn.Checked = true;

            //执行自动命令
            CStaticClass.ReConnect();
            MMDarketManage.Checked = true;
            MMUserManage.Checked = false;
            MIUserInfoManage.Checked = false;
            //toolStripMenuItem15_Click(sender, e);
            CStaticClass.AutoOrder = true;
            CStaticClass.HandOrder = false;
            CStaticClass.TempOrder = false;
            if (MIStartRetrieveTask.Checked == true)
            {
                this.Text = systemname + "--【开始获取任务！】" + "--【正在执行自动命令！】";
            }
            else
            {
                this.Text = systemname + "--【正在执行自动命令！】";
            }
            
            FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "", false);

        //    CListenAGVState.StartListen();

            CParsePLCData.StartListen();
       //   CStaticClass.StartListenReturn();

        }
        int GetManageHandIdx()
        {
            DataSet ds = dbo.ExceSQL("SELECT F_ManageTaskKindIndex, max(FID) as mFID FROM T_Manage_Task Where F_ManageTaskKindIndex=4 group by F_ManageTaskKindIndex");
            if (ds.Tables[0].DefaultView.Count > 0)
            {
                return (Convert.ToInt32(ds.Tables[0].DefaultView[0]["mFID"]) + 1);
            }
            else
            {
                DataSet dss = dbo.ExceSQL("SELECT F_ManageTaskIndex FROM T_Base_Manage_Task_Index_Hand_Task");
                if (ds.Tables[0].DefaultView.Count > 0)
                {
                    return (Convert.ToInt32(dss.Tables[0].DefaultView[0]["F_ManageTaskIndex"]) + 1);
                }
                else
                {
                    return 40001;//83178135
                }
            }
        }

        private void MITurnOff_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确认要“关闭命令开关”吗？如果“关闭命令开关”将导致调度计算机与所有设备通讯中断！", "操作提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
            {
                return;
            }
            toolStripMenuItem14.Checked = true;
            toolStripMenuItem13.Checked = false;
            toolStripMenuItem14.Enabled = false;
            toolStripMenuItem13.Enabled = true;
            
            CStaticClass.Order = false;
            MITurnOff.Enabled = false;
            MITurnOn.Enabled = true;
            
            MITurnOn.Checked = false;
            MITurnOff.Checked = true;
            CStaticClass.HandOrder = false;
            CStaticClass.AutoOrder = false;
            CStaticClass.TempOrder  = false;
            if (MIStartRetrieveTask.Checked == true)
            {
                this.Text = systemname + "--【开始获取任务！】";
            }
            else
            {
                this.Text = systemname;
            }
            CDisassembleTask.EndListen();
            SocketsTCPIP.CClientTCPIP.EndConnect();
           CParsePLCData.EndListen();
          // CStaticClass.EndListenReturn();
        }

        

        private void MIHandOrder_Click(object sender, EventArgs e)
        {
            CStaticClass.ReConnect();
            MMUserManage.Checked = true;
            MMDarketManage.Checked = false;
            MIUserInfoManage.Checked = false;
            //toolStripMenuItem16_Click(sender, e);
            CStaticClass.HandOrder = true;
            CStaticClass.AutoOrder = false;
            CStaticClass.TempOrder = false;

            this.Text = systemname + "--【正在执行手工命令！】";
            FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "", false);
        }

       

        private void MIManageShow_Click(object sender, EventArgs e)
        {
            FrmAutoCommand.FormInstance.ShowDialog();
        }

        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            FrmDarkCasket.FormInstance.ShowDialog();
        }

        

        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            FrmDeviceErrorLog.FormInstance.ShowDialog();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //if (m_bShowWnd == true)//隐藏主界面 
            //{
            //    this.Visible = false;
            //    m_bShowWnd = false;
            //    this.TopMost = false;
            //}
            //else//显示主界面 
            //{
            this.TopMost = true;
            this.Visible = true;
            this.TopMost = false;
            //20091223
            this.WindowState = FormWindowState.Maximized;
            //} 
        }

        private void toolStripMenuItem8_Click(object sender, EventArgs e)
        {
            this.Visible = true;
            //20091223
            this.WindowState = FormWindowState.Maximized;
        }

        private void toolStripMenuItem9_Click(object sender, EventArgs e)
        {//20091107
            MIExitSystem_Click(sender, e);
        }

        private void toolStripMenuItem10_Click(object sender, EventArgs e)
        {
            this.Visible = false;
            
        }

        private void toolStripMenuItem11_Click(object sender, EventArgs e)
        {//20091107
            //toolStripMenuItem11.Checked = true;
            //toolStripMenuItem12.Checked = false;
            //CStaticClass.ObtainManageTask = true;
            //toolStripMenuItem12.Enabled = true;
            //toolStripMenuItem11.Enabled = false;
            //FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "", false);
            MIStartRetriveTask_Click(sender, e);
        }

        private void toolStripMenuItem12_Click(object sender, EventArgs e)
        {//20091107
            //toolStripMenuItem12.Checked = true;
            //toolStripMenuItem11.Checked = false;
            //CStaticClass.ObtainManageTask = false;
            //toolStripMenuItem12.Enabled = false;
            //toolStripMenuItem11.Enabled = true;
            MIStopRetriveTask_Click(sender, e);
        }

        private void toolStripMenuItem13_Click(object sender, EventArgs e)
        {//20091107
            MITurnOn_Click(sender, e);
            //toolStripMenuItem13.Checked = true;
            //toolStripMenuItem14.Checked = false;
            //CStaticClass.Order = true;
            //toolStripMenuItem14.Enabled = true;
            //toolStripMenuItem13.Enabled = false;
            //toolStripMenuItem15.Enabled = true;
            //toolStripMenuItem16.Enabled = true;
            //toolStripMenuItem19.Enabled = true;
            //if (CStaticClass.DeviceInit == true)
            //{
            //    //在设备初始化表提取需要初始化的设备和命令
            //    try
            //    {

            //        string Sql;
            //        string start = "-";
            //        string end = "-";
            //        int hidx = GetManageHandIdx();
            //        DataSet ds = dbo.ExceSQL("SELECT F_InitIndex, F_ManageTaskKindIndex, T_Base_Device_Init.F_DeviceIndex, " +
            //            "T_Base_Device_Init.F_DeviceCommandIndex,F_NumParam1, F_NumParam2, F_NumParam3,F_DeviceName," +
            //            "F_DeviceCommandName FROM T_Base_Device_Init,T_Base_Device,T_Base_Device_Command Where " +
            //            "T_Base_Device_Init.F_DeviceIndex = T_Base_Device.F_DeviceIndex and T_Base_Device.F_DeviceKindIndex = T_Base_Device_Command.F_DeviceKindIndex and " +
            //            "T_Base_Device_Init.F_DeviceCommandIndex = T_Base_Device_Command.F_DeviceCommandIndex");
            //        DataView dv = ds.Tables[0].DefaultView;
            //        if (dv.Count <= 0) return;
            //        for (int i = 0; i < dv.Count; i++)
            //        {
            //            if ((Convert.ToInt32(dv[0]["F_NumParam1"]) == 0) && (Convert.ToInt32(dv[0]["F_NumParam2"]) == 0) && (Convert.ToInt32(dv[0]["F_NumParam3"]) == 0))
            //            {
            //                return;
            //            }
            //            else
            //            {
            //                start = dv[0]["F_NumParam1"].ToString() + "-" + dv[0]["F_NumParam2"].ToString() + "-" + dv[0]["F_NumParam3"].ToString();
            //            }
            //            end = start;
            //            Sql = "insert into T_Manage_Task(FID,F_ManageTaskKindIndex,FSTARTCELL," +
            //                    "FENDCELL,FDeviceIndex,FDeviceName,FDeviceCommand,FDeviceCommandName) " +
            //                    "values(" + hidx + ",4,'" + start + "','" + end + "'," + Convert.ToInt32(dv[0]["F_DeviceIndex"])
            //                    + ",'" + dv[0]["F_DeviceName"].ToString() + "'," + Convert.ToInt32(dv[0]["F_DeviceCommandIndex"]) + ",'" + dv[0]["F_DeviceCommandName"].ToString() + "')";
            //            dbo.ExceSQL(Sql);
            //        }

            //    }
            //    catch (Exception ex)
            //    {
            //        throw ex;
            //    }

            //    CStaticClass.HandOrder = true;
            //    CStaticClass.DeviceInit = false;

            //}
        }

        private void toolStripMenuItem14_Click(object sender, EventArgs e)
        {//20091107
            MITurnOff_Click(sender, e);
            //toolStripMenuItem14.Checked = true;
            //toolStripMenuItem13.Checked = false;
            //CStaticClass.Order = false;
            //toolStripMenuItem14.Enabled = false;
            //toolStripMenuItem13.Enabled = true;
            //toolStripMenuItem15.Enabled = false;
            //toolStripMenuItem16.Enabled = false;
            //toolStripMenuItem15.Checked = false;
            //toolStripMenuItem16.Checked = false;
            //toolStripMenuItem19.Enabled = false;
            //toolStripMenuItem19.Checked = false;
        }

        

        private void toolStripMenuItem16_Click(object sender, EventArgs e)
        {//20091107
            MIHandOrder_Click(sender, e);
            //toolStripMenuItem16.Checked = true;
            //toolStripMenuItem15.Checked = false;
            //toolStripMenuItem19.Checked = false;
            //CStaticClass.HandOrder = true;
            //CStaticClass.AutoOrder = false;
            //CStaticClass.TempOrder = false;
            //this.Text = "新松自动化物流监控调度系统" + "--【正在执行手工命令！】";
            //FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "", false);
        }

        private void MIHelp_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Help.ShowHelp(Parent, "SiaSunWCMS.chm");

            
        }

        private void MIAbout_Click(object sender, EventArgs e)
        {
            FrmAboutBox.FormInstance.ShowDialog();
        }

        private void toolStripMenuItem17_Click(object sender, EventArgs e)
        {
            FrmConnectDB.FormInstance.ConnectType = "Manage";
            FrmConnectDB.FormInstance.ShowDialog();
        }

        private void toolStripMenuItem18_Click(object sender, EventArgs e)
        {
            FrmConnectDB.FormInstance.ConnectType = "Monitor";
            FrmConnectDB.FormInstance.ShowDialog();
        }

        private void MITempOrder_Click(object sender, EventArgs e)
        {
            CStaticClass.ReConnect();
            MMUserManage.Checked = false;
            MMDarketManage.Checked = false;
            MIUserInfoManage.Checked = true;
            //toolStripMenuItem19
            CStaticClass.TempOrder = true;
            CStaticClass.AutoOrder = false;
            CStaticClass.HandOrder = false;

            this.Text = systemname + "--【正在执行临时管理命令！】";
            FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "",false );
        }

        private void toolStripMenuItem19_Click(object sender, EventArgs e)
        {
            MITempOrder_Click(sender, e);
            //toolStripMenuItem16.Checked =false ;
            //toolStripMenuItem15.Checked = false;
            //toolStripMenuItem19.Checked = true;
            //CStaticClass.HandOrder = false;
            //CStaticClass.AutoOrder = false;
            //CStaticClass.TempOrder = true;
            //this.Text = "新松自动化物流监控调度系统" + "--【正在执行临时管理命令！】";
            //FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "", false);
        }

        private void toolStripMenuItem20_Click(object sender, EventArgs e)
        {
            FrmDeviceInfoEdit.FormInstance.ShowDialog();
        }

        private void toolStripMenuItem22_Click(object sender, EventArgs e)
        {
            FrmModifyMonitor.FormInstance.ShowDialog();
        }

        private void toolStripMenuItem23_Click(object sender, EventArgs e)
        {
            FrmModifyManage.FormInstance.ShowDialog();
        }

        private void notifyIcon1_BalloonTipShown(object sender, EventArgs e)
        {
            try
            {
               // Voice.Speak(notifyIcon1.BalloonTipText, SpFlags);
            }
            catch
            {

            }
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {//20091223
           
            if (CStaticClass.IfRemind == false) return;
            if (MessageBox.Show("您确认要退出自动化物流监控调度系统吗？", "操作提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                SocketsTCPIP.CClientTCPIP.EndConnect();
                CDisassembleTask.EndListen();
                CListenAGVState.EndListen();
                CObtainTask.EndListen();
                //20091107
                CParsePLCData.EndListen();

              //  CStaticClass.EndListenReturn();
                //Application.Exit();
                CommonClassLib.CCarryConvert.WriteDarkCasket("Login", "UserID：" + CStaticClass.UserID + "的操作日志", "退出系统", "", "");
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void MIDarketFileSet_Click(object sender, EventArgs e)
        {
            FrmDarkCasket.FormInstance.ShowDialog();
        }

        private void MIDeviceState_Click(object sender, EventArgs e)
        {
            FrmDeviceInfoEdit.FormInstance.ShowDialog();
        }

        private void MIRouteInfo_Click(object sender, EventArgs e)
        {
            FrmRouteEdit.FormInstance.ShowDialog();
        }

        private void MIAltMonitor_Click(object sender, EventArgs e)
        {
            FrmModifyMonitor.FormInstance.ShowDialog();
           // FrmModifyMonitor.FormInstance.Show();
        }

        private void MIAltManange_Click(object sender, EventArgs e)
        {
            FrmModifyManage.FormInstance.ShowDialog();
            //FrmModifyManage.FormInstance.Show();
        }

        private void MIExitSystem_Click(object sender, EventArgs e)
        {
          //
        }

        private void MIAltPassword_Click(object sender, EventArgs e)
        {
            FrmPassword.FormInstance.ShowDialog();
        }

        private void MIUserInfoManage_Click(object sender, EventArgs e)
        {
            FrmUsers.FormInstance.ShowDialog();
        }

        private void MIDataClear_Click(object sender, EventArgs e)
        {
            CGetState cgs = new CGetState();
            if (MessageBox.Show("您确认要清空调度任务信息和设备指令队列信息吗？", "操作提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                dbo.ExecuteSql("delete from T_Manage_Task");
                DataView dv= dbo.ExceSQL("select * from T_Monitor_Task").Tables[0].DefaultView ;//20100610
                for (int i = 0; i < dv.Count; i++)
                {
                    cgs.ActionComplete(Convert.ToInt32(dv[i]["F_DeviceIndex"]), Convert.ToInt32(dv[i]["F_MonitorIndex"]), Model.CGeneralFunction.TASKDELETE);
                }
                CommonClassLib.CCarryConvert.WriteDarkCasket("Login", "UserID：" + CStaticClass.UserID + "的操作日志", "进行数据清理操作", "", "");
            }
        }

        private void MISystemInit_Click(object sender, EventArgs e)
        {
            FrmSystemInit.FormInstance.ShowDialog();
        }

        private void MISeeDarket_Click(object sender, EventArgs e)
        {
            FrmBrowseDarkCasket.FormInstance.ShowDialog();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            FrmHandCommand.FormInstance.ShowDialog();
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            FrmHandAssociateCommand.FormInstance.ShowDialog();
        }

        private void MIWaitTime_Click(object sender, EventArgs e)
        {
            string deletetime = DateTime.Now.AddMonths(-1).ToString("u");
            deletetime = deletetime.Substring(0, deletetime.Length - 1);
            try
            {

                dbo.ExceSQL("delete from t_bak_uploadmsg where time < '" + deletetime + "'");
                dbo.ExceSQL("delete from T_BAK_Manage_Task where FBEGTIME < '" + deletetime + "'");
                dbo.ExceSQL("delete  from T_BAK_Monitor_Task where F_StartTime < '" + deletetime + "'");
                MessageBox.Show("清除完成!" );
            }
            catch (Exception ex)
            {
                MessageBox.Show("清除失败" + ex.Message);

            }
            finally
            {
            }

            

           // FrmWaitTime.FormInstance.ShowDialog();
        }

        private void MIIOStation_Click(object sender, EventArgs e)
        {
            //FrmRelativeIDSet.FormInstance.ShowDialog();
        }

        private void MIAutoTaskHistory_Click(object sender, EventArgs e)
        {
            //FrmBrowseAotoTaskLog.FormInstance.ShowDialog();
        }
        static public bool ExistsWinRAR()
        {
            RegistryKey the_Reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");
            return !string.IsNullOrEmpty(the_Reg.GetValue("").ToString());
        }
        /// <summary>
        /// 将目录压缩为.RAR文件
        /// </summary>
        /// <param name="patch">源目录</param>
        /// <param name="rarPatch">目的目录</param>
        /// <param name="rarName">压缩文件名称,如包含目录名称可以不制定rarpatch</param>
        public bool CompressRAR(string patch, string rarPatch, string rarName)
        {
            bool flag = false ;
            string the_rar;
            RegistryKey the_Reg;
            object the_Obj;
            string the_Info;
            ProcessStartInfo the_StartInfo;
            Process the_Process;
            try
            {
                the_Reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");
                the_Obj = the_Reg.GetValue("");
                the_rar = the_Obj.ToString();
                the_Reg.Close();
                //the_rar = the_rar.Substring(1, the_rar.Length - 7);//该行可能有问题?
                //Directory.CreateDirectory(patch);//使用已有目录
                //命令参数
                //the_Info = " a    " + rarName + " " + @"C:Test?70821.txt"; //文件压缩
                the_Info = string.Format("A -r -ep1 \"{0}\" {1}\"", rarName, patch);//路径中含有空格的处理－加入\
                the_StartInfo = new ProcessStartInfo();
                the_StartInfo.FileName = the_rar;
                the_StartInfo.Arguments = the_Info;
                the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                //打包文件存放目录,如果文件名中包含目录信息则可以不指定
                //the_StartInfo.WorkingDirectory = rarPatch;
                the_Process = new Process();
                the_Process.StartInfo = the_StartInfo;
                the_Process.Start();
                the_Process.WaitForExit();

                if (the_Process.HasExited)
                {
                    if(the_Process.ExitCode==0)
                    {
                    flag = true;
                    }
                }
                the_Process.Close();
                
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return flag;
        }

        private void BakDarketMenuItem_Click_1(object sender, EventArgs e)
        {
            try
            {
                if (ExistsWinRAR())
                {
                    string SourceFilePath = System.Environment.CurrentDirectory + "\\DarkCasket";
                    string localFilePath;
                    string saveFilepath = "F:\\";
                    //string newFileName;
                    saveFileDialog1.Title = "备份黑匣子...";
                    saveFileDialog1.FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "DarkCasket";
                    saveFileDialog1.Filter = "WinRAR文件(*.rar)|*.rar";

                    if (System.IO.Directory.Exists(saveFilepath))//文件目录是否存在
                    {
                        saveFileDialog1.InitialDirectory = saveFilepath;
                    }

                    saveFileDialog1.RestoreDirectory = true;

                    saveFileDialog1.CheckPathExists = true;
                    saveFileDialog1.OverwritePrompt = true;

                    if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
                    {

                        localFilePath = saveFileDialog1.FileName.ToString();
                        saveFilepath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\") + 1);//获得路径,不含文件名
                        //newFileName=localFilePath.Substring(localFilePath.LastIndexOf("\\")+1);//获得文件名，不含路径

                        //CompressRAR(SourceFilePath,saveFilepath,newFileName);
                        bool ifsuccess = CompressRAR(SourceFilePath, saveFilepath, localFilePath);
                        //下面判断文件是否生成来确定是否备份成功
                        if (ifsuccess == true && System.IO.File.Exists(localFilePath))
                        {
                            MessageBox.Show("黑匣子文件备份并压缩成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        }
                        else
                        {
                            MessageBox.Show("黑匣子文件备份失败!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }

                        //还原是一样的.只是sql改成"RESTORE FILELISTONLY  FROM DISK ='路径'"
                    }

                }
                else
                {
                    MessageBox.Show("未安装WinRAR,无法完成备份!请安装WinRAR之后再尝试备用或直接进行手工备份!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void MonitorDataBackUpMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string localFilePath;
                string saveFilepath = "D:\\";
                saveFileDialog1.Title = "备份调度系统数据库...";
                saveFileDialog1.FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "DBBak";
                saveFileDialog1.Filter = "所有文件(*.*)|*.*";

                if (System.IO.Directory.Exists(saveFilepath))//文件目录是否存在
                {
                    saveFileDialog1.InitialDirectory = saveFilepath;
                }

                saveFileDialog1.RestoreDirectory = true;
                //saveFileDialog1.CheckFileExists = true;
                saveFileDialog1.CheckPathExists = true;
                saveFileDialog1.OverwritePrompt = true;

                if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
                {

                    localFilePath = saveFileDialog1.FileName.ToString();


                    string sql = string.Format("Backup database JXDL to disk = '{0}'", localFilePath); //MyTest为远程数据库名称，也可以改成用变量传入
                    dbo.ExceSQL(sql);

                    //下面判断文件是否生成来确定是否备份成功
                    if (System.IO.File.Exists(localFilePath))
                    {
                        MessageBox.Show("数据库备份成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    else
                    {
                        MessageBox.Show("数据库备份失败!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }

                    //还原是一样的.只是sql改成"RESTORE FILELISTONLY  FROM DISK ='路径'"
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }

        private void DeviceStatusSearchMenuItem_Click(object sender, EventArgs e)
        {
            FrmDeviceErrorLog.FormInstance.ShowDialog();
        }

        private void MIHandShow_Click(object sender, EventArgs e)
        {
            FrmHandCommand.FormInstance.ShowDialog();
           // FrmHandCommand.FormInstance.Show();
        }

      


        

        

        

        

        

        
    }
}