using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using GcDevicePc.ProThread;
using GcDevicePc.Common;
using System.Threading;
using GcDevicePc.CK_UI;
using Ini.Net;
using System.Runtime.InteropServices;
using GcDevicePc.ConfigMethod;
using GcDevicePc.Controls;
using GcDevicePc.GCBuffer;
using GcDevicePc.IniParam;

namespace GcDevicePc
{
    public partial class MDIBase : Form
    {
        //private int childFormNumber = 0;
        private static FormUser  _userForm;  //用户界面
        private static Formdebug _debugForm;  //调试界面

        private string Formstr;//窗口名称
        private string statestr;//状态信息
       // private Color stateColor=new Color();//状态颜色;
        private bool IsStateColor = false;
        System.DateTime startTime;  //系统启动时间
        TimeSpan timespan;

        bool inifilec = false;  //方法文件是否加载


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

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

        /// <summary>
        /// Modbus Slave 变量
        /// </summary>
        GCModbusSlave Slavetest;

        /// <summary>
        /// Modbus Slave 485 变量
        /// </summary>
        GCModbusSlave485 Slave485test;

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

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

        private DataOutput wtd624xOutput = new DataOutput();

        #region Author by zjx
        /// <summary>
        /// 组件初始化
        /// </summary>
        private void DllInit()
        {
            try
            {
                if (CKVocAnalyzer.Config.Instance.ReadPath())
                {
                    CKVocAnalyzer.VOCEntityConfig.Instance.vocinit();
                    CKVocAnalyzer.VOCEntityConfig.Instance.SetAutoAdjust();
                    CKVocAnalyzer.Config.Instance.ReadAxisRange();
                    LogOperate.LogInit.Instance.path = CKVocAnalyzer.GlobalCKV.FolderLog;
                    LogOperate.LogInit.Instance.Init();
                    CKVocAnalyzer.GlobalCKV.tcpservice.tcpStart(CKVocAnalyzer.GlobalCKV.hostadd, CKVocAnalyzer.GlobalCKV.tcpport);
                    //自动删除
                    SpaceM.SpaceThread sthread = new SpaceM.SpaceThread(CKVocAnalyzer.GlobalCKV.HistDataPath,CKVocAnalyzer.GlobalCKV.SpaceSize,CKVocAnalyzer.GlobalCKV.SpaceTimes);
                    sthread.SpaceStart();

                    Log.Info("System Init Success");
                }
                else
                {
                    Log.Error("System Init Failed, Plesae Check Config File");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }
        #endregion


        /// <summary>
        /// 构造函数
        /// </summary>
        public MDIBase()
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
        }


        #region 数据保存定时事件
        private MillisecondTimer _logTimer;
        private void InitLogTimer()
        {
            _logTimer = new MillisecondTimer();
            _logTimer.Tick += logTimer_Tick; ;
            _logTimer.Interval = 1000 * 60; //1min
            _logTimer.Start();
        }

        private void logTimer_Tick(object sender, EventArgs e)
        {
            string status_info = "";

            string other_info = "";

            string temp_info = "";

            if (globaldata.m_hmibuffer.gcinfo.hmistatus == 4)
            {
                status_info = " HMI进行单次运行 ";
            }
            else if (globaldata.m_hmibuffer.gcinfo.hmistatus == 2)
            {
                status_info = " HMI进行批处理 ";
            }
            else if (globaldata.m_hmibuffer.gcinfo.hmistatus == 0)
            {
                status_info = " HMI空闲 ";
            }
            else
            {
                status_info = " HMI状态未知 ";
            }

            if (globaldata.m_hmibuffer.gcinfo.hmistatus == 4 || globaldata.m_hmibuffer.gcinfo.hmistatus == 2)
            {
                switch (globaldata.m_hmibuffer.gcinfo.methodstatus)
                {
                    case 0:
                    case 1:
                        status_info += "方法空闲 ";
                        break;
                    case 2:
                        status_info += "方法平衡中 ";
                        break;
                    case 3:
                        status_info += "方法已就绪 ";
                        break;
                    case 4:
                    case 5:
                        status_info += "方法运行中 ";

                        break;
                    case 6:
                        status_info += "方法后处理 ";
                        break;
                    case 7:
                        status_info += "方法后处理完毕 ";
                        break;
                    case 8:
                        status_info += "信号稳定中 ";
                        break;
                    case 9:
                        status_info += "设备断开 ";
                        break;
                    default:
                        status_info += "设备连接 ";
                        break;
                }
            }

            if (globaldata.m_hmibuffer.gcinfo.hmistatus == 2)
            {
                status_info += "运行进度 " + globaldata.m_hmibuffer.gcinfo.batno.ToString() + "/" +
                               globaldata.m_hmibuffer.gcinfo.batruncount.ToString();
            }

            Log.HmiInfo(status_info);

            other_info = "点火状态:";
            switch (globaldata.m_dpbuffer.ShowList.showDet.fDetStatue)
            {
                case 0:
                    other_info += "未点火";
                    break;
                case 1:
                    other_info += "点火中";
                    break;
                case 2:
                    other_info += "点火成功";
                    break;
                case 3:
                    other_info += "点火失败";
                    break;
                case 4:
                    other_info += "火焰熄灭";
                    break;
                case 5:
                    other_info += "重新点火";
                    break;
                default:
                    other_info += "状态错误";
                    break;
            }

            other_info += " FID:" + globaldata.m_dpbuffer.ShowList.showDet.fDetValue.ToString("0.000");

            Log.HmiInfo(other_info);
            if (CProfileDevice.m_DevParam.syspara.u16InjPortFront == 1)
            {
                temp_info += "前进样口:" + globaldata.m_dpbuffer.ShowList.showtemp.FPActualTemp.ToString("#0.00") + " / " +
                             globaldata.m_dpbuffer.ShowList.showtemp.FPSetTemp.ToString("0");
            }

            if (CProfileDevice.m_DevParam.syspara.u16InjPortBehind == 1)
            {
                temp_info += "后进样口:" + globaldata.m_dpbuffer.ShowList.showtemp.BPActualTemp.ToString("#0.00") + " / " +
                             globaldata.m_dpbuffer.ShowList.showtemp.BPSetTemp.ToString("0");
            }

            if (CProfileDevice.m_DevParam.syspara.u16Col == 1)
            {
                temp_info += "柱箱:" + globaldata.m_dpbuffer.ShowList.showtemp.ColActualTemp.ToString("#0.00") + " / " +
                             globaldata.m_dpbuffer.ShowList.showtemp.ColSetTemp.ToString("0");
            }

            if (CProfileDevice.m_DevParam.syspara.u16DetNum >= 1)
            {
                if (CProfileDevice.m_DevParam.syspara.u16DetFront == 1)
                {
                    temp_info += "前检测:" + globaldata.m_dpbuffer.ShowList.showtemp.fDetActualTemp.ToString("#0.00") +
                                 " / " + globaldata.m_dpbuffer.ShowList.showtemp.fDetSetTemp.ToString("0");
                }

                if (CProfileDevice.m_DevParam.syspara.u16DetInter == 1)
                {
                    temp_info += "中检测:" + globaldata.m_dpbuffer.ShowList.showtemp.iDetActualTemp.ToString("#0.00") +
                                 " / " + globaldata.m_dpbuffer.ShowList.showtemp.iDetSetTemp.ToString("0");
                }

                if (CProfileDevice.m_DevParam.syspara.u16DetBehind == 1)
                {
                    temp_info += "后检测:" + globaldata.m_dpbuffer.ShowList.showtemp.bDetActualTemp.ToString("#0.00") +
                                 " / " + globaldata.m_dpbuffer.ShowList.showtemp.bDetSetTemp.ToString("0");
                }

                Log.HmiInfo(temp_info);
            }
        }

        #endregion

        /// <summary>
        /// 主窗口载入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MDIBase_Load(object sender, EventArgs e)
        {
            DllInit();

            InitConfig();

            //系统检测日志
            InitLogTimer();

            _debugForm = new Formdebug();
            _debugForm.MdiParent = this;
            _debugForm.Dock = DockStyle.Fill;
            _debugForm.Show();

            // debugForm.Hide();
            _userForm = new FormUser();
            _userForm.MdiParent = this;
            _userForm.Dock = DockStyle.Fill;
            _userForm.Show();

            // debugForm.Show();

            Formstr = "用户窗口";
            startTime = DateTime.Now;
          //  toolStripStatusLabeSystme.Text = string.Format("状态：{0}", Formstr);

            timespan = DateTime.Now - startTime;
            toolStripStatusLabelusertime.Text = String.Format("运行时间：{0}", timespan.Days.ToString() + "天" + timespan.Hours.ToString() + "时" + timespan.Minutes.ToString() + "分" + timespan.Seconds.ToString() + "秒");

            //显示方法名称
            if (String.IsNullOrEmpty(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName))
            {
                SetMainFormMethodName("未加载");
            }
            else
            {
                SetMainFormMethodName(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName.Substring(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName.LastIndexOf("\\") + 1));
            }

            SetMenu(LandIn.Island);
            autopensys();

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

        }


        /// <summary>
        /// 判断是否要开启系统
        /// </summary>
        private void autopensys()
        {
            try
            {
                int opensys = 0;
                String tmpfile = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.StartUpFolder + "\\startup.ini";
                globaldata.starttimer = 0x7FFFFFFF;
                IniFile IniParser = new IniFile(tmpfile);

                if(IniParser.KeyExists("StartUp", "打开系统"))
                    opensys = IniParser.ReadInteger("StartUp", "打开系统");

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

                //if (globaldata.m_hmibuffer.gcinfo.methodstatus != 0)
                //{
                //  //  hmistatus_opensys();
                //}
            }
            catch(Exception ex)
            {
                Log.Error(ex.Message);
            }
        }
       
        private void SetMenu(bool isbool)
        {
            try
            {
                if (isbool)
                {
                    NetWorkMenu.Visible = true;
                    MethodBrowseMenuItem.Visible = true;
                    NewMethodMenu.Visible = true;
                    OpenMethodMenu.Visible = true;
                    MethodBrowseMenuItem.Visible = true;
                    CalibrationMenu.Visible = true;
                    GCConfigMenuItem.Visible = true;
                    AuxToolMenu.Visible = true;
                    ParameterSettingMenu.Visible = true;
                    DebugMainMenu.Visible = true;
                   // HmiStatus.Visible = true;
                    SettingSeparator.Visible = true;

                }else
                {
                    NetWorkMenu.Visible = false;
                    MethodBrowseMenuItem.Visible = false;
                    NewMethodMenu.Visible = false;
                    OpenMethodMenu.Visible = false;
                    MethodBrowseMenuItem.Visible = false;
                    CalibrationMenu.Visible = false;
                    GCConfigMenuItem.Visible = false;
                    AuxToolMenu.Visible = false;
                    ParameterSettingMenu.Visible = false;
                    DebugMainMenu.Visible = false;
                   // HmiStatus.Visible = false;
                    SettingSeparator.Visible = false;
                }

            }
            catch(Exception ex)
            {
                Log.Error(ex.Message);
            }
        }
   
        /// <summary>
        /// 更新显示栏信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 1.0.2.3  添加了周期完成后，重新绘图功能
         float fDetvalueold = 0.0f;
        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Text = String.Format("VOCs在线监测-1.1.3.05 {0}",Formstr);
            if (LandIn.Island)
            {
            HmiStatus.Text = String.Format("状态：{0}", statestr);
            }else
            {
                float fDetvalue = 0.0f;
            
                        if (globaldata.m_signalbuffer.Draw_Port.Count > 1)
                        {                           
                           fDetvalue = globaldata.m_dpbuffer.ShowList.showDet.fDetValue;
                           if (fDetvalue != 0.0f)
                               fDetvalueold = fDetvalue;
                           
                        }

                        HmiStatus.Text = String.Format("FID:{0:N3} mV", fDetvalueold);
            }

            //  toolStripStatusLabeSystme.Text = String.Format("状态：{0}", statestr);
            timespan = System.DateTime.Now - startTime;
            toolStripStatusLabelusertime.Text = String.Format("运行时间：{0}", 
                timespan.Days.ToString() + "天" + timespan.Hours.ToString() + "时" + timespan.Minutes.ToString() + "分" + timespan.Seconds.ToString() + "秒");
           // Trace.WriteLine(string.Format("时间{0}，状态{1}", getIdleTick(),LandIn.Island),"sys");

            //监视界面活动
            if (getIdleTick()>60*30 && LandIn.Island)
            {
                
                if (_userForm != null)
                {
                    Formstr = "用户窗口";
                    _userForm.Activate();
                    //userForm.Show();
                }
                LandIn.Island = false;
                SetMenu(LandIn.Island);
                Trace.WriteLine("进入自动销户","sys");
            }
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct LASTINPUTINFO
        {
            [MarshalAs(UnmanagedType.U4)]
            public int cbSize;
            [MarshalAs(UnmanagedType.U4)]
            public uint dwTime;
        }
        [DllImport("user32.dll")]
        public static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

        /// <summary>
        /// 返回持续时间  s
        /// </summary>
        /// <returns></returns>
        public long getIdleTick()
        {
            LASTINPUTINFO vLastInputInfo = new LASTINPUTINFO();
            vLastInputInfo.cbSize = Marshal.SizeOf(vLastInputInfo);
            if (!GetLastInputInfo(ref vLastInputInfo)) return 0;
            return (Environment.TickCount - (long)vLastInputInfo.dwTime)/1000;
        }

        public void SendPCCMD(bool flag)
        {
            if (flag)  //打开运行
            {
                hmiopt.WriteStopVal();
                WaitHMIFree();

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

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

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

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

                }
            }
        }

