using FileManager;
using MeasureData;
using MeasureThread;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static MeasureThread.ThreadStatusEventArgs;

namespace HOZProject
{
    public partial class FormHOZMain : Form
    {
        #region 控制窗体可以调整大小用
        const int HTLEFT = 10;
        const int HTRIGHT = 11;
        const int HTTOP = 12;
        const int HTTOPLEFT = 13;
        const int HTTOPRIGHT = 14;
        const int HTBOTTOM = 15;
        const int HTBOTTOMLEFT = 0x10;
        const int HTBOTTOMRIGHT = 17;
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case 0x0084:
                    base.WndProc(ref m);
                    Point vPoint = new Point((int)m.LParam & 0xFFFF,
                        (int)m.LParam >> 16 & 0xFFFF);
                    vPoint = PointToClient(vPoint);
                    if (vPoint.X <= 5)
                        if (vPoint.Y <= 5)
                            m.Result = (IntPtr)HTTOPLEFT;
                        else if (vPoint.Y >= ClientSize.Height - 5)
                            m.Result = (IntPtr)HTBOTTOMLEFT;
                        else m.Result = (IntPtr)HTLEFT;
                    else if (vPoint.X >= ClientSize.Width - 5)
                        if (vPoint.Y <= 5)
                            m.Result = (IntPtr)HTTOPRIGHT;
                        else if (vPoint.Y >= ClientSize.Height - 5)
                            m.Result = (IntPtr)HTBOTTOMRIGHT;
                        else m.Result = (IntPtr)HTRIGHT;
                    else if (vPoint.Y <= 5)
                        m.Result = (IntPtr)HTTOP;
                    else if (vPoint.Y >= ClientSize.Height - 5)
                        m.Result = (IntPtr)HTBOTTOM;
                    break;
                case 0x0201://鼠标左键按下的消息 
                    m.Msg = 0x00A1;//更改消息为非客户区按下鼠标 
                    m.LParam = IntPtr.Zero;//默认值 
                    m.WParam = new IntPtr(2);//鼠标放在标题栏内 
                    base.WndProc(ref m);
                    break;
                default:
                    base.WndProc(ref m);
                    break;
            }
        }
        #endregion

        #region 成员变量
        public BackgroundWorker m_BackgroundWorker;// 申明后台对象
        /// <summary>
        /// 测量文件
        /// </summary>
        public MeasureFile m_MeasureFile;

        /// 测量线程  
        public Measure m_Ms;

        /// <summary>
        /// 显示日志窗体
        /// </summary>
        Form m_FormLog = null;
        /// <summary>
        /// 显示实例化窗体
        /// </summary>
        FormMove m_FormInit = null;

        /// <summary>
        /// 是否已保存
        /// </summary>
        public bool IsSave = false;

        /// <summary>
        /// 初始化用户控件
        /// </summary>
        UControl_Init uControl_Init = null;
        /// <summary>
        /// 日志用户控件
        /// </summary>
        UControl_Log ucLog = null;
        //流程控制
        public int m_MeasureType = (int)MeasureMsgManage.measureType.FIB;

        //是否关闭窗体标识
        public bool IsClose = false;

        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        #endregion

        #region 构造函数
        public FormHOZMain()
        {
            InitializeComponent();
            //在线程操作过程中，可以设置控件属性
            Control.CheckForIllegalCrossThreadCalls = false;
            m_BackgroundWorker = new BackgroundWorker(); // 实例化后台对象 
            m_BackgroundWorker.WorkerReportsProgress = true; // 设置可以通告进度 
            m_BackgroundWorker.WorkerSupportsCancellation = true; // 设置可以取消 
            m_BackgroundWorker.DoWork += new DoWorkEventHandler(DoWork);
            m_BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(UpdateProgress);
            m_BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork);

            LogManager.InitManulLog();
        }
        #endregion

        #region 测量线程
        void DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                m_Ms = new Measure(ConfigurationManager.AppSettings["WebServerIP"].ToString(),
                       ConfigurationManager.AppSettings["WebServerPort"].ToString(),
                       ConfigurationManager.AppSettings["WebServerUrl"].ToString());

                m_MeasureFile.MParam.AutoFocus.UP = Convert.ToSingle(ConfigurationManager.AppSettings["Focus_UP"].ToString());
                m_MeasureFile.MParam.AutoFocus.Down = Convert.ToSingle(ConfigurationManager.AppSettings["Focus_Down"].ToString());
                m_MeasureFile.MParam.AutoFocus.Step = Convert.ToSingle(ConfigurationManager.AppSettings["Focus_Step"].ToString());
                m_MeasureFile.MParam.AutoFocus.Range = Convert.ToSingle(ConfigurationManager.AppSettings["Focus_Range"].ToString());
                m_MeasureFile.MParam.AutoFocus.fStep = Convert.ToSingle(ConfigurationManager.AppSettings["Focus_FStep"].ToString());

                m_MeasureFile.MParam.FIBFocus.UP = Convert.ToSingle(ConfigurationManager.AppSettings["FIB_UP"].ToString());
                m_MeasureFile.MParam.FIBFocus.Down = Convert.ToSingle(ConfigurationManager.AppSettings["FIB_Down"].ToString());
                m_MeasureFile.MParam.FIBFocus.Step = Convert.ToSingle(ConfigurationManager.AppSettings["FIB_Step"].ToString());
                m_MeasureFile.MParam.FIBFocus.Range = Convert.ToSingle(ConfigurationManager.AppSettings["FIB_Range"].ToString());
                m_MeasureFile.MParam.FIBFocus.fStep = Convert.ToSingle(ConfigurationManager.AppSettings["FIB_FStep"].ToString());

                m_MeasureFile.MParam.AutoStigX.UP = Convert.ToSingle(ConfigurationManager.AppSettings["StigX_UP"].ToString());
                m_MeasureFile.MParam.AutoStigX.Down = Convert.ToSingle(ConfigurationManager.AppSettings["StigX_Down"].ToString());
                m_MeasureFile.MParam.AutoStigX.Step = Convert.ToSingle(ConfigurationManager.AppSettings["StigX_Step"].ToString());
                m_MeasureFile.MParam.AutoStigX.Range = Convert.ToSingle(ConfigurationManager.AppSettings["StigX_Range"].ToString());
                m_MeasureFile.MParam.AutoStigX.fStep = Convert.ToSingle(ConfigurationManager.AppSettings["StigX_FStep"].ToString());

                m_MeasureFile.MParam.AutoStigY.UP = Convert.ToSingle(ConfigurationManager.AppSettings["StigY_UP"].ToString());
                m_MeasureFile.MParam.AutoStigY.Down = Convert.ToSingle(ConfigurationManager.AppSettings["StigY_Down"].ToString());
                m_MeasureFile.MParam.AutoStigY.Step = Convert.ToSingle(ConfigurationManager.AppSettings["StigY_Step"].ToString());
                m_MeasureFile.MParam.AutoStigY.Range = Convert.ToSingle(ConfigurationManager.AppSettings["StigY_Range"].ToString());
                m_MeasureFile.MParam.AutoStigY.fStep = Convert.ToSingle(ConfigurationManager.AppSettings["StigY_FStep"].ToString());


                m_Ms.X_Min = Convert.ToSingle(ConfigurationManager.AppSettings["X_Min"]);
                m_Ms.X_Max = Convert.ToSingle(ConfigurationManager.AppSettings["X_Max"]);
                m_Ms.Y_Min = Convert.ToSingle(ConfigurationManager.AppSettings["Y_Min"]);
                m_Ms.Y_Max = Convert.ToSingle(ConfigurationManager.AppSettings["Y_Max"]);
                m_Ms.Z_Min = Convert.ToSingle(ConfigurationManager.AppSettings["Z_Min"]);
                m_Ms.Z_Max = Convert.ToSingle(ConfigurationManager.AppSettings["Z_Max"]);
                m_Ms.T_Min = Convert.ToSingle(ConfigurationManager.AppSettings["T_Min"]);
                m_Ms.T_Max = Convert.ToSingle(ConfigurationManager.AppSettings["T_Max"]);
                m_Ms.R_Min = Convert.ToSingle(ConfigurationManager.AppSettings["R_Min"]);
                m_Ms.R_Max = Convert.ToSingle(ConfigurationManager.AppSettings["R_Max"]);
                m_Ms.M_Min = Convert.ToSingle(ConfigurationManager.AppSettings["M_Min"]);
                m_Ms.M_Max = Convert.ToSingle(ConfigurationManager.AppSettings["M_Max"]);

                //人工干预
                m_Ms.hand_intervene = Convert.ToInt32(ConfigurationManager.AppSettings["Hand_Intervene"]);

                //SmartSEM远程路径
                m_Ms.RemoteELYPath = ConfigurationManager.AppSettings["RemoteELYPath"];
                m_Ms.RemoteMLFPath = ConfigurationManager.AppSettings["RemoteMLFPath"];

                //Z轴移动距离
                m_MeasureFile.MParam.ZDistance= Convert.ToSingle(ConfigurationManager.AppSettings["ZDistance"]);

                m_Ms.InitMeas(m_MeasureFile);
                //注册事件
                m_Ms.SendThreadStatus += new ThreadStatusHandler(displayMessage);
                //注册事件
                m_Ms.SendCutHolesStatus += new CutHolesStatusHandler(displayCutHoleMessage); 
                //设置控件操作
                SetWinControlMeasureState(false);
                //自动测量的全过程
                m_Ms.DoMeasure();
            }
            catch (Exception ex)
            {
                LogManager.LogError(ex.ToString());
            }
        }

        public void displayMessage(object sender, ThreadStatusEventArgs e)
        {
            //主界面显示内容
            this.BeginInvoke((Action)delegate
            {
                this.listmsg.Items.Add(e.HoleName +"_" + e.Time.ToString() + "_"+ e.Message + "_" + e.State );
                //显示流程中对应编号的内容
                MeasureMsgManage.ShowMsgContent(this, e);
                AddLogListInfo(e);
            });
        }
        public void displayCutHoleMessage(object sender, CutHolesStatusEventArgs e)
        {
            //主界面显示内容
            this.BeginInvoke((Action)delegate
            {
                //修改切孔状态
                ChangeCutHoleState(e.HoleName.ToString(), Convert.ToInt32(e.State));
            });
        }

        void UpdateProgress(object sender, ProgressChangedEventArgs e)
        {
        }
        void CompletedWork(object sender, RunWorkerCompletedEventArgs e)
        {
            //设置控件操作
            MessageBox.Show("测量已完成!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            SetWinControlMeasureState(true);
        }
        #endregion

        #region 窗体加载
        private void FormHOZMain_Load(object sender, EventArgs e)
        {
            //加载控件的点击事件
            this.Click += new EventHandler(FormHOZMain_Click);
            plFill.Click += new EventHandler(FormHOZMain_Click);
            plTop.Click += new EventHandler(FormHOZMain_Click);
            plLeft.Click += new EventHandler(FormHOZMain_Click);
            plLeftContent.Click += new EventHandler(FormHOZMain_Click);
            pbImage.Click += new EventHandler(FormHOZMain_Click);

            //加载窗口移动事件
            this.MouseDown += new MouseEventHandler(FormHOZMain_MouseDown);
            //新建
            NewCreate();
            //实例初始化窗体对象
            if (uControl_Init == null)
            {
                uControl_Init = new UControl_Init(this);
                uControl_Init.ReloadConfig();
            }
        } 
        #endregion

        #region 创建切孔列表信息
        /// <summary>
        /// 创建切孔列表信息
        /// </summary>
        /// <param name="ListCutHole"></param>
        public void CreateCutHoleList(List<CutHole> ListCutHole)
        {
            //清空左侧Panel中的切孔控件
            ClearPanelControls();
            for (int i = ListCutHole.Count - 1; i >= 0; i--)
            {
                UControl_CutHole ucCutHole = new UControl_CutHole(this);
                ucCutHole.Dock = DockStyle.Top;
                ucCutHole.CutHoleName = ListCutHole[i].HoleName;

                //显示切孔参数信息
                if (ucCutHole.UControl_ParaInfo == null)
                {
                    ucCutHole.UControl_ParaInfo = new UControl_ParaInfo(this);
                }
                plPrarInfo.Width = ucCutHole.UControl_ParaInfo.Width;
                plPrarInfo.Height = ucCutHole.UControl_ParaInfo.Height;
                //设置当前样品的参数信息
                string CutHoleName = ListCutHole[i].HoleName;
                ucCutHole.UControl_ParaInfo.Name = CutHoleName;
                ucCutHole.UControl_ParaInfo.CutHoleName = CutHoleName;
                ucCutHole.UControl_ParaInfo.Position = ListCutHole[i].Position;
                ucCutHole.UControl_ParaInfo.StartTime = ListCutHole[i].START.ToString();
                ucCutHole.UControl_ParaInfo.EndTime = ListCutHole[i].END.ToString();
                int state = (int)ListCutHole[i].STATE;
                ucCutHole.UControl_ParaInfo.State = state;
                ucCutHole.UControl_ParaInfo.IsSwitch = ListCutHole[i].SWITCH;
                ucCutHole.UControl_ParaInfo.Dock = DockStyle.Fill;
                ucCutHole.UControl_ParaInfo.ShowParaInfo();
                plPrarInfo.Controls.Add(ucCutHole.UControl_ParaInfo);
                plLeftContent.Controls.Add(ucCutHole);
                ChangeCutHoleState(CutHoleName, state);
            }
            plPrarInfo.Visible = false;
        }
        #endregion

        #region 隐藏处理层
        //隐藏处理层
        private void FormHOZMain_Click(object sender, EventArgs e)
        {
            if (plPrarInfo.Visible)
            {
                plPrarInfo.Visible = false;
            }
        } 
        #endregion

        #region 设置控件在线程过程中的编辑状态
        /// <summary>
        /// 设置控件在线程过程中的编辑状态
        /// </summary>
        /// <param name="cState"></param>
        public void SetWinControlMeasureState(bool cState)
        {
            pbNew.Enabled = cState;
            pbOpen.Enabled = cState;
            pbSave.Enabled = cState;
            pbInit.Enabled = cState;
            pbImportTemplateFile.Enabled = cState;
            //pbLog.Enabled = cState;
            pbStart.Enabled = cState;
            pbStop.Enabled = !cState;
            //设置切孔是否执行
            foreach (Control item in plPrarInfo.Controls)
            {
                if (item is UserControl)
                {
                    UControl_ParaInfo ucParaInfo = (UControl_ParaInfo)item;
                    ucParaInfo.CkIsSwitch.Enabled = cState;
                }
            }
        }
        #endregion
        
        #region 窗体中 线程开始 停止 最大化 最小化 关闭 按钮事件
        private void pbMin_MouseEnter(object sender, EventArgs e)
        {
            this.pbMin.BackgroundImage = global::HOZProject.Properties.Resources.Min;
        }

        private void pbMin_MouseLeave(object sender, EventArgs e)
        {
            this.pbMin.BackgroundImage = global::HOZProject.Properties.Resources.Min;
        }

        private void pbMax_MouseEnter(object sender, EventArgs e)
        {
            this.pbMax.BackgroundImage = global::HOZProject.Properties.Resources.Max;
        }

        private void pbMax_MouseLeave(object sender, EventArgs e)
        {
            this.pbMax.BackgroundImage = global::HOZProject.Properties.Resources.Max;
        }

        private void pbClose_MouseEnter(object sender, EventArgs e)
        {
            this.pbClose.BackgroundImage = global::HOZProject.Properties.Resources.Exit;
        }

        private void pbClose_MouseLeave(object sender, EventArgs e)
        {
            this.pbClose.BackgroundImage = global::HOZProject.Properties.Resources.Exit;
        }

        private void pbStart_MouseEnter(object sender, EventArgs e)
        {
            this.pbStart.BackgroundImage = global::HOZProject.Properties.Resources.StartLeave;
        }

        private void pbStart_MouseLeave(object sender, EventArgs e)
        {
            this.pbStart.BackgroundImage = global::HOZProject.Properties.Resources.StartLeave;
        }

        private void pbStop_MouseEnter(object sender, EventArgs e)
        {
            this.pbStop.BackgroundImage = global::HOZProject.Properties.Resources.StopLeave;
        }

        private void pbStop_MouseLeave(object sender, EventArgs e)
        {
            this.pbStop.BackgroundImage = global::HOZProject.Properties.Resources.StopLeave;
        }

        private void pbClose_Click(object sender, EventArgs e)
        {
            try
            {
                if (m_Ms != null)
                {
                    if (m_BackgroundWorker.IsBusy)
                    {
                        if (MessageBox.Show("当前测量正在运行,是否关闭此窗体?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            //线程停止变量
                            m_Ms.key_stop = true;
                            IsClose = true;
                            lblStateMessage.Text = "正在关闭窗体...请等待";
                            pbClose.Enabled = false;
                        }
                        return;
                    }
                }
                if (MessageBox.Show("是否关闭此窗体?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    m_MeasureFile.Save();
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                LogManager.LogError(ex.Message);
            }
        }

        private void pbMin_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void pbMax_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
            }
            else
            {
                this.WindowState = FormWindowState.Maximized;
            }
            //窗体据中
            this.StartPosition = FormStartPosition.CenterScreen;
        }
        #endregion

        #region 新建、保存、打开、初始化、导入配置、查看日志
        private void pbNew_Click(object sender, EventArgs e)
        {
            NewCreate();
        }

        private void NewCreate()
        {
            m_MeasureFile = new MeasureFile();
            if (!m_MeasureFile.New())
            {
                return;
            }
            else
            {
                //清空内容容器中的控件
                ClearPanelControls();
            }
            //实例初始化窗体对象
            if (uControl_Init == null)
            {
                uControl_Init = new UControl_Init(this);
                uControl_Init.ReloadConfig();
            }
            
            m_MeasureFile.MParam = uControl_Init.GetMeasureParam();
        }

        private void pbSave_Click(object sender, EventArgs e)
        {
            if (m_MeasureFile == null)
            {
                MessageBox.Show("请新建一个测量文件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                //保存测量文件
                if (m_MeasureFile.SaveAs())
                {
                    //获取测量文件所在路径
                    string savePath = m_MeasureFile.FilePath;
                    //数据库名称
                    string dbFileName = "MeasureFile.db";
                    //要复制的文件路径
                    string pLocalFilePath = Application.StartupPath +"\\"+dbFileName;
                    string pSaveFilePath = savePath + "\\" + dbFileName;//指定存储的路径
                    if (File.Exists(pLocalFilePath))//必须判断要复制的文件是否存在
                    {
                        //三个参数分别是源文件路径，存储路径，若存储路径有相同文件是否替换
                        File.Copy(pLocalFilePath, pSaveFilePath, true);
                    }
                    //将初始化中的参数，配置到测量参数中
                    m_MeasureFile.MParam = uControl_Init.GetMeasureParamInfo();
                    //设置已保存状态
                    IsSave = true;
                }
            }
        }

        private void pbOpen_Click(object sender, EventArgs e)
        {
            try
            {
                //打开默认路径
                OpenFileDialog openFileDialog = new OpenFileDialog();
                //设置筛选文件格式
                openFileDialog.Filter = "测量文件（*.msf）|*.msf";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    //读取文件
                    string measureFileNamePath = openFileDialog.FileName;
                    m_MeasureFile.FileName = measureFileNamePath;
                    m_MeasureFile.Open();
                    List<CutHole> ListCutHole = m_MeasureFile.ListCutHole;
                    //文件路径
                    string CutHoleFilePath = m_MeasureFile.CutHoleFilePath;
                    CreateCutHoleList(ListCutHole);
                    ////保存测量文件
                    //m_MeasureFile.Save();
                    //设置已保存状态
                    IsSave = true;
                }
            }
            catch (Exception ex)
            {
                LogManager.LogError(ex.Message);
            }
        }

        private void pbInit_Click(object sender, EventArgs e)
        {
            if (uControl_Init == null)
            {
                uControl_Init = new UControl_Init(this);
                uControl_Init.ReloadConfig();
            }
            if (m_FormInit == null)
            {
                m_FormInit = new FormMove();
            }
            m_FormInit.StartPosition = FormStartPosition.CenterScreen;
            m_FormInit.FormBorderStyle = FormBorderStyle.None;
            m_FormInit.Width = uControl_Init.Width + 20;
            m_FormInit.Height = uControl_Init.Height + 20;


            if (m_FormInit.Controls.Count == 0)
            {
                uControl_Init.Location = new Point(10,10);
               
                m_FormInit.Controls.Add(uControl_Init);
                
            }
            m_FormInit.ShowDialog();
        }

        private void pbImportTemplateFile_Click(object sender, EventArgs e)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string m_TemplateFilePath = config.AppSettings.Settings["TemplateFilePath"].Value.ToString();
            //判断保存的路径是否存在
            if (!Directory.Exists(m_TemplateFilePath))
            {
                ////创建路径
                //Directory.CreateDirectory(m_TemplateFilePath);
                FolderBrowserDialog dialog = new FolderBrowserDialog();
                dialog.Description = "请选择文件路径";
                //dialog.RootFolder = Environment.SpecialFolder.Programs;
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    m_TemplateFilePath = dialog.SelectedPath;
                    config.AppSettings.Settings["TemplateFilePath"].Value = m_TemplateFilePath;
                    config.Save(ConfigurationSaveMode.Modified);
                    ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件
                }
            }
            //打开默认路径
            OpenFileDialog openFileDialog = new OpenFileDialog();
            //设置默认打开路径(绝对路径)
            openFileDialog.InitialDirectory = m_TemplateFilePath;
            openFileDialog.Filter = "样品参数文件|*.cfg";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                if (uControl_Init == null)
                {
                    uControl_Init = new UControl_Init(this);
                }
                //设置选择的模板文件
                uControl_Init.ReadConfigPath = openFileDialog.FileName;
                //获取文件
                uControl_Init.ReadConfigInfo();
            }
        }

        private void pbLog_Click(object sender, EventArgs e)
        {
            m_FormLog = new Form();
            m_FormLog.StartPosition = FormStartPosition.CenterScreen;
            if (ucLog == null)
            {
                ucLog = new UControl_Log();
            }
            m_FormLog.FormBorderStyle = FormBorderStyle.None;
            m_FormLog.Width = ucLog.Width;
            m_FormLog.Height = ucLog.Height;
            ucLog.Name = "UControl_Log";
            //获取日志信息
            if (listmsg.Items.Count>0)
            {
                string[] strLog = new string[listmsg.Items.Count];
                for (int i = 0; i < listmsg.Items.Count; i++)
                {
                    //赋值给数组
                    strLog[i] = listmsg.Items[i].ToString();
                }
                ucLog.ShowProcessLogInfo(strLog);
            }
            m_FormLog.Controls.Add(ucLog);
            m_FormLog.ShowDialog();
        }

        //显示日志
        private void AddLogListInfo(ThreadStatusEventArgs e)
        {
            if (m_FormLog != null)
            {
                foreach (Control item in m_FormLog.Controls)
                {
                    if (item is UserControl)
                    {
                        if (item.Name == "UControl_Log")
                        {
                             ucLog = (UControl_Log)item;
                            //获取日志信息
                            if (listmsg.Items.Count > 0)
                            {
                                string[] strLog = new string[listmsg.Items.Count];
                                for (int i = 0; i < listmsg.Items.Count; i++)
                                {
                                    //赋值给数组
                                    strLog[i] = listmsg.Items[i].ToString();
                                }
                                ucLog.ShowProcessLogInfo(strLog);
                            }
                        }
                    }
                }
            }
        }
        #endregion

        #region 修改切孔状态
        /// <summary>
        /// 修改切孔状态
        /// </summary>
        /// <param name="cutHoleCode"></param>
        /// <param name="States"></param>
        public void ChangeCutHoleState(string CutHoleName, int States)
        {
            foreach (Control item in plLeftContent.Controls)
            {
                if (item is UserControl)
                {
                    UControl_CutHole cutHole = (UControl_CutHole)item;
                    if (cutHole.CutHoleName == CutHoleName)
                    {
                        Button btnCutHole = (Button)cutHole.Controls.Find("btnCutHole", false)[0];
                        switch (States)
                        {
                            //运行中
                            case (int)ThreadState.InProcess:
                                //btnCutHole.BackColor = Color.Yellow;
                                btnCutHole.BackgroundImage = Properties.Resources.CutHole_Yellow;
                                btnCutHole.BackgroundImageLayout = ImageLayout.Center;
                                ChangeCutHoleMeasureState(CutHoleName, States);
                                break;
                            //等待
                            case (int)ThreadState.Waiting:
                                //btnCutHole.BackColor = Color.Yellow;
                                btnCutHole.BackgroundImage = Properties.Resources.CutHole_Yellow;
                                btnCutHole.BackgroundImageLayout = ImageLayout.Center;
                                ChangeCutHoleMeasureState(CutHoleName, States);
                                break;
                            //准备
                            case (int)ThreadState.Ready:
                                //btnCutHole.BackColor = Color.White;
                                btnCutHole.BackgroundImage = Properties.Resources.CutHole_Gray;
                                btnCutHole.BackgroundImageLayout = ImageLayout.Center;
                                ChangeCutHoleMeasureState(CutHoleName, States);
                                break;
                            //失败
                            case (int)ThreadState.Failed:
                                //btnCutHole.BackColor = Color.Red;
                                btnCutHole.BackgroundImage = Properties.Resources.CutHole_Red;
                                btnCutHole.BackgroundImageLayout = ImageLayout.Center;
                                ChangeCutHoleMeasureState(CutHoleName, States);
                                break;
                            //完成
                            case (int)ThreadState.Success:
                                //btnCutHole.BackColor = Color.GreenYellow;
                                btnCutHole.BackgroundImage = Properties.Resources.CutHole_Green;
                                btnCutHole.BackgroundImageLayout = ImageLayout.Center;
                                //修改切孔状态
                                ChangeCutHoleMeasureState(CutHoleName, States);
                                break;
                        }
                        break;
                    }
                }
            }
        }
        #endregion

        #region 修改切孔状态
        public void ChangeCutHoleMeasureState(string CutHoleName, int States)
        {
            if (plPrarInfo.Controls.Count > 0)
            {
                foreach (Control item in plPrarInfo.Controls)
                {
                    if (item is UserControl)
                    {
                        if (item.Name == CutHoleName)
                        {
                            UControl_ParaInfo uControl_ParaInfo = (UControl_ParaInfo)item;
                            //获取切孔列表
                            List<CutHole> aCutHole = m_MeasureFile.ListCutHole;
                            foreach (CutHole cutHoleItem in aCutHole)
                            {
                                if (cutHoleItem.HoleName == CutHoleName)
                                {
                                    //设置开始时间与结束时间
                                    uControl_ParaInfo.StartTime = cutHoleItem.START.ToString();
                                    uControl_ParaInfo.EndTime = cutHoleItem.END.ToString();
                                    uControl_ParaInfo.ShowTime();
                                    break;
                                }
                            }
                            switch (States)
                            {
                                //准备
                                case (int)ThreadState.Ready:
                                    //修改切孔状态
                                    uControl_ParaInfo.lblShowState.Text = "准备";
                                    break;
                                //等待
                                case (int)ThreadState.Waiting:
                                    //修改切孔状态
                                    uControl_ParaInfo.lblShowState.Text = "等待";
                                    break;
                                //进行中
                                case (int)ThreadState.InProcess:
                                    //修改切孔状态
                                    uControl_ParaInfo.lblShowState.Text = "进行中";
                                    break;
                                //完成
                                case (int)ThreadState.Success:
                                    //修改切孔状态
                                    uControl_ParaInfo.lblShowState.Text = "完成";
                                    break;
                                //失败
                                case (int)ThreadState.Failed:
                                    uControl_ParaInfo.lblShowState.Text = "失败";
                                    uControl_ParaInfo.pbMeasure.Value = 100;
                                    uControl_ParaInfo.lblCompletedAmount.Text = "100%";
                                    break;
                            }
                            break;
                        }
                    }
                }
            }
        }
        #endregion

        #region 拖动无窗体的控件
        [DllImport("user32.dll")]//拖动无窗体的控件
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;
        private void FormHOZMain_MouseDown(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                //拖动窗体
                ReleaseCapture();
                SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
            }
        }      
        #endregion

        #region 开始、结束线程事件
        private void pbStart_Click(object sender, EventArgs e)
        {
            if (plLeftContent.Controls.Count==0)
            {
                MessageBox.Show("请添加切孔信息！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (IsSave)
            {
                if (m_BackgroundWorker.IsBusy)
                {
                    MessageBox.Show("线程已经运行!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (MessageBox.Show("是否开始测量!", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    m_BackgroundWorker.RunWorkerAsync(this);
                }
            }
            else
            {
                MessageBox.Show("请保存当前测量文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }

        private void pbStop_Click(object sender, EventArgs e)
        {
            if (m_Ms != null)
            { 
                if (MessageBox.Show("是否停止当前测量?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question)== DialogResult.Yes)
                {
                    //线程停止变量
                    m_Ms.key_stop = true;
                }
            }
        }
        #endregion

        #region 清空内容容器中的控件
        /// <summary>
        /// 清空内容容器中的控件
        /// </summary>
        private void ClearPanelControls()
        {
            //清空内容容器中的控件
            plLeftContent.Controls.Clear();
            plPrarInfo.Controls.Clear();
        }

        /// <summary>
        /// 清空日志控件内容
        /// </summary>
        private void ClearContrlsContent()
        {
            try
            {
                if (ucLog != null)
                {
                    if (ucLog.dgvLog != null)
                    {
                        if (ucLog.dgvLog.Rows.Count > 0)
                        {
                            ucLog.dgvLog.Rows.Clear();
                        }
                    }
                }
                if (listmsg != null)
                {
                    if (listmsg.Items.Count > 0)
                    {
                        listmsg.Items.Clear();
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.LogError(ex.Message);
            }
        }
        #endregion

        #region 测试修改切孔中流程状态
        private void button1_Click(object sender, EventArgs e)
        {
            if (plPrarInfo.Controls.Count > 0)
            {
                string name = textBox1.Text;
                string code = textBox2.Text;
                bool state = Convert.ToBoolean(comboBox1.Text);
                foreach (Control item in plPrarInfo.Controls)
                {
                    if (item is UserControl)
                    {
                        if (item.Name == name)
                        {
                            UControl_ParaInfo uControl_ParaInfo = (UControl_ParaInfo)item;
                            TimeLineItem[] ParaItem = uControl_ParaInfo.TlItem;
                            foreach (TimeLineItem tlItem in ParaItem)
                            {
                                if (tlItem.Code == code)
                                {
                                    tlItem.State = Convert.ToInt32(state);
                                    break;
                                }
                            }
                            uControl_ParaInfo.TimeLineInvalidate();
                            break;
                        }
                    }
                }
            }
        }
        #endregion

        private void FormHOZMain_Resize(object sender, EventArgs e)
        {
            plMain.Left = 12;
            plMain.Top = 12;
            plMain.Width = this.Width - 24;
            plMain.Height = this.Height - 24;
            plFill.Width = plMain.Width - plLeft.Width - 4;
            plFill.Height = plMain.Height - plTop.Height - 4;
            plFill.Left = plLeft.Width + 4;
            plFill.Top = plTop.Height + 4;
        }
    }
}
