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 System.Diagnostics;
using GcDevicePc.ProThread;
using GcDevicePc.Common;
using GcDevicePc.IniParam;
using System.Threading;
using System.IO;
using GcDevicePc.CK_UI;

namespace GcDevicePc
{
    public partial class MDIBase : Form
    {
        private int childFormNumber = 0;
        private static FormUser  userForm;  //用户界面
        private static Formdebug debugForm;  //调试界面
       // private static MainBase basefrom;
        private string Formstr;//窗口名称
        private string statestr;//状态信息
       // private Color stateColor=new Color();//状态颜色;
        private bool IsStateColor = false;
        System.DateTime startTime;  //系统启动时间
        TimeSpan timespan;
        bool inifilec = false;  //方法文件是否加载
        /// <summary>
        /// HMI控制接口
        /// </summary>
        HMIControl hmiopt;
        /// <summary>
        /// HMI数据获取接口
        /// </summary>
        GcDataTh mymodbus;

        /// <summary>
        /// Modbus Slave 接口
        /// </summary>
        GCModbusSlave Slavetest;
        /// <summary>
        /// 数据接收
        /// </summary>
        DataRcv mytcptest = new DataRcv();
        /// <summary>
        /// 处理数据接口
        /// </summary>
        CKvocUpdata dataVOC = new CKvocUpdata();
        public MDIBase()
        {
            InitializeComponent();
           // this.WindowState = FormWindowState.Maximized;
        }

        private void ShowNewForm(object sender, EventArgs e)
        {
            Form childForm = new Form();
            childForm.MdiParent = this;
            childForm.Text = "窗口 " + childFormNumber++;
            childForm.Show();
        }

        private void OpenFile(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            openFileDialog.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = openFileDialog.FileName;
            }
        }

