using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using System.IO;
using GcDevicePc.ProThread;
using System.Diagnostics;
using GcDevicePc.Common;

//using GcDevicePc.CK_UI;


namespace GcDevicePc
{
    public delegate void invokeDelegate();
    public partial class MainBase : Form
    {    
        
        Point dwPoint;
        bool moveFlag;

       /// <summary>
       /// 画图界面
       /// </summary>
       CurveDisPlay curdisplay = new CurveDisPlay();

        /// <summary>
        /// 侧边栏数据显示
        /// </summary>
        DataState dockPanelSideLeft = new DataState();


        /// <summary>
        /// 启动配置
        /// </summary>
        UserConfig appstartup = new UserConfig();

        //方法浏览窗口
        //BrowseForm f_browsemethod = new BrowseForm();
        //MethodScan f_browsemethod = new MethodScan();       

        /// <summary>
        /// 批处理
        /// </summary>
        RunTables f_runtable = new RunTables();

        /// <summary>
        /// 辅助工具
        /// </summary>
        auxtool f_auxtool = new auxtool();

        /// <summary>
        /// 仪器配置
        /// </summary>
        InstrConfig f_showcfg;

        /// <summary>
        /// 数据查询
        /// </summary>
        WaveTotalForm queryprocess = new WaveTotalForm();

        /// <summary>
        /// 数据校准
        /// </summary>
        AdjustFrom dataadjust = new AdjustFrom();

        /// <summary>
        /// 历史图谱
        /// </summary>
        HistChartForm Historical_Atlas = new HistChartForm();
      
        /// <summary>
        /// 新建方法
        /// </summary>
        MethodNameInputForm m_methodNameInputForm = new MethodNameInputForm();

        //开启系统线程
        // Thread Bat_Run;    
        Thread Connect_Status;
        //Thread SendToHW_TH;

        //Thread ModubusSlave_Test;
        //Thread Data_Record;

        /// <summary>
        /// HMI控制接口
        /// </summary>
        HMIControl hmiopt;

        /// <summary>
        /// HMI数据获取接口
        /// </summary>
        GcDataTh mymodbus;

        /// <summary>
        /// 本地数据保存接口
        /// </summary>
        ChannelDataSave mydatasave = new ChannelDataSave();

        /// <summary>
        /// 处理数据接口
        /// </summary>
        CKvocUpdata dataVOC = new CKvocUpdata();

        /// <summary>
        /// Modbus Slave 接口
        /// </summary>
        GCModbusSlave Slavetest;

        //状态改变信号
       // ManualResetEvent rsmre = new ManualResetEvent(false);
        ManualResetEvent datamre = new ManualResetEvent(false);
        ManualResetEvent conmre = new ManualResetEvent(false);

        /// <summary>
        /// 数据接收
        /// </summary>
        DataRcv mytcptest = new DataRcv();

        bool inifilec = false;
        ushort GCstatus = 9;
        public TextBox textconent;

        /// <summary>
        /// 软件运行时间
        /// </summary>
        System.DateTime startTime, endTime;
        System.TimeSpan time;

       
       /// <summary>
       /// 构造函数
       /// </summary>      
       public MainBase()
       {
            //MainBase初始化
            InitializeComponent();      
            //运行环境初始化
           // MainBase_InitAppConfig();
            //标题初始化
            //ManinBase_InitFormTitle();
            //菜单初始化
            //MainBase_InitFromMenu();

            dllInit();

            startTime = System.DateTime.Now;
       }

        ~MainBase()
        {
            try
            {
                dockPanelSideLeft.Close_Threading();
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
            }
            
        }

        /// <summary>
        /// 组件初始化
        /// </summary>
        private void dllInit() 
        {
            try
            {
                //初始化路径

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

                    CKVocAnalyzer.Config.Instance.ReadAxisRange();
                    //添加日志监听
                    //Trace.Listeners.Clear();
                    //Trace.Listeners.Add(new LogOperate.LogTraceListener(GlobalCKV.FolderLog)); ;
                    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);
            }
        }