        public void SendSTDCMD()
        {
            int ret = -1;
            int count = 3;
            hmiopt.WriteStopVal();
            WaitHMIFree();
            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue)
            {
                ret = hmiopt.WriteSTDBatVal();
                while (ret != 0)
                {
                    ret = hmiopt.WriteSTDBatVal();
                    if (count < 0)
                    {
                        break;
                    }
                    count--;
                }
                hmiopt.WriteStartVal();
            }
        }

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

        private void SetMainFormMethodNameTH(string text)
        {
            this.Invoke(new Action(() =>
            {
                this.toolStripStatusLabelText.Text = "当前运行方法：" + text;
            }));
        }

        #region 后台工作
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int ret = -1;
            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 % 10 == 0 && i != 0)
                    {
                        if (globaldata.OS_STOP)
                        {
                           ret = hmiopt.WriteEndVal();
                        }
                        else
                        {
                            ret = hmiopt.WriteStopVal();
                        }
                    }

                    if (i != 99)
                    {
                        worker.ReportProgress(i);
                    }

                    //if (ret == 0)
                    //{
                    //    if (globaldata.OS_STOP)
                    //    {
                    //        globaldata.OS_STOP = false;
                    //    }
                    //    worker.ReportProgress(100);
                        
                    //}     
                }

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

                Thread.Sleep(100);

                
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.workProgress.Visible = false;
            autoResetEvent.Set();
        }

        private void WaitHMIFree()
        {
            if (!backgroundWorker1.IsBusy)
            {
                this.workProgress.Visible = true;
                this.workProgress.Value = 0;
                this.backgroundWorker1.RunWorkerAsync();
            }
           
        }

        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            int ret = -1;

            while (!autoResetEvent.WaitOne())
            {
                TimeSpan.FromSeconds(1);
            }

            if (!workProgress.Visible)
            {
                workProgress.Visible = true;
            }
           
            this.workProgress.Value = 0;

            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)
                            ret = hmiopt.WriteOpenVal();

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

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

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

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

               
            }
        }

        private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.workProgress.Visible = false;
            autoResetEvent.Reset();
        }

        private void WaitHMIWork()
        {
            if (!backgroundWorker2.IsBusy)
            {
                this.workProgress.Visible = true;
                this.workProgress.Value = 0;
                this.backgroundWorker2.RunWorkerAsync();
            }
        }
        
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.workProgress.Value = e.ProgressPercentage;
        }
    
        private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.workProgress.Value = e.ProgressPercentage;
        }
        #endregion

        private void SendStopCMD()
        {
            try
            {
                hmiopt.WriteStopVal();
                WaitHMIFree();
            }
            catch
            {
            }

        }

        private void InitConfig()
        {
            string tmpname = "";
            try
            {
                if (!String.IsNullOrEmpty(globaldata.connection_ip))
                {
                    Start_ConnectStatusThread();
                    try
                    {
                        globaldata.m_profileMethod.SetStatusFullName(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName);
                        globaldata.m_profileMethod.GetDevState();
                       
                        tmpname = globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2? 
                            globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName: 
                            globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;

                        if (!String.IsNullOrEmpty(tmpname))
                        {
                            globaldata.show_MethodName = tmpname;
                            SetMainFormMethodName(tmpname);
                            globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName = Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, tmpname.ToString());

                            if(globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName = 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();  
                        }
                        else
                        {
                            Log.Error("Method is Null...");
                        }
                    }
                    catch
                    {

                        Log.Error("System Init Failed");                 
                    }

                    statestr = "设备联机";
                    IsStateColor=true;

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

                        if (globaldata.m_pcbuffer.gcpcinfo.outputinfo.port != 0)
                        {
                            Slave485test = new GCModbusSlave485(globaldata.m_pcbuffer.gcpcinfo.outputinfo.port, 9600);
                            Slave485test.CModbusSlave485Init(1, 2, 3, 5);
                        }
                        

                    }
                    catch (Exception e)
                    {
                        Log.Error(e.Message);
                    }

                }
                else
                {
                    statestr = "未联机";
                    IsStateColor = false;
                }
            }
            catch(Exception ex)
            {
                Log.Error(ex.Message);
            }
        }


        private void Start_Thread()
        {
            // mydatasave.ChannelDataStart();
            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {
                mymodbus.HmiStatueStart();
                mymodbus.ChannelDataStart();
            }
           
            dataVOC.CKvocUpdataStart();
            mytcptest.DataRcvStart();

            if (!String.IsNullOrEmpty(globaldata.m_pcbuffer.gcpcinfo.moduleinfo.ip))
                wtd624xOutput.DataOutStart();
        }

        private void Stop_Thread()
        {
            // mydatasave.ChannelDataStop();
        
            dataVOC.CKvocUpdataStop();
            mytcptest.DataRcvStop();

            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {
                mymodbus.HmiStatueStop();
                mymodbus.ChannelDataStop();
            }

            if (!String.IsNullOrEmpty(globaldata.m_pcbuffer.gcpcinfo.moduleinfo.ip))
                wtd624xOutput.DataOutStop();
        }

       /// <summary>
       /// 状态改变信号量
       /// </summary>
        ManualResetEvent datamre = new ManualResetEvent(false);
        ManualResetEvent conmre = new ManualResetEvent(false);
        ushort GCstatus = 9;
        Thread Connect_Status;


        /// <summary>
        /// HMI状态监控线程
        /// </summary>
        private void Start_ConnectStatusThread()
        {
            if (conmre != null)
            {
                conmre.Reset();
            }
            Connect_Status = new Thread(Monitor_Connect);
            Connect_Status.IsBackground = true;
            Connect_Status.Start();
        }

        /// <summary>
        /// HMI状态监控线程实现
        /// </summary>
        private void Monitor_Connect()
        {
            UInt16[] dest = new UInt16[9];
        
            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;
                }

                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;

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

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


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

                switch (runtype)
                {
                    case 0:
                        Common_HeadInfo();
                        DataControl_Status(dest[5], 0);
                        break;
                    case 2:
                        BAT_HeadInfo(dest[0], dest[1]); 
                        DataControl_Status(dest[5], 2);
                        break;
                    case 3:
                        QuickRun_HeadInfo();
                        DataControl_Status(dest[5], 1);
                        break;
                    case 4:
                        SingleRun_HeadInfo();
                        DataControl_Status(dest[5], 1);
                        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 (!File.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName))
                            {
                                getFileName = tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1);
                                ret = mainclient.WtClientCopyfromServer(getFileName, globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName, globaldata.remoteFolder + "仪器方法\\");
                                Thread.Sleep(400);
                            }

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

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

                }

            }
        }


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

        /// <summary>
        /// 控制调试按钮权限
        /// </summary>
        /// <param name="flag"></param>
        void ButtonControl_Status(ushort flag)
        {
            this.Invoke(new Action(() =>
            {
                switch (flag)
                {
                    case 0:
                    case 1:
                    case 2:
                    {
                        SingleCancel.Enabled = false;
                        SingleStop.Enabled = false;
                        SingleStart.Enabled = false;
                    }
                        break;
                    case 3: //已就绪
                    {
                        SingleCancel.Enabled = false;
                        SingleStop.Enabled = false;
                        SingleStart.Enabled = true;
                    }
                        break;
                    case 4:
                    case 5:
                    {
                        SingleCancel.Enabled = true;
                        SingleStop.Enabled = true;
                        SingleStart.Enabled = false;
                    }
                        break;
                    case 6:
                    case 7:
                    {
                        SingleCancel.Enabled = false;
                        SingleStop.Enabled = false;
                        SingleStart.Enabled = false;
                    }
                        break;
                    default:
                    {
                        SingleCancel.Enabled = false;
                        SingleStop.Enabled = false;
                        SingleStart.Enabled = false;
                    }
                        break;
                }
            }));
        }

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

                    break;
            }
            statestr = status_text;
            IsStateColor = color_flag;

            if (oldflag != flag)
            {
                oldflag = flag;
            }
        }

        void Common_HeadInfo()
        {
            string tmpFileName;
            tmpFileName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;
            SetMainFormMethodNameTH(tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1));

        }

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

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

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


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

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

       

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

            uint ret = 0;
            uint count = 0;

            CKVocAnalyzer.GlobalCKV.tcpservice.stop();
            _debugForm.CloseThread();

            if (dr == DialogResult.OK)  //停止系统并退出
            {
                Stop_Thread();
                if (!String.IsNullOrEmpty(globaldata.connection_ip))
                {
                    globaldata.OS_STOP = true;
                    hmiopt.WriteEndVal();

                    WaitHMIFree();

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


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

                    if (globaldata.m_pcbuffer.gcpcinfo.outputinfo.port != 0)
                    {
                        count = 0;
                        ret = Slave485test.CModbusSlave485Close();
                        while (ret != 0)
                        {
                            count++;
                            ret = Slave485test.CModbusSlave485Close();
                            Thread.Sleep(100);
                            if (count > 3)
                            {
                                break;
                            }
                        }
                    }
                        
                }

                try
                {
                    this.Dispose();
                    System.Diagnostics.Process.GetCurrentProcess().Kill();
                }
                catch
                {

                }
            }

            if (dr == DialogResult.Yes)  //仅退出
            {
                if (!String.IsNullOrEmpty(globaldata.connection_ip))
                {
                    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;
                        }
                    }

                    if (globaldata.m_pcbuffer.gcpcinfo.outputinfo.port != 0)
                    {
                        count = 0;
                        ret = Slave485test.CModbusSlave485Close();
                        while (ret != 0)
                        {
                            count++;
                            ret = Slave485test.CModbusSlave485Close();
                            Thread.Sleep(100);
                            if (count > 3)
                            {
                                break;
                            }
                        }
                    }
                }


                try
                {
                    this.Dispose();
                    System.Diagnostics.Process.GetCurrentProcess().Kill();
                }
                catch
                {

                }
            }

            if (dr == DialogResult.Cancel)  //取消
            {
                e.Cancel = true;
            }
        }

        AutoResetEvent autoResetEvent = new AutoResetEvent(false);
        // private bool isopen = false;
        private void open()
        {
            bool ret = false;
            try
            {
                if(globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue)
                {
                    MessageBox.Show("系统开启中......");
                    return ;
                }

                if (!String.IsNullOrEmpty(globaldata.connection_ip))
                {
                    hmiopt.WriteStopVal();
                    statestr = "系统准备中...";

                    WaitHMIFree();

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

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

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 1)
                    {
                        hmiopt.WriteSingleVal();
                    }
                    Console.WriteLine("WaitHMIWork ");
                    WaitHMIWork();
                    Console.WriteLine("WaitHMIWork End");

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


                }
                else
                {

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

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

        private void fireupopt(int flag, ushort time1, ushort time2)
        {
            hmiopt.FireUPWork(flag, time1, time2);
        }

     
        /// <summary>
        /// 调试运行表接口
        /// </summary>
        /// <param name="folder">批处理目录</param>
        /// <param name="runtablename">批处理文件名(带.ini)</param>
        /// <returns>0-失败 1-成功</returns>
        private int RunTableOpt(String folder, String runtablename)
        {
            int initret = 0;
            int ret = 0;

            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {
                FileServerClient rtclient = new FileServerClient();
                initret =  rtclient.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);

                if (initret == 1)
                {
                    if (File.Exists(Path.Combine(folder, runtablename)))
                    {
                        ret = rtclient.WtClientCopytoServer("RunMethod.ini", Path.Combine(folder, runtablename), globaldata.remoteFolder + "运行表\\");
                        SendPCCMD(false);
                    }

                    rtclient.WtClientClose();
                    globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab = Path.Combine(folder, runtablename);
                }
            }

            return ret;
        }

        /// <summary>
        /// 调试运行表接口
        /// </summary>
        /// <param name="folder">批处理目录</param>
        /// <param name="runtablename">批处理文件名(带.ini)</param>
        /// <param name="count">批处理运行次数</param>
        /// <returns>0-失败 1-成功</returns>
        private int RunTableOptWithCount(String folder, String runtablename, ushort count)
        {
            int initret = 0;
            int ret = 0;

            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {
                FileServerClient rtclient = new FileServerClient();
                initret = rtclient.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);

                if (initret == 1)
                {
                    if (File.Exists(Path.Combine(folder, runtablename)))
                    {
                        ret = rtclient.WtClientCopytoServer("RunMethodStd.ini", Path.Combine(folder, runtablename), globaldata.remoteFolder + "运行表\\");
                        hmiopt.SetBatCount(count);
                        SendSTDCMD();
                    }

                    rtclient.WtClientClose();
                    globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab = Path.Combine(folder, runtablename);
                }
                
            }
            return ret;
        }

        /// <summary>
        /// 直接执行STD批处理
        /// </summary>
        /// <param name="count">次数</param>
        private void RunTableOptWithCount(ushort count)
        {
            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {
                hmiopt.SetBatCount(count);
                SendSTDCMD(); 
            }
        }

        /// <summary>
        /// 更新所需，关闭HMI
        /// </summary>
        public void stopforupdatefirm()
        {
            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {

                statestr = "系统停止中...";
                globaldata.OS_STOP = true;
                hmiopt.WriteEndVal();
                WaitHMIFree();
                statestr = "系统停止中...";

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

        /// <summary>
        /// 开始更新指令
        /// </summary>
        public void startupdatefirm()
        {
            hmiopt.WriteUpdateVal();
        }
        public void hair_sw(int val)
        {
            hmiopt.HAirSwitch(val);
        }
        

        private void UserLoginMenu_Click(object sender, EventArgs e)
        {
            DialogResult dr = new LandIn("admin").ShowDialog();

            if (dr == DialogResult.OK)
            {
                if (LandIn.Island)
                {
                    if (_debugForm != null)
                    {
                        Formstr = "调试窗口";
                        _debugForm.Activate();
                    }
                    SetMenu(LandIn.Island);
                    Trace.WriteLine(string.Format("用户{0}，进入调试模式","admin"),"sys");
                }
            }

            if (dr == DialogResult.No)
            {

            }

        }

        private void UserLogoutMenu_Click(object sender, EventArgs e)
        {
            if (_debugForm != null)
            {
                // debugForm.Hide();
            }
            if (_userForm != null)
            {
                Formstr = "用户窗口";
                _userForm.Activate();
                //userForm.Show();
                Trace.WriteLine("注销登录，进入用户模式", "sys");
            }
            LandIn.Island = false;
            SetMenu(LandIn.Island);

        }

        private void SystemStartMenu_Click(object sender, EventArgs e)
        {
            open();
        }

        private void SystemStopMenu_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {

                statestr = "系统停止中...";

                globaldata.OS_STOP = true;
                hmiopt.WriteEndVal();

                WaitHMIFree();

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

            }
            else
            {

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

        private void AuxToolMenu_Click(object sender, EventArgs e)
        {
            auxtool f_auxtool = new auxtool();
            int ret = 0;
            ushort[] firetime = new ushort[2];

            if(!String.IsNullOrEmpty(globaldata.connection_ip))
                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 NetWorkMenu_Click(object sender, EventArgs e)
        {
            UserConfig confu = new UserConfig();
            confu.Show();
        }

        private void MethodBatMenu_Click(object sender, EventArgs e)
        {
            try
            {
                RunTables f_runtable = new RunTables();
                f_runtable.sendupdatecmd -= new SendUpdateCMD(SendPCCMD);
                f_runtable.sendupdatecmd += new SendUpdateCMD(SendPCCMD);
                f_runtable.sendstopcmd -= new SendStopCMD(SendStopCMD);
                f_runtable.sendstopcmd += new SendStopCMD(SendStopCMD);
                f_runtable.Show();

            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);

            }
        }

        private void NewMethodMenu_Click(object sender, EventArgs e)
        {
            SaveDialog saveDialog = new SaveDialog(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, 0);
            DialogResult dr = saveDialog.ShowDialog();
            if (dr == DialogResult.OK)
            {
                String mfilename = Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, saveDialog.filename);
                GCMethodConfig methodconfig = new GCMethodConfig();

                if (File.Exists(mfilename) == false)
                {
                    StreamWriter sw = new StreamWriter(mfilename, false, System.Text.Encoding.Unicode);
                    sw.WriteLine("[方法名称]");
                    sw.WriteLine("名称=" + saveDialog.filename);
                    sw.Close();
                    // globaldata.createfile = true;
                }

                methodconfig.SetMethodConfigName(mfilename);
                methodconfig.SetMethodSaveName(mfilename);

                MethodMain myform = new MethodMain();
                myform.SetGCConfig(globaldata.m_hwconfig, methodconfig);
                myform.Show();
            }
        }

        private void OpenMethodMenu_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDlg = new OpenFileDialog();
            fileDlg.Multiselect = false;
            fileDlg.InitialDirectory = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder;
            fileDlg.RestoreDirectory = true;
            fileDlg.Title = "请选择方法文件";
            fileDlg.Filter = "配置文件(*.ini)|*.ini";
            if (fileDlg.ShowDialog() == DialogResult.OK)
            {
                string file = fileDlg.FileName;

                String mfilename = Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, file);

                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_OpenMethodName = mfilename;
                GCMethodConfig methodconfig = new GCMethodConfig();

                methodconfig.SetMethodConfigName(mfilename);
                methodconfig.SetMethodSaveName(mfilename);

                MethodMain myform = new MethodMain(true);

                myform.sendupdatecmd += new MethodMain.SendUpdateCMD(SendPCCMD);
                myform.SetGCConfig(globaldata.m_hwconfig, methodconfig);
                myform.Show();

                string tmpFileName;
                tmpFileName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;
                SetMainFormMethodNameTH(tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1));

                this.inifilec = true;

                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType = 0;
            }

        }

        private void MethodBrowseMenuItem_Click(object sender, EventArgs e)
        {
            if (globaldata.m_configDlg.Visible == true)
                return;

            if (inifilec)
            {
                String mfilename = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_OpenMethodName;
                GCMethodConfig methodconfig = new GCMethodConfig();
                methodconfig.SetMethodConfigName(mfilename);
                methodconfig.SetMethodSaveName(mfilename);
                MethodMain myform = new MethodMain(true, false);
                myform.SetGCConfig(globaldata.m_hwconfig, methodconfig);
                myform.Show();
            }
            else
            {
                OpenFileDialog fileDlg = new OpenFileDialog();
                fileDlg.Multiselect = false;
                fileDlg.InitialDirectory = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder;
                fileDlg.RestoreDirectory = true;
                fileDlg.Title = "请选择方法文件";
                fileDlg.Filter = "配置文件(*.ini)|*.ini";
                if (fileDlg.ShowDialog() == DialogResult.OK)
                {
                    string file = fileDlg.FileName;
                    String mfilename = Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, file);
                    GCMethodConfig methodconfig = new GCMethodConfig();
                    methodconfig.SetMethodConfigName(mfilename);
                    methodconfig.SetMethodSaveName(mfilename);
                    MethodMain myform = new MethodMain(true, false);
                    myform.SetGCConfig(globaldata.m_hwconfig, methodconfig);
                    myform.Show();
                }
            }
        }

        private void HistoryDataMenu_Click(object sender, EventArgs e)
        {
            try
            {
                WaveTotalForm total = new WaveTotalForm();
                total.Show();

            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        private void CalibrationMenu_Click(object sender, EventArgs e)
        {

            try
            {
                AdjustFrom just = new AdjustFrom();
                just.Show();
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        private void HistoryPicMenu_Click(object sender, EventArgs e)
        {
            try
            {
                HistChartForm hist = new HistChartForm();
                hist.Show();
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }

        }

        private void ConfigCreateSubMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                CreateConfig f = new CreateConfig();
                f.Show();
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }

          
        }

        private void ConfigShowSubMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                ShowConfig f = new ShowConfig();
                f.Show();
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }

        }

        private void ConfigSendSubMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                SendConfig f = new SendConfig();
                f.Show();
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        private void ParameterSettingMenu_Click(object sender, EventArgs e)
        {
            try
            {
                CKVocAnalyzer.SetInfoForm sf = new CKVocAnalyzer.SetInfoForm();
                sf.Show();

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

        #region 单次处理控制
        private void startbtn()
        {
            globaldata.startflag = true;
            globaldata.stopflag = false;
            globaldata.cancelflag = false;
            globaldata.startclear = true;
            globaldata.starttimer = 0;
            globaldata.startimerIsSet = true;
            globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 1;
        }

        private void SingleStart_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {

                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true && globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                {

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

                    }
                    hmiopt.WriteStartVal();

                    startbtn();
                }
            }
        }

        Thread t_checkcmd;
        public void stopbtn()
        {
            globaldata.startflag = false;
            globaldata.stopflag = true;
            globaldata.cancelflag = false;

            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {
                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();
                    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 SingleStop_Click(object sender, EventArgs e)
        {
            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true)
            {
             
                hmiopt.WriteStopVal();
                
                WaitHMIFree();

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

        private void cancelbtn()
        {
            globaldata.startflag = false;
            globaldata.stopflag = false;
            globaldata.cancelflag = true;
            globaldata.starttimer = 0x7FFFFFFF;
            if (!String.IsNullOrEmpty(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();
                    t_checkcmd = new Thread(checkcmd);
                    t_checkcmd.IsBackground = true;
                    t_checkcmd.Start();
                }

            }
        }

        private void SingleCancel_Click(object sender, EventArgs e)
        {
            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true)
            {
                hmiopt.WriteCancalVal();
                WaitHMIFree();
                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                {
                    hmiopt.WriteOpenVal();
                                 
                }
                cancelbtn();
            }
        }

        #endregion

        AboutForm f_showcfg;
        private void AboutMenu_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 AboutForm(version);
                f_showcfg.Show();
            }
            else
            {
                if (f_showcfg.IsDisposed)
                {
                    f_showcfg = new AboutForm(version);
                    f_showcfg.Show();
                }
                else
                {
                    f_showcfg.Show();
                }

            }
        }
        /// <summary>
        /// true 开始校准   false  强制结束
        /// </summary>
        /// <param name="boolrun"></param>
        private void AutoAdjustRun(bool boolrun)
        {
            if(boolrun)
            {
                CurveDisPlay.curdisp.SetAutoAdjust();

            }else
            {
                CurveDisPlay.curdisp.StopAutoAdjust();
            }

        }
        /// <summary>
        /// 校准完成时间
        /// </summary>

        DateTime AutoAdjust;
        private void timerWorker_Tick(object sender, EventArgs e)
        {
            try
            {
                //Trace.WriteLine(string.Format("{0},{1}", SharedSpace.MControl.SetOut, SharedSpace.MControl.SetRun), "debug");

                if (SharedSpace.MControl.SetOut && SharedSpace.MControl.SetRun == false)  //准备开始校准
                {
                    SharedSpace.MControl.errstr = null;
                    SharedSpace.MControl.zhouqi = globaldata.m_dpbuffer.ShowList.showtime.alltime;
                  
                    if(SharedSpace.MControl.zhouqi*SharedSpace.MControl.runcount<=SharedSpace.MControl.dateend)
                    {
                        
                    
                        if (RunTableOpt(SharedSpace.MControl.path, SharedSpace.MControl.Name)==1&& SharedSpace.MControl.MethodType==1)
                        {
                            Trace.WriteLine(string.Format("开始校准{0},{1}", SharedSpace.MControl.zhouqi, SharedSpace.MControl.runcount), "sys");
                            SharedSpace.MControl.SetRun = true;//仪器进入校准环境
                            CurveDisPlay.forcePurge = true;//强制清除数据
                            AutoAdjust = DateTime.Now.AddSeconds(SharedSpace.MControl.dateend);
                        }
                        if (SharedSpace.MControl.MethodType == 2)
                        {
                            Trace.WriteLine(string.Format("开始校准{0},{1}", SharedSpace.MControl.zhouqi, SharedSpace.MControl.runcount), "sys");
                            SharedSpace.MControl.SetRun = true;//仪器进入校准环境
                            CurveDisPlay.forcePurge = true;
                            AutoAdjust = DateTime.Now.AddSeconds(SharedSpace.MControl.dateend);
                        }
                
                  
                    }else
                    {
                        SharedSpace.MControl.errstr = "校准时间不够";
                        SharedSpace.MControl.SetOut = false;
                    }
                }
                //else if (SharedSpace.MControl.SetRun == false)
                //{
                //    SharedSpace.MControl.errstr = "系统准备失败";
                //    SharedSpace.MControl.SetOut = false;
                //}
                //等待校准结束
                if (DateTime.Now >= AutoAdjust && SharedSpace.MControl.SetOut && SharedSpace.MControl.SetRun)
                {
                    SharedSpace.MControl.IsEnd = true;


                    if (RunTableOpt(SharedSpace.MControl.defaultPath, SharedSpace.MControl.defaultName) == 1 && SharedSpace.MControl.MethodType == 1)
                    {
                        SharedSpace.MControl.SetOut = false;
                        SharedSpace.MControl.SetRun = false;
                        if (SharedSpace.Data.typesint == 2)
                        {
                        CurveDisPlay.curdisp.ConfingAdjust();
                        }
                        Trace.WriteLine("校准结束", "sys");
                    }
                    if(SharedSpace.MControl.MethodType==2)
                    {
                        SharedSpace.MControl.SetOut = false;
                        SharedSpace.MControl.SetRun = false;
                        if (SharedSpace.Data.typesint == 2)
                        {
                            CurveDisPlay.curdisp.ConfingAdjust();
                        }
                        Trace.WriteLine("校准结束", "sys");
                    }

                }

                if (SharedSpace.MControl.forceEnd && SharedSpace.MControl.SetOut && SharedSpace.MControl.SetRun)
                {
                    SharedSpace.MControl.IsEnd = false;
                   
                  

                    if (RunTableOpt(SharedSpace.MControl.defaultPath, SharedSpace.MControl.defaultName) == 1&&SharedSpace.MControl.MethodType == 1)
                    {
                        SharedSpace.MControl.SetOut = false;
                        SharedSpace.MControl.SetRun = false;
                        Trace.WriteLine("强制校准结束", "sys");
                    }
                    if (SharedSpace.MControl.MethodType == 2)
                    {
                        SharedSpace.MControl.SetOut = false;
                        SharedSpace.MControl.SetRun = false;
                        Trace.WriteLine("强制校准结束", "sys");
                    }

                }

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

        //private void debugSubMenu_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        _424XTest test = new _424XTest();
        //        test.Show();
        //    }
        //    catch (Exception ex)
        //    {
        //        Log.Error(ex.Message);
        //    }
        //}
    }
}