        private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            saveFileDialog.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = saveFileDialog.FileName;
            }
        }

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

        private void CutToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void PasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void ToolBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
          //  toolStrip.Visible = toolBarToolStripMenuItem.Checked;
        }

        private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
           // statusStrip.Visible = statusBarToolStripMenuItem.Checked;
        }

        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void TileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.ArrangeIcons);
        }

        private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in MdiChildren)
            {
                childForm.Close();
            }
        }

        private void MDIBase_Load(object sender, EventArgs e)
        {
            dllInit();
            InitConfig();
            debugForm = new Formdebug();
            debugForm.MdiParent = this;
            debugForm.Dock = DockStyle.Fill;
            debugForm.Show();
           // debugForm.Hide();
            userForm = new FormUser();
            userForm.MdiParent = this;
            userForm.Dock = DockStyle.Fill;
             userForm.Show();
            // debugForm.Show();
             Formstr = "用户窗口";
             startTime = DateTime.Now;
             toolStripStatusLabeSystme.Text = string.Format("状态：{0}", Formstr);
          
             timespan = System.DateTime.Now - startTime;
             toolStripStatusLabelusertime.Text = string.Format("运行时间：{0}", timespan.Days.ToString() + "天" + timespan.Hours.ToString() + "时" + timespan.Minutes.ToString() + "分" + timespan.Seconds.ToString() + "秒");
            //显示方法名称
             if (globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName==null)
            {
                SetMainFormMethodName("未加载");

            }else
            {
                SetMainFormMethodName( globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName.Substring(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName.LastIndexOf("\\") + 1));
            }

             SetMenu(LandIn.Island);
             autopensys();

            //点火接口
             userForm.autofire += new Fireport(fireupopt);

            
        }
        /// <summary>
        /// 判断是否要开启系统
        /// </summary>
        private void autopensys()
        {
            try
            {
                globaldata.starttimer = 0x7FFFFFFF;
             

                string file = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunFolder + "\\startup.ini";
                INIOperation test = new INIOperation(file);
                string opensys = test.INIGetStringValue("StartUp", "打开系统", "0");

                if ((Convert.ToInt32(opensys) == 1 && globaldata.m_hmibuffer.gcinfo.methodstatus == 0) || globaldata.m_hmibuffer.gcinfo.methodstatus != 0)
                {
                    //autoopensys_Click();
                    open();
                }

                //if (globaldata.m_hmibuffer.gcinfo.methodstatus != 0)
                //{
                //  //  hmistatus_opensys();
                //}

            }
            catch(Exception ex)
            {
                Trace.Write(ex);
            }
        }
        /// <summary>
        /// 组件初始化
        /// </summary>
        private void dllInit()
        {
           

            try
            {
                MainBase_InitAppConfig();
                //初始化路径

                if (CKVocAnalyzer.Config.Instance.ReadPath())
                {
                    //初始化
                    CKVocAnalyzer.VOCEntityConfig.Instance.vocinit();

                    CKVocAnalyzer.Config.Instance.ReadAxisRange();
                  
                    LogOperate.LogInit.Instance.path = CKVocAnalyzer.GlobalCKV.FolderLog;
                    LogOperate.LogInit.Instance.Init();
                    CKVocAnalyzer.GlobalCKV.tcpservice.tcpStart(CKVocAnalyzer.GlobalCKV.hostadd, CKVocAnalyzer.GlobalCKV.tcpport);
                    Trace.WriteLine("系统初始化成功", "sys");
                }
                else
                {
                    //MessageBox.Show("系统初始化失败，请检查配置文件是否存在");
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
                MessageBox.Show(ex.Message);
            }
        }

        private void 调试窗口ToolStripMenuItem_Click(object sender, EventArgs e)  //历史数据查询
        {
         try
         {
             WaveTotalForm total = new WaveTotalForm();
             total.Show();

         }
          catch(Exception ex)
         {
             Trace.Write(ex);
         }
        }
        private void SetMenu(bool isbool)
        {
            try
            {
                if (isbool)
                {
                    网络配置ToolStripMenuItem.Enabled = true;
                    方法查阅ToolStripMenuItem.Enabled = true;
                    新建方法ToolStripMenuItem.Enabled = true;
                    打开方法文件ToolStripMenuItem.Enabled = true;
                    方法查阅ToolStripMenuItem.Enabled = true;
                    校准查看ToolStripMenuItem.Enabled = true;
                    //方法批处理ToolStripMenuItem.Enabled = true;

                }else
                {
                    网络配置ToolStripMenuItem.Enabled = false;
                    方法查阅ToolStripMenuItem.Enabled = false;
                    新建方法ToolStripMenuItem.Enabled = false;
                    打开方法文件ToolStripMenuItem.Enabled = false;
                    方法查阅ToolStripMenuItem.Enabled = false;
                    校准查看ToolStripMenuItem.Enabled = false;
                    //方法批处理ToolStripMenuItem.Enabled = false;
                }

            }
            catch(Exception ex)
            {
                Trace.Write(ex);
            }
        }
        private void 用户登录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult dr = new LandIn().ShowDialog();        

            if (dr == DialogResult.OK)  //停止系统并退出
            {
                if(LandIn.Island)
                {
                   if (debugForm != null)
                  {
                    Formstr = "调试窗口";
                    debugForm.Activate();
                  }
                   SetMenu(LandIn.Island);
                }
            }
            if (dr == DialogResult.No)
            {

            }
           
           
        }

        private void 用户注销ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (debugForm != null)
            {

               // debugForm.Hide();

            }
            if (userForm != null)
            {
                Formstr = "用户窗口";
                userForm.Activate();
                //userForm.Show();
            }
            LandIn.Island = false;
            SetMenu(LandIn.Island);
        }

        private void timer1_Tick(object sender, EventArgs e)  //显示状态栏信息
        {
            this.Text = string.Format("VOCs在线监测-1.0.0.0   {0}",Formstr);
            toolStripStatusLabeSystme.Text = string.Format("状态：{0}", statestr);
            //if (IsStateColor)
            //    toolStripStatusLabeSystme.BackColor = Color.LightBlue;// System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(149)))), ((int)(((byte)(237)))));
            //else
            //    toolStripStatusLabeSystme.BackColor = Color.Coral;//System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0)))));

                      
       
            timespan = System.DateTime.Now - startTime;
            toolStripStatusLabelusertime.Text = string.Format("运行时间：{0}", timespan.Days.ToString() + "天" + timespan.Hours.ToString() + "时" + timespan.Minutes.ToString() + "分" + timespan.Seconds.ToString() + "秒");
            //if(globaldata.MethodRun_Statue==4||globaldata.MethodRun_Statue==5)
            //{
            //    toolStripProgressBar1.Maximum = globaldata.m_dpbuffer.ShowList.showtime.alltime;
            //    if (globaldata.m_dpbuffer.ShowList.showtime.runtimenow < globaldata.m_dpbuffer.ShowList.showtime.alltime)
            //    {
            //    toolStripProgressBar1.Value = globaldata.m_dpbuffer.ShowList.showtime.runtimenow;
            //    }else
            //    {
            //        toolStripProgressBar1.Value = globaldata.m_dpbuffer.ShowList.showtime.alltime;
            //    }

            //}
            //else
            //{
            //    toolStripProgressBar1.Value=0;
            //}

        }
        /// <summary>
        /// 网络配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 网络配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UserConfig confu = new UserConfig();
            confu.Show();
        }
        public void SendPCCMD(bool flag)
        {
            if (flag)  //打开运行
            {
                hmiopt.WriteStopVal();
                //singlemodbus.WriteStopVal();
                WaitHMIFree();

                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue)
                {
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                    {
                        hmiopt.WriteStopVal();
                    }

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 1)
                        hmiopt.WriteSingleVal();

                    WaitHMIWork();
                }
            }
            else   //批处理
            {
                hmiopt.WriteStopVal();
                // singlemodbus.WriteStopVal();
                WaitHMIFree();

                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue)
                {
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                    {
                        hmiopt.WriteBatVal();

                        hmiopt.WriteStartVal();

                        WaitHMIWork();
                    }

                }
            }
        }
        public void SetMainFormMethodName(string text)
        {
           // this.now_method.Text = "当前运行方法：" + text;
            this.toolStripStatusLabelText.Text = "当前运行方法：" + text;
        }

        private void 打开方法文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDlg = new OpenFileDialog();
            fileDlg.Multiselect = false;
            fileDlg.InitialDirectory = Application.StartupPath + "\\仪器方法";
            fileDlg.Title = "请选择方法文件";
            fileDlg.Filter = "配置文件(*.ini)|*.ini";
            if (fileDlg.ShowDialog() == DialogResult.OK)
            {
                string file = fileDlg.FileName;
                // globaldata.cur_MethodName = file;
                // globaldata.cur_OpenMethodName = file;
                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_OpenMethodName = file;
                this.inifilec = true;

                globaldata.m_profileMethod.SetMethodFullName(file);
                globaldata.m_profileMethod.GetDevState();

                if (globaldata.m_configDlg.IsDisposed)
                    globaldata.m_configDlg = new MethodConfig();

                globaldata.m_configDlg.m_InjPortDlg.reflashContent();
                globaldata.m_configDlg.m_InjSampleDlg.reflashContent();
                globaldata.m_configDlg.m_InjValveDlg.reflashContent();
                globaldata.m_configDlg.m_chromeDlg.reflashContent();
                globaldata.m_configDlg.m_RealColDlg.reflashContent();
                globaldata.m_configDlg.m_det.reflashContent();
                globaldata.m_configDlg.m_AuxDlg.reflashContent();
                // globaldata.m_configDlg.m_SignalDlg.reflashContent();

                globaldata.m_configDlg.changenameforup -= new ConfigDlg.ChangeMNameForUp(SetMainFormMethodName);
                globaldata.m_configDlg.changenameforup += new ConfigDlg.ChangeMNameForUp(SetMainFormMethodName);
                globaldata.m_configDlg.sendupdatecmd -= new ConfigDlg.SendUpdateCMD(SendPCCMD);
                globaldata.m_configDlg.sendupdatecmd += new ConfigDlg.SendUpdateCMD(SendPCCMD);
                globaldata.m_configDlg.Show();

                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType = 0;
                //globaldata.RunType = 0;
                //  globaldata.m_configDlg.m_RunTableDlg.reflashContent();
            }
        }

        private void 方法查阅ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (globaldata.m_configDlg.Visible == true)
                return;

            if (inifilec)
            {
                globaldata.m_profileMethod.SetMethodFullName(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName);
                globaldata.m_profileMethod.GetDevState();

                if (globaldata.m_configDlg.IsDisposed)
                    globaldata.m_configDlg = new MethodConfig();

                globaldata.m_configDlg.m_InjPortDlg.reflashContent();
                globaldata.m_configDlg.m_InjSampleDlg.reflashContent();
                globaldata.m_configDlg.m_InjValveDlg.reflashContent();
                globaldata.m_configDlg.m_chromeDlg.reflashContent();
                globaldata.m_configDlg.m_RealColDlg.reflashContent();
                globaldata.m_configDlg.m_det.reflashContent();
                globaldata.m_configDlg.m_AuxDlg.reflashContent();
                // globaldata.m_configDlg.m_SignalDlg.reflashContent();

                globaldata.m_configDlg.changenameforup -= new ConfigDlg.ChangeMNameForUp(SetMainFormMethodName);
                globaldata.m_configDlg.changenameforup += new ConfigDlg.ChangeMNameForUp(SetMainFormMethodName);

                globaldata.m_configDlg.sendupdatecmd -= new ConfigDlg.SendUpdateCMD(SendPCCMD);
                globaldata.m_configDlg.sendupdatecmd += new ConfigDlg.SendUpdateCMD(SendPCCMD);

                globaldata.m_configDlg.Show();

            }
            else
            {
                OpenFileDialog fileDlg = new OpenFileDialog();
                fileDlg.Multiselect = false;
                fileDlg.InitialDirectory = Application.StartupPath + "\\仪器方法";
                fileDlg.Title = "请选择方法文件";
                fileDlg.Filter = "配置文件(*.ini)|*.ini";
                if (fileDlg.ShowDialog() == DialogResult.OK)
                {
                    string file = fileDlg.FileName;
                    //  globaldata.cur_MethodName = file;
                    //globaldata.cur_OpenMethodName = file;
                    globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_OpenMethodName = file;

                    globaldata.m_profileMethod.SetMethodFullName(file);
                    globaldata.m_profileMethod.GetDevState();

                    if (globaldata.m_configDlg.IsDisposed)
                        globaldata.m_configDlg = new MethodConfig();

                    globaldata.m_configDlg.m_InjPortDlg.reflashContent();
                    globaldata.m_configDlg.m_InjSampleDlg.reflashContent();
                    globaldata.m_configDlg.m_InjValveDlg.reflashContent();
                    globaldata.m_configDlg.m_chromeDlg.reflashContent();
                    globaldata.m_configDlg.m_RealColDlg.reflashContent();
                    globaldata.m_configDlg.m_det.reflashContent();
                    globaldata.m_configDlg.m_AuxDlg.reflashContent();
                    //  globaldata.m_configDlg.m_SignalDlg.reflashContent();

                    globaldata.m_configDlg.changenameforup -= new ConfigDlg.ChangeMNameForUp(SetMainFormMethodName);
                    globaldata.m_configDlg.changenameforup += new ConfigDlg.ChangeMNameForUp(SetMainFormMethodName);
                    globaldata.m_configDlg.sendupdatecmd -= new ConfigDlg.SendUpdateCMD(SendPCCMD);
                    globaldata.m_configDlg.sendupdatecmd += new ConfigDlg.SendUpdateCMD(SendPCCMD);
                    globaldata.m_configDlg.Show();
                    //  globaldata.m_configDlg.m_RunTableDlg.reflashContent();
                }
            }       
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            for (int i = 0; i < 100; i++)
            {
                if (globaldata.m_hmibuffer.gcinfo.hmistatus == 0)
                {
                    if (globaldata.OS_STOP)
                    {
                        globaldata.OS_STOP = false;
                    }

                    worker.ReportProgress(100);
                    break;
                }
                else
                {
                    if (i % 20 == 0)
                    {
                        if (globaldata.OS_STOP)
                        {
                            hmiopt.WriteEndVal();
                            // LogHelper.I("backgroundWorker1_DoWork", "WriteEndVal");
                        }
                        else
                        {
                            hmiopt.WriteStopVal();
                            // LogHelper.I("backgroundWorker1_DoWork", "WriteStopVal");
                        }

                    }

                    Thread.Sleep(100);
                    if (i != 99)
                        worker.ReportProgress(i);
                }

                if (worker.CancellationPending)  // 如果用户取消则跳出处理数据代码 
                {
                    e.Cancel = true;
                    break;
                }
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled)
            {
            }
            else
            {
            }
        }
        public void WaitHMIFree()
        {
            this.backgroundWorker1.RunWorkerAsync();
            WaitForm form = new WaitForm(this.backgroundWorker1);
            form.ShowDialog(this);
            form.Close();
        }

        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            for (int i = 0; i < 100; i++)
            {
                if (globaldata.m_hmibuffer.gcinfo.methodstatus > 0 && globaldata.m_hmibuffer.gcinfo.methodstatus < 5)
                {
                    worker.ReportProgress(100);
                    break;
                }
                else
                {
                    if (i % 20 == 0 && i != 0)
                    {
                        if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                            hmiopt.WriteOpenVal();

                        if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 1)
                            hmiopt.WriteSingleVal();


                        if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                        {
                            hmiopt.WriteBatVal();
                            hmiopt.WriteStartVal();
                        }
                    }

                    Thread.Sleep(100);
                    if (i <= 99)
                        worker.ReportProgress(i);
                }

                if (worker.CancellationPending)  // 如果用户取消则跳出处理数据代码 
                {
                    e.Cancel = true;
                    break;
                }
            }
        }

        private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                // MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled)
            {
            }
            else
            {
            }
        }
        public void WaitHMIWork()
        {
            this.backgroundWorker2.RunWorkerAsync();
            WaitForm form = new WaitForm(this.backgroundWorker2);
            form.ShowDialog(this);
            form.Close();
        }
        /// <summary>
        /// 检测本地默认目录
        /// </summary>
        private void MainBase_InitAppConfig()
        {
            try
            {
                string tmpFolder;
                //检查创建仪器方法目录     
                globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunFolder = System.Windows.Forms.Application.StartupPath;
                tmpFolder = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunFolder;

                globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder = System.IO.Path.Combine(tmpFolder, "仪器方法");
                tmpFolder = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder;

                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName = System.IO.Path.Combine(tmpFolder, "SingleAnal.ini(单次运行默认方法)");
                tmpFolder = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder;
                if (System.IO.Directory.Exists(tmpFolder) == false)
                {
                    System.IO.Directory.CreateDirectory(tmpFolder);
                }

                //检查创建仪器状态目录
                tmpFolder = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunFolder;
                globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StatusFolder = System.IO.Path.Combine(tmpFolder, "仪器状态");
                tmpFolder = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StatusFolder;
                if (System.IO.Directory.Exists(tmpFolder) == false)
                {
                    System.IO.Directory.CreateDirectory(tmpFolder);
                }

                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName = System.IO.Path.Combine(tmpFolder, "DevStatus.ini");
                if ((globaldata.connection_ip == null || globaldata.connection_ip == "") && System.IO.File.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName) == false)
                {
                    System.IO.File.Create(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName).Dispose();
                }

                globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.subStatusFolder = System.IO.Path.Combine(tmpFolder, "子状态");
                if (System.IO.Directory.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.subStatusFolder) == false)
                {
                    System.IO.Directory.CreateDirectory(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.subStatusFolder);
                }

                globaldata.m_profileMethod.SetStatusFullName(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName);

                //获取硬件配置
                //globaldata.m_hwconfig = new GCBuffer.HWConfig(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName);
                // globaldata.m_hwconfig.GetHWConfig();

                //检查创建运行表目录
                globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunFolder, "运行表");
                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder, "RunMethod.ini");

                if (System.IO.Directory.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder) == false)
                {
                    System.IO.Directory.CreateDirectory(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder);
                }
                if (System.IO.File.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab) == false)
                {
                    StreamWriter sw = new StreamWriter(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab, false, System.Text.Encoding.Unicode);
                    sw.WriteLine("[运行表]");
                    sw.Close();
                }

                globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.DataFolder = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunFolder, "历史数据");
                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_DataName = null;

                if (System.IO.Directory.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.DataFolder) == false)
                {
                    System.IO.Directory.CreateDirectory(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.DataFolder);
                }
                tmpFolder = null;
            }
            catch(Exception ex)
            {
                Trace.Write(ex);
            }
        }
        public void SendStopCMD()
        {
            try
            {
                hmiopt.WriteStopVal();
                WaitHMIFree();
            }
            catch
            {
            }

        }
        private void 方法批处理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                
               RunTables f_runtable = new RunTables();
                f_runtable.sendupdatecmd -= new SendUpdateCMD(SendPCCMD);
                f_runtable.sendupdatecmd += new SendUpdateCMD(SendPCCMD);
                f_runtable.sendstopcmd -= new SendStopCMD(SendStopCMD);
                f_runtable.sendstopcmd += new SendStopCMD(SendStopCMD);
                f_runtable.Show();
           
            }
            catch (Exception ex)
            {
                Trace.Write(ex);

            }
        }

        private void 校准查看ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                AdjustFrom just = new AdjustFrom();
                just.Show();

            }
            catch(Exception ex)
            {
                Trace.Write(ex);
            }
        }

        private void 历史谱图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                HistChartForm hist = new HistChartForm();
                hist.Show();

            }
            catch(Exception ex)
            {
                Trace.Write(ex);
            }
        }

        private void 新建方法ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MethodNameInputForm m_methodNameInputForm = new MethodNameInputForm();
            m_methodNameInputForm.Show();
        }
        private void InitConfig()
        {
            try
            {

                string singlefilename = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, "SingleAnal.ini");
                string tmpname;
                string runtabfilename = "";

                int ret;

                if (globaldata.connection_ip != null && globaldata.connection_ip != "")
                {
                    Start_ConnectStatusThread();

                    //获取配置文件
                    try
                    {
                        FileServerClient mainclient = new FileServerClient();
                        mainclient.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);
                        if (System.IO.File.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName))
                        {
                            Thread.Sleep(100);
                            System.IO.File.Delete(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName);
                        }
                        ret = mainclient.WtClientCopyfromServer("DevStatus.ini", globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName, globaldata.remoteFolder + "仪器状态\\");
                        Thread.Sleep(400);

                        if (System.IO.File.Exists(singlefilename))
                        {
                            System.IO.File.Delete(singlefilename);
                        }
                        ret = mainclient.WtClientCopyfromServer("SingleAnal.ini", singlefilename, globaldata.remoteFolder + "仪器方法\\");
                        Thread.Sleep(400);


                        if (System.IO.File.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab))
                        {
                            Thread.Sleep(100);
                            System.IO.File.Delete(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab);
                        }


                        try
                        {
                            tmpname = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunTabFolder, "RunMethod.ini");
                            ret = mainclient.WtClientCopyfromServer("RunMethod.ini", tmpname, globaldata.remoteFolder + "运行表\\");
                            Thread.Sleep(400);

                            INIOperation runtable = new INIOperation(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab);
                            string[] key = runtable.INIGetAllItemKeys("运行表");

                            runtabfilename = runtable.INIGetStringValue("运行表", key[1], null);

                            if (runtabfilename == null)
                            {
                                // MessageBox.Show("请检查批处理文件是否存在或内容是否为空");
                            }
                            else
                            {
                                tmpname = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, runtabfilename);

                                if (!System.IO.File.Exists(tmpname))
                                {
                                    ret = mainclient.WtClientCopyfromServer(runtabfilename, tmpname, globaldata.remoteFolder + "仪器方法\\");
                                }

                                Thread.Sleep(400);
                            }

                        }
                        catch
                        {
                            //MessageBox.Show("请检查批处理文件是否存在或内容是否为空");
                        }

                        mainclient.WtClientClose();

                        if (!System.IO.File.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName) /*|| !System.IO.File.Exists(singlefilename)*/)
                        {
                            //MessageBox.Show("配置文件获取失败，请检测HMI配置文件是否存在！");
                        }

                       // Console.WriteLine("运行类型是：" + globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType.ToString());

                        globaldata.m_profileMethod.GetDevState();
                        if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                        {
                            tmpname = runtabfilename;
                            if (tmpname != null && tmpname != "")
                            {
                                globaldata.show_MethodName = tmpname;
                                //this.now_method.Text = "当前运行方法：" + tmpname;
                                SetMainFormMethodName(tmpname);
                                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, tmpname.ToString());
                                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;
                                globaldata.m_profileMethod.SetMethodFullName(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName);

                                globaldata.m_profileMethod.GetDevInjPortAllPara();
                                globaldata.m_profileMethod.GetSampleAllPara("前进样器");
                                globaldata.m_profileMethod.GetInjValveAllPara();
                                globaldata.m_profileMethod.GetChromAllPara();
                                globaldata.m_profileMethod.GetColTableElseAllPara();
                                globaldata.m_profileMethod.GetFidAllPara();
                                globaldata.m_profileMethod.GetTcdAllPara();
                                globaldata.m_profileMethod.GetAuxiliaryAllPara();

                                // globaldata.m_profileMethod.GetDevSignalAllPara();      
                            }
                        }
                        else
                        {
                            INIOperation GetMethodName = new INIOperation(singlefilename);
                            tmpname = GetMethodName.INIGetStringValue("方法名称", "名称", null);
                            if (tmpname != null)
                            {
                                globaldata.show_MethodName = tmpname;
                               // this.now_method.Text = "当前运行方法：" + tmpname;
                                SetMainFormMethodName(tmpname);
                                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, tmpname.ToString());
                                globaldata.m_profileMethod.SetMethodFullName(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName);

                                globaldata.m_profileMethod.GetDevInjPortAllPara();
                                globaldata.m_profileMethod.GetSampleAllPara("前进样器");
                                globaldata.m_profileMethod.GetInjValveAllPara();
                                globaldata.m_profileMethod.GetChromAllPara();
                                globaldata.m_profileMethod.GetColTableElseAllPara();
                                globaldata.m_profileMethod.GetFidAllPara();
                                globaldata.m_profileMethod.GetTcdAllPara();
                                globaldata.m_profileMethod.GetAuxiliaryAllPara();

                                // globaldata.m_profileMethod.GetDevSignalAllPara();      
                            }
                        }

                    }
                    catch
                    {
                        //string message = "系统初始化失败";
                        //MessageBox.Show(message.ToString(), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);                 
                    }

                   statestr = "设备联机";
                   // curdisplay.Text = "前检测器";
                  // stateColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(149)))), ((int)(((byte)(237)))));
                    IsStateColor=true;
                }
                else
                {

                    statestr = "未联机";
                    //ateColor = System.Drawing.Color.FromArgb(((int)(((byte)(254)))), ((int)(((byte)(185)))), ((int)(((byte)(16)))));
                    IsStateColor = false;

                 //   curdisplay.Text = "前检测器";

                }


                //this.showPanel.Contains(curdisplay);
                //curdisplay.Show(this.showPanel);
                //curdisplay.CloseButtonVisible = false;

                hmiopt = null;
                hmiopt = new HMIControl(globaldata.connection_ip, globaldata.datamodbusport);
                mymodbus = null;
                mymodbus = new GcDataTh(globaldata.connection_ip, globaldata.datamodbusport);


                Start_Thread();

                try
                {
                    Slavetest = new GCModbusSlave();
                    Slavetest.CModbusSlaveInit(1, 2, 3, 5);

                }
                catch
                {

                }

                //dockPanelSideLeft.Close_Threading();
                //dockPanelSideLeft.Close();

                //侧边状态菜单
                //dockPanelSideLeft = new DataState();
                //dockPanelSideLeft.Show(this.showPanel, WeifenLuo.WinFormsUI.Docking.DockState.DockRight);
                //dockPanelSideLeft.CloseButtonVisible = false;

            }
            catch(Exception ex)
            {
                Trace.Write(ex);
            }
        }
        public void Start_Thread()
        {
            // mydatasave.ChannelDataStart();
            mymodbus.HmiStatueStart();
            mymodbus.ChannelDataStart();
            dataVOC.CKvocUpdataStart();

            mytcptest.DataRcvStart();
        }

        public void Stop_Thread()
        {
            // mydatasave.ChannelDataStop();
            mymodbus.HmiStatueStop();
            mymodbus.ChannelDataStop();
            dataVOC.CKvocUpdataStop();

            mytcptest.DataRcvStop();
        }

       /// <summary>
       /// 状态改变信号量
       /// </summary>
        ManualResetEvent datamre = new ManualResetEvent(false);
        ManualResetEvent conmre = new ManualResetEvent(false);
        ushort GCstatus = 9;
        Thread Connect_Status;
        /// <summary>
        /// HMI状态监控线程
        /// </summary>
        private void Start_ConnectStatusThread()
        {
            if (conmre != null)
            {
                conmre.Reset();
            }
            Connect_Status = new Thread(Monitor_Connect);
            Connect_Status.IsBackground = true;
            Connect_Status.Start();
        }

        /// <summary>
        /// HMI状态监控线程实现
        /// </summary>
        private void Monitor_Connect()
        {
            System.UInt16[] dest = new System.UInt16[9];
            //int ret = 0 ;
            //int LoseNum = 0;
            ushort status_flag = 10;
            ushort status_flag_old = 10;
            ushort runtype = 0;

            while (!conmre.WaitOne(500))
            {
                Thread.Sleep(500);

                if (globaldata.m_pcbuffer.gcpcinfo.pcthreadinfo.HMI_Monitor_TH == 1)
                {
                    break;
                }

                // LogHelper.I("HMI状态获取", "Run.....");
                dest[0] = globaldata.m_hmibuffer.gcinfo.batno;
                dest[1] = globaldata.m_hmibuffer.gcinfo.batruncount;
                dest[2] = globaldata.m_hmibuffer.gcinfo.oneruntime;
                dest[3] = globaldata.m_hmibuffer.gcinfo.singlerun;
                dest[4] = globaldata.m_hmibuffer.gcinfo.batrun;
                dest[5] = globaldata.m_hmibuffer.gcinfo.methodstatus;
                dest[6] = globaldata.m_hmibuffer.gcinfo.waitstart;
                dest[7] = globaldata.m_hmibuffer.gcinfo.hmistatus;
                dest[8] = globaldata.m_hmibuffer.gcinfo.runtime;

                //LogHelper.I("methodstatus", dest[5].ToString());
                //if(globaldata.connection_ip !=null)
                //    ret = m_modbus.ReadHoldingReg(144, 9, globaldata.connection_ip, globaldata.datamodbusport, ref dest);
                //    //ret = globaldata.m_modbus.ReadHoldingReg(144, 9, globaldata.connection_ip, globaldata.datamodbusport, ref dest);

                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue)
                    status_flag = dest[5];
                else
                    status_flag = 10;

                GCstatus = dest[5];
                runtype = dest[7];

                globaldata.MethodRun_Statue = dest[5];
                globaldata.RunTime_Now = dest[2];
                globaldata.RunTotal_Now = dest[8];

                //Console.WriteLine("+++++++++++调试信息++++++++++++++");
                //Console.WriteLine("批处理序号：" + dest[0].ToString());
                //Console.WriteLine("运行次数：" + dest[1].ToString());
                //Console.WriteLine("运行多少秒：" + dest[2].ToString());
                //Console.WriteLine("单次运行：" + dest[3].ToString());
                //Console.WriteLine("运行运行表：" + dest[4].ToString());
                //Console.WriteLine("当前运行方法状态:" + dest[5].ToString());
                ////Console.WriteLine("打开当前方法，等待开始指令：" + dest[6].ToString());
                //Console.WriteLine("机器运行状态：" + dest[7].ToString());
                ////Console.WriteLine("运行总时间：" + dest[8].ToString());
                // LogHelper.I("当前运行方法状态", dest[5].ToString());
                //Console.WriteLine("+++++++++++错误信息++++++++++++++");
                //Console.WriteLine("通讯板错误报警：" + globaldata.m_hmibuffer.gcinfo.ErrorStatus[0].ToString());
                //Console.WriteLine("检测板错误报警：" + globaldata.m_hmibuffer.gcinfo.ErrorStatus[1].ToString());
                //Console.WriteLine("电源板错误报警：" + globaldata.m_hmibuffer.gcinfo.ErrorStatus[2].ToString());
                //Console.WriteLine("异常温度错误报警：" + globaldata.m_hmibuffer.gcinfo.ErrorStatus[3].ToString());
                //Console.WriteLine("与主机通讯异常：" + globaldata.m_hmibuffer.gcinfo.ErrorStatus[4].ToString());


                if (globaldata.m_hmibuffer.gcinfo.hmioffline)
                {
                    status_flag = 9;
                    // globaldata.connection_ip = null;
                }

                //if(dest[5] == 3 && dest[7] == 4)
                //{
                //    Console.WriteLine("已就绪！！！！！！！");
                //}

                if ((dest[5] == 4 || dest[5] == 5) && dest[7] == 4 && globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue != 1)
                {

                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType = 0;
                   // invokeDelegate update_ButtonStatus = () =>
                    //{
                    //    ChangeButton(2);
                    //};
                    //Invoke(update_ButtonStatus);
                   // startbtn();
                }



                //点火失败或着火焰熄灭，停止系统
                //if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue && globaldata.m_hmibuffer.gcinfo.FireStatus[0] == 3 && globaldata.m_hmibuffer.gcinfo.methodstatus == 0 && globaldata.m_hmibuffer.gcinfo.hmistatus == 0)
                //{
                //    invokeDelegate auto_close = () =>
                //    {
                //        autoclosesys_Click();                        
                //    };
                //    Invoke(auto_close);

                //}

                //if ( (dest[5] ==0 || dest[5] == 6 || dest[5] == 7 ) && dest[7] == 0 && globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 1)
                //{
                //    Console.WriteLine("已就绪,下位机按了停止！！");
                //}

                //if (dest[5] == 0)
                //{
                //    globaldata.work_Statue = 0;
                //}

                switch (runtype)
                {
                    case 0:
                        ButtonControl_Status(dest[5], 0);
                        DataControl_Status(dest[5], 0);
                        break;
                    case 2:
                        BAT_HeadInfo(dest[0], dest[1]);
                        ButtonControl_Status(dest[5], 2);
                        DataControl_Status(dest[5], 2);
                        break;
                    case 3:
                        QuickRun_HeadInfo();
                        ButtonControl_Status(dest[5], 1);
                        DataControl_Status(dest[5], 1);
                        break;
                    case 4:
                        SingleRun_HeadInfo();
                        ButtonControl_Status(dest[5], 0);
                        //  DataControl_Status(dest[5], 0);
                        break;
                    default:
                        Common_HeadInfo();
                        break;
                }
                Status_Show(status_flag, ref status_flag_old);

                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                {
                    //Console.WriteLine("当前方法：" + globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName);
                    //Console.WriteLine("当前批处理方法：" + globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName);

                    if (globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName != globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName)
                    {
                        string tmpFileName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName;
                        string getFileName = "";
                        int ret;
                        FileServerClient mainclient = new FileServerClient();
                        try
                        {
                            mainclient.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);
                            if (!System.IO.File.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName))
                            {
                                getFileName = tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1);
                                ret = mainclient.WtClientCopyfromServer(getFileName, globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName, globaldata.remoteFolder + "仪器方法\\");
                                Thread.Sleep(400);
                            }

                            globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName;
                            globaldata.m_profileMethod.SetMethodFullName(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName);
                            globaldata.m_profileMethod.GetDevInjPortAllPara();
                            globaldata.m_profileMethod.GetSampleAllPara("前进样器");
                            globaldata.m_profileMethod.GetInjValveAllPara();
                            globaldata.m_profileMethod.GetChromAllPara();
                            globaldata.m_profileMethod.GetColTableElseAllPara();
                            globaldata.m_profileMethod.GetFidAllPara();
                            globaldata.m_profileMethod.GetTcdAllPara();
                            globaldata.m_profileMethod.GetAuxiliaryAllPara();

                            mainclient.WtClientClose();
                        }
                        catch
                        {
                            mainclient.WtClientClose();
                        }
                    }

                }

            }
        }


        void DataControl_Status(ushort flag, ushort runtype)
        {
            switch (flag)
            {
                case 0:
                case 1:
                case 2:
                    //globaldata.work_Statue = 0;                   
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 1)
                        stopbtn();
                    break;
                case 3:   //已就绪               
                    break;
                case 4:
                case 5:
                    //if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 0)
                       // startbtn();
                    break;
                case 6:
                case 7:
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 1)
                        stopbtn();
                    break;
            }
        }

        void ButtonControl_Status(ushort flag, ushort runtype)
        {
            invokeDelegate update_ButtonStatus_UI = () =>
            {
                switch (flag)
                {
                    case 0:
                    case 1:
                    case 2:
                      //  ChangeButton(0);
                        break;
                    case 3:   //已就绪
                     //   if (runtype == 0 && globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue != 1)
                           // ChangeButton(1);
                        break;
                    case 4:
                    case 5:
                        //ChangeButton(2);
                        break;
                    case 6:
                     //   ChangeButton(0);
                        break;
                    case 7:
                     //   ChangeButton(0);
                        break;
                }
            };
            Invoke(update_ButtonStatus_UI);
        }

        /// <summary>
        /// 显示系统连接状态和方法运行
        /// </summary>
        /// <param name="flag"></param>
        /// <param name="oldflag"></param>
        void Status_Show(ushort flag, ref ushort oldflag)
        {
            string status_text = null;
            bool color_flag = true;
            switch (flag)
            {
                case 0:
                case 1:
                    status_text = "空闲中...";
                    break;
                case 2:
                    status_text = "仪器平衡中...";
                    break;
                case 3:
                    status_text = "已就绪...";
                    break;
                case 4:
                case 5:
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 1)
                        status_text = "方法运行中...";
                    else if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 2)
                        status_text = "方法运行中...";
                    else if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 3)
                        status_text = "方法运行中...";
                    else
                        status_text = "方法运行中...";
                    break;
                case 6:
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 1)
                        stopbtn();
                    status_text = "后处理...";
                    break;
                case 7:
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 1)
                        stopbtn();
                    status_text = "后处理完毕...";
                    break;
                case 8:
                    status_text = "信号稳定中...";
                    break;
                case 9:
                    status_text = "设备断开";
                    color_flag = false;
                    break;
                default:
                    status_text = "设备连接";

                    break;
            }
            statestr = status_text;
            IsStateColor = color_flag;

            if (oldflag != flag)
            {
                //invokeDelegate update_statustext = () =>
                //{
                //    SetTitleStatueName(status_text, color_flag);
                //};
                //Invoke(update_statustext);
                oldflag = flag;
            }
        }

        void Common_HeadInfo()
        {
            string tmpFileName;
            tmpFileName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;
            invokeDelegate update_singlerunhead = () =>
            {
                SetMainFormMethodName(tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1));
            };
            Invoke(update_singlerunhead);
        }

        void SingleRun_HeadInfo()
        {
            string tmpFileName;
            tmpFileName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;
            invokeDelegate update_singlerunhead = () =>
            {
                SetMainFormMethodName(tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1) + " 单次运行");
            };
            Invoke(update_singlerunhead);
        }

        void QuickRun_HeadInfo()
        {
            string tmpFileName;
            tmpFileName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;
            invokeDelegate update_quickrunhead = () =>
            {
                SetMainFormMethodName(tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1) + " 快速运行");
            };
            Invoke(update_quickrunhead);
        }

        void BAT_HeadInfo(ushort num, ushort count)
        {
            try
            {
                INIOperation runtable = new INIOperation(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab);
                string[] key = runtable.INIGetAllItemKeys("运行表");
                string[] runnum = runtable.INIGetAllItemKeys("循环");


                if (num < key.Length)
                {
                    if ((num != 0 || count > 0))
                    {
                        if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue != 0)
                        {
                            invokeDelegate update_methodname = () =>
                            {
                                SetMainFormMethodName(runtable.INIGetStringValue("运行表", key[num], "无") + "  批处理： " + " 第" + (count + 1).ToString() + "/" + runtable.INIGetStringValue("循环", runnum[num], "无") + "次");
                            };
                            Invoke(update_methodname);


                        }
                        else
                        {
                            invokeDelegate update_methodname = () =>
                            {
                                SetMainFormMethodName(runtable.INIGetStringValue("运行表", key[num], "无") + "  批处理 ");
                            };
                            Invoke(update_methodname);
                        }
                    }

                    globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, runtable.INIGetStringValue("运行表", key[num], "无"));
                }
            }
            catch(Exception ex)
            {
                Trace.Write(ex);
            }
        }

        Thread t_checkcmd;
        public void stopbtn()
        {
            globaldata.startflag = false;
            globaldata.stopflag = true;
            globaldata.cancelflag = false;
            //  globaldata.starttimer = 0x7FFFFFFF;
            Console.WriteLine("stopbtn  startimer");
            if (globaldata.connection_ip != null && globaldata.connection_ip != "")
            {
                // globaldata.work_Statue = 2;
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 2;
            }

            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
            {
                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true)
                {
                    hmiopt.WriteOpenVal();
                    // singlemodbus.WriteOpenVal();
                    // WaitHMIWork();
                    t_checkcmd = new Thread(checkcmd);
                    t_checkcmd.IsBackground = true;
                    t_checkcmd.Start();
                }
            }
        }

        private void checkcmd()
        {
            while (globaldata.m_hmibuffer.gcinfo.methodstatus != 3)
            {
                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                {
                    hmiopt.WriteOpenVal();
                }
                else if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 1)
                {
                    hmiopt.WriteSingleVal();
                }
                else
                {

                }
                Thread.Sleep(1000);
            }

        }

        private void MDIBase_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult dr = new QuitForm().ShowDialog();
           

            uint ret = 0;
            uint count = 0;

            if (dr == DialogResult.OK)  //停止系统并退出
            {
                count = 0;
                if (globaldata.connection_ip != null && globaldata.connection_ip != "")
                {
                    globaldata.OS_STOP = true;
                    hmiopt.WriteEndVal();

                    WaitHMIFree();
                }

                conmre.Set();
                globaldata.m_pcbuffer.gcpcinfo.pcthreadinfo.HMI_Monitor_TH = 1;
                Thread.Sleep(1500);


                count = 0;
                ret = Slavetest.CModbusSlaveClose();
                while (ret != 0)
                {
                    count++;
                    ret = Slavetest.CModbusSlaveClose();
                    Thread.Sleep(100);
                    if (count > 3)
                    {
                        break;
                    }
                }

                System.Environment.Exit(0);
            }

            if (dr == DialogResult.Yes)  //仅退出
            {
                count = 0;
                if (globaldata.connection_ip != null && globaldata.connection_ip != "")
                {
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                    {
                        globaldata.OS_STOP = false;
                        hmiopt.WriteStopVal();

                        WaitHMIFree();
                    }

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                    {
                        hmiopt.WriteOpenVal();
                        WaitHMIWork();
                    }
                }

                conmre.Set();
                globaldata.m_pcbuffer.gcpcinfo.pcthreadinfo.HMI_Monitor_TH = 1;
                Thread.Sleep(1500);

                count = 0;
                ret = Slavetest.CModbusSlaveClose();
                while (ret != 0)
                {
                    count++;
                    ret = Slavetest.CModbusSlaveClose();
                    Thread.Sleep(100);
                    if (count > 3)
                    {
                        break;
                    }
                }
                System.Environment.Exit(0);
            }

        }

        private void 系统开启ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            open();
        }
       // private bool isopen = false;
        private void open()
        {
            try
            {
                if(globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue)
                {
                    MessageBox.Show("系统开启中......");
                    return ;
                }
                if (globaldata.connection_ip != null && globaldata.connection_ip != "")
                {

                    hmiopt.WriteStopVal();

                    statestr = "系统准备中...";

                    WaitHMIFree();

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                    {
                        hmiopt.WriteBatVal();
                    }

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                    {
                        hmiopt.WriteOpenVal();
                    }

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 1)
                    {
                        hmiopt.WriteSingleVal();
                    }

                    WaitHMIWork();

                    Thread.Sleep(500);



                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = true;
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
                    globaldata.starttimer = 0;
                    globaldata.startimerIsSet = true;


                }
                else
                {

                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
                }

            }
            catch(Exception ex)
            {
                Trace.Write(ex);
            }
        }

        private void 系统关闭ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (globaldata.connection_ip != null && globaldata.connection_ip != "")
            {
               
                    statestr = "系统停止中...";
                   
                    globaldata.OS_STOP = true;
                    hmiopt.WriteEndVal();
                
                    WaitHMIFree();
                  
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
               
            }
            else
            {

                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
            }
        }
        public void fireupopt(int flag, ushort time1, ushort time2)
        {
            hmiopt.FireUPWork(flag, time1, time2);
        }

        /// <summary>
        /// 更新所需，关闭HMI
        /// </summary>
        public void stopforupdatefirm()
        {
            if (globaldata.connection_ip != null && globaldata.connection_ip != "")
            {
               //、、 OSflag = !OSflag;
                //globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
                //SetTitleStatueName("系统停止中...", false);
                statestr = "系统停止中...";
                globaldata.OS_STOP = true;
                hmiopt.WriteEndVal();
                WaitHMIFree();
             //   SetTitleStatueName("系统停止...", false);
                statestr = "系统停止中...";

                //int tagnum = Convert.ToInt32(((PictureBox)panelMenu.Controls[14]).Tag);
                //((PictureBox)panelMenu.Controls[14]).Image = menuList.Images[tagnum];

                //((PictureBox)panelMenu.Controls[0]).Enabled = false;
                //((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[14];
                //((PictureBox)panelMenu.Controls[1]).Enabled = false;
                //((PictureBox)panelMenu.Controls[1]).Image = menuList.Images[15];
                //((PictureBox)panelMenu.Controls[2]).Enabled = false;
                //((PictureBox)panelMenu.Controls[2]).Image = menuList.Images[16];

                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
            }
            else
            {
                //string message = "系统处于离线状态...";
                //MessageBox.Show(message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
            }
        }

        /// <summary>
        /// 开始更新指令
        /// </summary>
        public void startupdatefirm()
        {
            hmiopt.WriteUpdateVal();
        }
        public void hair_sw(int val)
        {
            hmiopt.HAirSwitch(val);
        }
        private void 辅助工具ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            auxtool f_auxtool = new auxtool();
            int ret = 0;
            ushort[] firetime = new ushort[2];
            ret = mymodbus.GetFireUpTime(ref firetime);

            if (f_auxtool == null)
            {
                f_auxtool = new auxtool(firetime[0], firetime[1]);



                f_auxtool.auxtoolforfireup += new AUXTool(fireupopt);
                f_auxtool.sfupdatefirm += new StopForUpdateFirm(stopforupdatefirm);
                f_auxtool.updatefirm += new UpdateFirmCMD(startupdatefirm);
                f_auxtool.hairsw += new HAir_SW(hair_sw);


                f_auxtool.Show();
            }
            else
            {
                if (f_auxtool.IsDisposed)
                {
                    f_auxtool = new auxtool(firetime[0], firetime[1]);

                    f_auxtool.auxtoolforfireup += new AUXTool(fireupopt);

                    f_auxtool.sfupdatefirm += new StopForUpdateFirm(stopforupdatefirm);
                    f_auxtool.updatefirm += new UpdateFirmCMD(startupdatefirm);
                    f_auxtool.hairsw += new HAir_SW(hair_sw);

                    f_auxtool.Show();
                }
                else
                {
                    f_auxtool.setfireuptime(firetime[0], firetime[1]);

                    f_auxtool.auxtoolforfireup -= new AUXTool(fireupopt);
                    f_auxtool.auxtoolforfireup += new AUXTool(fireupopt);

                    f_auxtool.sfupdatefirm -= new StopForUpdateFirm(stopforupdatefirm);
                    f_auxtool.sfupdatefirm += new StopForUpdateFirm(stopforupdatefirm);
                    f_auxtool.updatefirm -= new UpdateFirmCMD(startupdatefirm);
                    f_auxtool.updatefirm += new UpdateFirmCMD(startupdatefirm);

                    f_auxtool.hairsw -= new HAir_SW(hair_sw);
                    f_auxtool.hairsw += new HAir_SW(hair_sw);
                    f_auxtool.Show();
                }
            }
        }



    }
}