        /// <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)
                {
                   
                    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();
                        }
                    }

                }

            }
        }

        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();
        }

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

        public void SetTitleStatueName(string text, bool flag)
        {
            textconent.Text = text;
            if(flag)
            {
                textconent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(149)))), ((int)(((byte)(237)))));
            }else
            {
                textconent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(254)))), ((int)(((byte)(185)))), ((int)(((byte)(16)))));
            }           
        }
        
        public void SendStopCMD()
        {
            try
            {
                hmiopt.WriteStopVal();
                WaitHMIFree();
            }
            catch 
            {
            }
           
        }
      
        public void fireupopt(int flag, ushort time1, ushort time2)
        {
            hmiopt.FireUPWork(flag, time1,time2);
        }

        //public void tcd_setdac(ushort port, ushort val)
        //{
        //    hmiopt.TCD_SetDAC(port, val);
        //}

        public void hair_sw( int val)
        {
            hmiopt.HAirSwitch( val);
        }

        //public void tcd_sw(ushort port)
        //{
        //    hmiopt.TCD_Switch(port);
        //}


        /// <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);
                globaldata.OS_STOP = true;
                hmiopt.WriteEndVal();
                WaitHMIFree();
                SetTitleStatueName("系统停止...", false);

                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();
        }


        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled)
            {
            }
            else
            {
            }
        }

        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;
                }
            }
        }

        public void WaitHMIFree()
        {
            this.backgroundWorker1.RunWorkerAsync();
            WaitForm form = new WaitForm(this.backgroundWorker1);
            form.ShowDialog(this);
            form.Close();
        }

        private void bgWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
               // MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled)
            {
            }
            else
            {
            }
        }

        private void bgWorker2_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;
                }
            }
        }

        public void WaitHMIWork()
        {
            this.bgWorker2.RunWorkerAsync();
            WaitForm form = new WaitForm(this.bgWorker2);
            form.ShowDialog(this);
            form.Close();
        }


        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();
                    }
                    
                }
            }        
        }

        /// <summary>
        /// 检测本地默认目录
        /// </summary>
        private void MainBase_InitAppConfig()
        {
            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_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;
        }


        /// <summary>
        /// 初始化标题栏
        /// </summary>
        private void ManinBase_InitFormTitle()
        {
            string tmpFileName;
            this.mixlogo.Image = logoList.Images[0];
            this.companyname.Text = "Smart TetChrom";
            this.softname.Text = "在线色谱软件";
            this.softversion.Text = " ";

            tmpFileName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;

            if (tmpFileName == null)
            {
                this.now_method.Text = "当前运行方法： 未加载";
            }
            else
            {
                this.now_method.Text = "当前运行方法：" + tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1);
            }   
        }

        /// <summary>
        /// 初始化菜单栏
        /// </summary>
        private void MainBase_InitFromMenu()
        {
            int tagnum;
            //添加panelmemu里面内容
            for (int i = 0; i < 15; i++)
            {
                if (i != 10)
                {
                    PictureBox picture = new PictureBox();
                    picture.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(243)))));
                   
                    if(i > 10)
                    {
                        picture.Image = this.menuList.Images[i-1];
                        picture.Tag = i - 1;
                        picture.TabIndex = i - 1;
                    }
                    else
                    {
                        //if(i < 3)
                        //{
                        //    picture.Image = this.menuList.Images[i+14];
                        ////    picture.Enabled = false;
                        //}else
                        //{
                            picture.Image = this.menuList.Images[i];
                       // }                       
                        picture.Tag = i;
                        picture.TabIndex = i;
                    }
                   
                    picture.Size = new System.Drawing.Size(57, 57);
                  
                    picture.Name = "menubtn" + i.ToString();
                   
                    picture.TabStop = false;
                    this.panelMenu.Controls.Add(picture);
                }
                else
                {
                    Panel textPanel = new Panel();
                    textPanel.Name = "panel1";
                    textPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(243)))));
                    textPanel.Size = new System.Drawing.Size(100, 62);
                    textPanel.TabIndex = 10;
                    this.panelMenu.Controls.Add(textPanel);
                }
            }


            try
            {
                foreach (Control c in panelMenu.Controls)
                {
                    if (c is PictureBox)
                    {
                         tagnum = Convert.ToInt32(c.Tag);
                        if(tagnum > 2 && tagnum < 13)
                        {
                            c.MouseDown += new MouseEventHandler(btn_MouseDown);
                            c.MouseHover += new EventHandler(btn_MouseHover);
                            c.MouseLeave += new EventHandler(btn_MouseLeave);
                            c.MouseUp += new MouseEventHandler(btn_MouseUp);                          
                        }
                        
                        if(tagnum >=0 && tagnum <=2)
                        {
                           // c.Image = menuList.Images[tagnum + 14];
                          //     c.MouseDown += new MouseEventHandler(contrl_MouseDown);
                          //  c.MouseHover += new EventHandler(contrl_MouseHover);
                          //  c.MouseLeave += new EventHandler(contrl_MouseLeave);
                          //     c.MouseUp += new MouseEventHandler(contrl_MouseUp);
                        }

                        if(tagnum == 13)
                        {
                           // c.Click += new EventHandler(btn_Click);
                        }

                        c.Click += new EventHandler(btn_Click);
                        
                    }
                }
            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
            }

            Label runtime = new Label();
            runtime.Text = DateTime.Now.ToString("hh:mm:ss");
            runtime.Location = new Point(0,30);

            textconent = new TextBox();
            textconent.Enabled = false;
            textconent.Width = 100;

            if (globaldata.connection_ip != null && globaldata.connection_ip != "")
            {
                textconent.Text = "设备联机...";
                textconent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(149)))), ((int)(((byte)(237)))));
            }
            else
            {
                textconent.Text = "未联机...";
                textconent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(254)))), ((int)(((byte)(185)))), ((int)(((byte)(16)))));
            }
            textconent.BackColor = Color.White;
            ((Panel)this.panelMenu.Controls[10]).Controls.Add(textconent);
            ((Panel)this.panelMenu.Controls[10]).Controls.Add(runtime);

           //// PID测试
           // Button pidtest = new Button();
           // pidtest.Height = 50;
           // pidtest.Width = 50;
           // pidtest.Text = "PID测试";
           // pidtest.Click += new EventHandler(pidtest_test);
           // this.panelMenu.Controls.Add(pidtest);
            // ((Panel)this.panelMenu.Controls[15]).Controls.Add(pidtest);

            //文件更新
            //Button filetest = new Button();
            //filetest.Height = 50;
            //filetest.Width = 50;
            //filetest.Text = "更新测试";
            //filetest.Click += new EventHandler(filetest_test);
            //this.panelMenu.Controls.Add(filetest);
            
            ////初始化开始，停止，取消
            ((PictureBox)panelMenu.Controls[0]).Image = this.menuList.Images[14];
            ((PictureBox)panelMenu.Controls[1]).Image = this.menuList.Images[15];
            ((PictureBox)panelMenu.Controls[2]).Image = this.menuList.Images[16];

        }
     
        private void contrl_MouseUp(object sender, MouseEventArgs e)
        {
            PictureBox picturebtn = (PictureBox)sender;
            int tagnum = Convert.ToInt32(picturebtn.Tag);
            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true)
                picturebtn.Image = menuList.Images[tagnum + 14];          
        }

        private void contrl_MouseLeave(object sender, EventArgs e)
        {
            PictureBox picturebtn = (PictureBox)sender;
            int tagnum = Convert.ToInt32(picturebtn.Tag);
       //     if (globaldata.system_Statue == true)
       //         picturebtn.Image = menuList.Images[tagnum];
           
        }

        private void contrl_MouseHover(object sender, EventArgs e)
        {
            PictureBox picturebtn = (PictureBox)sender;
            int tagnum = Convert.ToInt32(picturebtn.Tag);
            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true)
                picturebtn.Image = menuList.Images[tagnum + 28];  
            
        }

        private void contrl_MouseDown(object sender, MouseEventArgs e)
        {
            PictureBox picturebtn = (PictureBox)sender;
            int tagnum = Convert.ToInt32(picturebtn.Tag);
            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true)
                picturebtn.Image = menuList.Images[tagnum + 14];     
        }

        /// <summary>
        /// PID测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pidtest_test(object sender, EventArgs e)
        {
            //PID_Form pidf = new PID_Form();
            //pidf.Show();
        }

        /// <summary>
        /// 文件测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void filetest_test(object sender, EventArgs e)
        {
            //UpdateTest filetest = new UpdateTest();
            //filetest.Show();
        }
      
        private void Load_Win()
        {
            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;

                            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;

                            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);                 
                }
                
                textconent.Text = "设备联机";
                curdisplay.Text = "前检测器";
                textconent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(149)))), ((int)(((byte)(237)))));
            }
            else
            {
                
                textconent.Text = "未联机";
                textconent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(254)))), ((int)(((byte)(185)))), ((int)(((byte)(16)))));
     
                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;
              
        }

        private void MainBase_Load(object sender, EventArgs e)
        {

            //if (f_netconfig.IsDisposed)
            //{
            //    f_netconfig = new ListViewTest();
            //}

            globaldata.starttimer = 0x7FFFFFFF;
           // Console.WriteLine("MainBase_Load  MainBase_Load");
            //f_netconfig.MainBase_Load += new ChangeMainShow(MainBase_Load);
            
            //this.windowState = FormWindowState.Maximized;

            string file = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunFolder + "\\startup.ini";
            INIOperation test = new INIOperation(file);
            string opensys = test.INIGetStringValue("StartUp", "打开系统", "0");
           // string runtype = test.INIGetStringValue("StartUp", "运行类型", null);
            Load_Win();

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

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

            //this.panelMenu.Controls[0].Enabled = true;
            //this.panelMenu.Controls[1].Enabled = false;
            //this.panelMenu.Controls[2].Enabled = false;
        }

        private void btn_Click(object sender, EventArgs e)
        {
            PictureBox picturebtn = (PictureBox)sender;
            int tagnum = Convert.ToInt32(picturebtn.Tag);

            switch (tagnum)
            {
                case 0:
                    Startbtn_Click(sender, e);  //开始
                    break;
                case 1:
                    Stopbtn_Click(sender, e);  //停止
                    break;
                case 2:
                    Cancelbtn_Click(sender, e);   //取消
                    break;
                case 3:
                    newbtn_Click(sender, e);   //新建方法
                    break;
                case 4:
                    browse_Click(sender, e);   //打开方法  
                    break;
                case 5:
                  //  SingleAnal_Click(sender, e);  //快速运行
                    helptool_Click(sender, e);
                    break;
                case 6:
                    batdeal_Click(sender, e);    //智能运行          
                    break;
                case 7:
                    openbtn_Click(sender, e);    //方法查询                 
                    break;
                case 8:
                    netcfg_Click(sender, e);    //通讯设置          
                    break;
                case 9:
                    showcfg_Click(sender, e);   //仪器配置
                    break;
                case 10:
                    showdata_Click(sender,e);  //数据查询
                    break;
                case 11:
                    datacalibration_Click(sender,e); //数据校准
                    break;
                case 12:
                    historyrec_Click(sender,e);  //历史文件
                   // Test mytest = new Test();
                   // mytest.Show();
                    break;
                case 13:
                    openSys_Click(sender, e);      //开启系统        
                    break;
            }
        }

        bool OSflag = false;
        private void hmistatus_opensys()
        {
            if (globaldata.connection_ip != null && globaldata.connection_ip != "")
            {
                if (!OSflag)
                {
                    OSflag = !OSflag;
                
                    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();
                    }

                    int tagnum = Convert.ToInt32(((PictureBox)panelMenu.Controls[14]).Tag);
                    ((PictureBox)panelMenu.Controls[14]).Image = menuList.Images[tagnum + 14];
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = true;
                    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>
        private void autoclosesys_Click()
        {
            if (globaldata.connection_ip != null && globaldata.connection_ip != "")
            {                              
                    OSflag = !OSflag;
                    //globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
                    
                    SetTitleStatueName("系统停止中...", false);
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;
                    globaldata.OS_STOP = true;
                    hmiopt.WriteEndVal();
                    //LogHelper.I("autoclosesys_Click", "WriteEndVal");
                    WaitHMIFree();
                    SetTitleStatueName("系统停止...", false);

                    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;
            }
        }



        private void autoopensys_Click()
        {
            if (globaldata.connection_ip != null && globaldata.connection_ip != "")
            {
                if (!OSflag)
                {
                    OSflag = !OSflag;
                    hmiopt.WriteStopVal();
                    //LogHelper.I("autoopensys_Click1", "WriteStopVal");
                    SetTitleStatueName("系统准备中...", true);
                    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);

                    int tagnum = Convert.ToInt32(((PictureBox)panelMenu.Controls[14]).Tag);
                    ((PictureBox)panelMenu.Controls[14]).Image = menuList.Images[tagnum + 14];
                   
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = true;                  
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;

                }
                else
                {
                    OSflag = !OSflag;
                    //globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
                    //globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;  
                    SetTitleStatueName("系统停止中...", false);
                    globaldata.OS_STOP = true;
                    hmiopt.WriteEndVal();
                    //LogHelper.I("autoopensys_Click2", "WriteEndVal");
                    WaitHMIFree();
                    SetTitleStatueName("系统停止...", false);

                    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;
            }
        }


        private void openSys_Click(object sender, EventArgs e)
        {
            if (globaldata.connection_ip != null && globaldata.connection_ip != "")
            {   
                if (!OSflag)
                {
                    OSflag = !OSflag;
                    hmiopt.WriteStopVal();
                    //LogHelper.I("openSys_Click", "WriteStopVal");
                    //globaldata.OS_STOP = false;
                    SetTitleStatueName("系统准备中...", true);
                    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);

                    int tagnum = Convert.ToInt32(((PictureBox)panelMenu.Controls[14]).Tag);
                    ((PictureBox)panelMenu.Controls[14]).Image = menuList.Images[tagnum + 14];
                                    
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = true;
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
                    globaldata.starttimer = 0;
                    globaldata.startimerIsSet = true;

                }else
                {
                    OSflag = !OSflag;
                    //globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;  
                    //globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
                    SetTitleStatueName("系统停止中...", false);
                    globaldata.OS_STOP = true;
                    hmiopt.WriteEndVal();
                    //LogHelper.I("openSys_Click", "WriteEndVal");
                    WaitHMIFree();
                    SetTitleStatueName("系统停止...", false);

                    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;
            }
        }

        private void historyrec_Click(object sender, EventArgs e)
        {
            //int ret;

            //if (globaldata.m_configDlg.Visible == true)
            //    return;

            //OpenFileDialog fileDlg = new OpenFileDialog();
            //fileDlg.Multiselect = false;
            //fileDlg.InitialDirectory = Application.StartupPath + "\\历史数据";
            //fileDlg.Title = "请选择方法文件";
            //fileDlg.Filter = "配置文件(*.tw)|*.tw";
            //if (fileDlg.ShowDialog() == DialogResult.OK)
            //{
            //    string file = fileDlg.FileName;
            //    file = file.Substring(file.LastIndexOf("\\") + 1);
            //    //enableforhd(file);  
            //  //  this.curdisplay.enable_for_HD(file);
            //}

            if (Historical_Atlas.IsDisposed)    //历史谱图
            {
                Historical_Atlas = new HistChartForm();
                Historical_Atlas.Show();

            }
            else
            {
                Historical_Atlas.Show();
            }         
        }

        private void datacalibration_Click(object sender, EventArgs e)
        {
            if (dataadjust.IsDisposed)
            {
                dataadjust = new AdjustFrom();
                dataadjust.Show();
            }
            else
            {
                dataadjust.Show();
            }
        }


        private void helptool_Click(object sender, EventArgs e)
        {
            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();
                }
            }
        }



        private void batdeal_Click(object sender, EventArgs e)
        {
            if (f_runtable.IsDisposed)
            {
                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();
            }
            else
            {
                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();
            }
        }

        private void savebtn_Click(object sender, EventArgs e)
        {
            if (globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName != null || globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_OpenMethodName !=null)
                globaldata.m_configDlg.Save_Method();
        }

        private void btn_MouseDown(object sender, EventArgs e)
        {
            PictureBox picturebtn = (PictureBox)sender;
            int tagnum = Convert.ToInt32(picturebtn.Tag);           
            picturebtn.Image = menuList.Images[tagnum + 14];
        }

        private void btn_MouseUp(object sender, EventArgs e)
        {
            PictureBox picturebtn = (PictureBox)sender;
            int tagnum = Convert.ToInt32(picturebtn.Tag);            
            picturebtn.Image = menuList.Images[tagnum + 14];
        }

        private void btn_MouseHover(object sender, EventArgs e)
        {
            PictureBox picturebtn = (PictureBox)sender;
            int tagnum = Convert.ToInt32(picturebtn.Tag);                                   
            picturebtn.Image = menuList.Images[tagnum + 14];                                                    
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            PictureBox picturebtn = (PictureBox)sender;
            int tagnum = Convert.ToInt32(picturebtn.Tag);           
            picturebtn.Image = menuList.Images[tagnum];        
        }

        //标题栏 最小化，全屏切换，关闭事件
        private void mixbtn_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void changebtn_Click(object sender, EventArgs e)
        {
            if (this.changebtn.Text == "口")
                this.windowState = FormWindowState.Maximized;
            else
                this.windowState = FormWindowState.Normal;
        }

        public System.Windows.Forms.DialogResult ShowQuitBox()
        {
            return new QuitForm().ShowDialog();
        }

        private void closebtn_Click(object sender, EventArgs e)
        {
            DialogResult dr;
            dr = ShowQuitBox();

            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);
            }

    
        }

        public FormWindowState windowState
        {
            get
            {
                return this.WindowState;
            }
            set
            {
                if (value == FormWindowState.Normal)
                {
                    this.changebtn.Text = "口";
                    this.WindowState = FormWindowState.Normal;
                }
                else if (value == FormWindowState.Maximized)
                {
                    this.changebtn.Text = "吕";
                    this.WindowState = FormWindowState.Maximized;
                }
            }
        }

        private void paneltitle_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.WindowState = this.WindowState == FormWindowState.Normal ? FormWindowState.Maximized : FormWindowState.Normal;
            if (this.WindowState == FormWindowState.Normal)
            {
                this.changebtn.Text = "口";
            }
            else
            {
                this.changebtn.Text = "吕";
            }
        }

        //窗口变化自适应
        private void MainBase_SizeChanged(object sender, EventArgs e)
        {
            //改变标题栏
            this.paneltitle.Width = this.Width;
            Point closep = new Point(this.Width - 30, 0);
            this.closebtn.Location = closep;
            Point changep = new Point(this.Width - 60, 0);
            this.changebtn.Location = changep;
            Point mixp = new Point(this.Width - 90, 0);
            this.mixbtn.Location = mixp;

            this.panelMenu.Width = this.Width;

            this.showPanel.Width = this.Width;
            this.showPanel.Height = this.Height - this.paneltitle.Height - this.panelMenu.Height;
        }

        private void paneltitle_MouseDown(object sender, MouseEventArgs e)
        {
           if (e.Button == MouseButtons.Left)
            {
                dwPoint = new Point(-e.X, -e.Y);
                moveFlag = true;
            }
        }

        private void paneltitle_MouseMove(object sender, MouseEventArgs e)
        {
            if (moveFlag)
            {
                Point mousePoint = Control.MousePosition;
                mousePoint.Offset(dwPoint.X, dwPoint.Y);
                Location = mousePoint;
            }
        }

        private void paneltitle_MouseUp(object sender, MouseEventArgs e)
        {
            if (moveFlag)
            {
                moveFlag = false;
            }
        }

        //网络配置事件
        private void netcfg_Click(object sender, EventArgs e)
        {
            // this.netcfg.Image = menuList.Images[25];
            //if (f_netconfig.IsDisposed)
            //{
            //    f_netconfig = new ListViewTest();
            //    f_netconfig.MainBase_Load += new ChangeMainShow(MainBase_Load);
            //    f_netconfig.Show();
            //}
            //else
            //{
            //    f_netconfig.Show();
            //}

            if (appstartup.IsDisposed)
            {
                appstartup = new UserConfig();
                appstartup.Show();
            }
            else
            {
                appstartup.Show();
            }

        }

        private void showcfg_Click(object sender, EventArgs e)
        {
            int ret = 0;
            ushort[] version = new ushort[12];
            ret = mymodbus.GetFireWareVersion(ref version);

            if (f_showcfg == null)
            {
                f_showcfg = new InstrConfig(version);
                f_showcfg.Show();
            }
            else
            {
                if (f_showcfg.IsDisposed)
                {
                    f_showcfg = new InstrConfig(version);
                    f_showcfg.Show();
                }
                else
                {
                    f_showcfg.Show();
                }

            }

           
        }

        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void browse_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();
            }



            //OpenFileDialog fileDlg = new OpenFileDialog();
            //fileDlg.Multiselect = false;
            //fileDlg.InitialDirectory = Application.StartupPath + "\\仪器方法";
            //fileDlg.Title = "请选择方法文件";
            //fileDlg.Filter = "配置文件(*.ini)|*.ini";
            //int ret;

            //if (fileDlg.ShowDialog() == DialogResult.OK)
            //{
            //    string file = fileDlg.FileName;
            //    globaldata.cur_MethodName = file;
            //    this.inifilec = true;

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

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

            //    this.now_method.Text = "当前运行方法：" + globaldata.cur_MethodName.Substring(globaldata.cur_MethodName.LastIndexOf("\\") + 1);

            //    if (globaldata.connection_ip != null)
            //    {
            //        singlemodbus.WriteStopVal();
           
            //        this.backgroundWorker1.RunWorkerAsync();
            //        WaitForm form = new WaitForm(this.backgroundWorker1);
            //        form.ShowDialog(this);
            //        form.Close();
                   

            //        string tmpname = globaldata.cur_MethodName.Substring(globaldata.cur_MethodName.LastIndexOf("\\") + 1);
            //        FileServerClient singlesend = new FileServerClient();
            //        singlesend.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);
            //        ret = singlesend.WtClientCopytoServer("SingleAnal.ini", globaldata.cur_MethodName, "\\Hard Disk\\仪器方法\\");

            //       // ret = singlesend.WtClientCopytoServer(tmpname, globaldata.cur_MethodName, "\\Hard Disk\\仪器方法\\");

            //        singlesend.WtClientClose();

            //        globaldata.RunType = 0;

            //        if (inifilec && globaldata.system_Statue)
            //        {
            //            singlemodbus.WriteOpenVal();
            //        }
            //    }
            //}
        }

        private void newbtn_Click(object sender, EventArgs e)
        {
            //Process kbpr = System.Diagnostics.Process.Start("osk.exe");
            if (m_methodNameInputForm.IsDisposed)
            {
                m_methodNameInputForm = new MethodNameInputForm();
                m_methodNameInputForm.Show();
            }
            else
            {
                m_methodNameInputForm.Show();
            }
            //if (kbpr.HasExited)
            //{
            //    kbpr = System.Diagnostics.Process.Start("osk.exe");
            //}
        }

        private void openbtn_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 SingleAnal_Click(object sender, EventArgs e)
        {
            if (globaldata.m_configDlg.Visible == true)
                return;

            if(this.inifilec)
            {
                if (globaldata.connection_ip != null && globaldata.connection_ip != "")
                {
                    FileServerClient singlesend = new FileServerClient();
                    singlesend.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);
                    singlesend.WtClientCopytoServer("SingleAnal.ini", globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName, globaldata.remoteFolder + "仪器方法\\");
                    singlesend.WtClientClose();

                    hmiopt.WriteStopVal();
                    //LogHelper.I("SingleAnal_Click1", "WriteStopVal");
                    //singlemodbus.WriteStopVal();
                    WaitHMIFree();
                    hmiopt.WriteSingleVal();
                    //singlemodbus.WriteSingleVal();
               
                    textconent.Text = "快速运行...";
                    textconent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(149)))), ((int)(((byte)(237)))));

                    now_method.Text = "当前运行方法：" + globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName.Substring(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName.LastIndexOf("\\") + 1);

                }

            }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.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName = file;

                    if (globaldata.connection_ip != null && globaldata.connection_ip != "")
                    {
                        FileServerClient singlesend = new FileServerClient();
                        singlesend.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);
                        singlesend.WtClientCopytoServer("SingleAnal.ini", globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName,globaldata.remoteFolder + "仪器方法\\");
                        singlesend.WtClientClose();

                        Thread.Sleep(500);
                        hmiopt.WriteStopVal();
                        //LogHelper.I("SingleAnal_Click2", "WriteStopVal");
                        //singlemodbus.WriteStopVal();
                        WaitHMIFree();
                        hmiopt.WriteSingleVal();
                        //singlemodbus.WriteSingleVal();

                        textconent.Text = "快速运行...";
                        textconent.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(149)))), ((int)(((byte)(237)))));

                        now_method.Text = "当前运行方法：" + globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName.Substring(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName.LastIndexOf("\\") + 1);
                    }
                    else
                    {
                        now_method.Text = "当前运行方法：" + "未传输";
                    }
                }
            }            
        }

        string twfilename = null;
        public void startbtn()
        {

            string tmpFileName;

            tmpFileName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;
            if (globaldata.connection_ip != null && globaldata.connection_ip != "")
            {
                if (tmpFileName != null)
                {
                    twfilename = tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1);
                    twfilename = twfilename.Remove(twfilename.LastIndexOf("."));
                    twfilename += "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".tw";
                    twfilename = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.DataFolder, twfilename);
                }

                if (twfilename == null)
                {
                    twfilename += "default_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".tw";
                }

             //  AESfile savefile = new AESfile(twfilename);
            //    ret = savefile.Create_filetw();

             //   if (ret)
                {
                    globaldata.startflag = true;
                    globaldata.stopflag = false;
                    globaldata.cancelflag = false;
                    globaldata.startclear = true;
                    globaldata.starttimer = 0;
                    globaldata.startimerIsSet = true;
                    globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_DataName = twfilename;
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 1;
                    //globaldata.work_Statue = 1;

      //          }
        //        else
       //         {
       //             MessageBox.Show("创建失败!");
                }
            }

        }

        private void Startbtn_Click(object sender, EventArgs e) //开始
        {        
            
           // if(globaldata.system_Statue == true && globaldata.RunType == 0 )
            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true && globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
            {
                //this.panelMenu.Controls[0].Enabled = false;
                //int tagnum = Convert.ToInt32(((PictureBox)panelMenu.Controls[0]).Tag);
                //((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[tagnum + 14];

                ((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[14];
                this.panelMenu.Controls[0].Enabled = false;
                this.panelMenu.Controls[1].Enabled = true;
                ((PictureBox)panelMenu.Controls[1]).Image = menuList.Images[1];
                this.panelMenu.Controls[2].Enabled = true;
                ((PictureBox)panelMenu.Controls[2]).Image = menuList.Images[2];

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

                startbtn();
            }           
        }

        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 Stopbtn_Click(object sender, EventArgs e)
        {
            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true)
            {
                //int tagnum = Convert.ToInt32(((PictureBox)panelMenu.Controls[0]).Tag);
                //((PictureBox)panelMenu.Controls[0]).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];

                hmiopt.WriteStopVal();
                //LogHelper.I("Stopbtn_Click", "WriteStopVal");
               // singlemodbus.WriteStopVal();
                WaitHMIFree();
             
                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                {
                    hmiopt.WriteOpenVal();
                    //singlemodbus.WriteOpenVal();
                }
                stopbtn();
            }                   
        }

        public void cancelbtn()
        {
            globaldata.startflag = false;
            globaldata.stopflag = false;
            globaldata.cancelflag = true;
            globaldata.starttimer = 0x7FFFFFFF;
            Console.WriteLine("cancelbtn  cancelbtn");
            if (globaldata.connection_ip != null && globaldata.connection_ip != "")
            {                                      
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 3;               
            }

            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 Cancelbtn_Click(object sender, EventArgs e)
        {        
            if(globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true)
            {
                //int tagnum = Convert.ToInt32(((PictureBox)panelMenu.Controls[0]).Tag);
                //((PictureBox)panelMenu.Controls[0]).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];

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

                cancelbtn();
            }
        }

        void ChangeButton(ushort flag)
        {
            switch(flag)
            {
                case 0:       //关闭所有
                            ((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];
                            break;
                case 1:       //只使能开始
                            ((PictureBox)panelMenu.Controls[0]).Enabled = true;
                            ((PictureBox)panelMenu.Controls[1]).Enabled = false;
                            ((PictureBox)panelMenu.Controls[2]).Enabled = false;
                            ((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[0];                            
                            ((PictureBox)panelMenu.Controls[1]).Image = menuList.Images[15];                            
                            ((PictureBox)panelMenu.Controls[2]).Image = menuList.Images[16];
                            break;
                case 2:       //使能停止和取消
                            ((PictureBox)panelMenu.Controls[0]).Enabled = false;
                            ((PictureBox)panelMenu.Controls[1]).Enabled = true;
                            ((PictureBox)panelMenu.Controls[2]).Enabled = true;
                            ((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[14];
                            ((PictureBox)panelMenu.Controls[1]).Image = menuList.Images[1];
                            ((PictureBox)panelMenu.Controls[2]).Image = menuList.Images[2];
                            break;
                case 3:      //开启所有
                            ((PictureBox)panelMenu.Controls[0]).Enabled = true;
                            ((PictureBox)panelMenu.Controls[1]).Enabled = true;
                            ((PictureBox)panelMenu.Controls[2]).Enabled = true;
                            ((PictureBox)panelMenu.Controls[0]).Image = menuList.Images[0];
                            ((PictureBox)panelMenu.Controls[1]).Image = menuList.Images[1];
                            ((PictureBox)panelMenu.Controls[2]).Image = menuList.Images[2];
                            break;
            }
        }

        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;
            }

            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)
        {        
            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], "无")); 
            }
        }

      
        private void showdata_Click(object sender, EventArgs e)
        {
            if (queryprocess.IsDisposed)
            {
                queryprocess = new WaveTotalForm();
                queryprocess.Show();
            }
            else
            {
                queryprocess.Show();
            }
        }

        private void sfruntimer_Tick(object sender, EventArgs e)
        {
            endTime = System.DateTime.Now;
            time = endTime - startTime;
            ((Label)((Panel)this.panelMenu.Controls[10]).Controls[1]).Text =time.Days.ToString() + "天" + time.Hours.ToString() + "时"+ time.Minutes.ToString() + "分"+ time.Seconds.ToString()+"秒";
        }

    }
}
