using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics.Eventing.Reader;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using grproLib;
using InjectionPC;
using MESClassLibrary.BLL.BasicInfo;
using MESClassLibrary.BLL.Log;
using MESClassLibrary.BLL.ZPPlan;
using MESClassLibrary.DAL;
using MESClassLibrary.DAL.ZPPlan;
using MESClassLibrary.EFModel;
using MESClassLibrary.Model;
using OPCAutomation;

namespace FacOneZPStation
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        #region 变量

        private string strHostIP;
        private string strHostName;
        private OPCServer opcServer;
        private OPCGroups opcGroups;
        private OPCGroup opcGroup1;
        private OPCItems opcItems1;
        private OPCItem[] opcItemm1;

        private OPCGroup opcGroup2;
        private OPCItems opcItems2;
        private OPCItem[] opcItemm2;
        private string[] ItemIDs;
        object ItemValues;
        object Qualities;
        object TimeStamps;
        public bool Connected = false;

        public int[] IsFinish = new int[7];
        public bool IsNew = false;    //是否是新计划或切换计划  true-是新和切换
        public static string planID = "";
        public string ID = "";
        public static string PartNo = "";
        public int stateOK =0;

        private string stationID = "";
        private int step = 0, maxSetp = 0, currentStep = 0;
        private bool IsLast = false;
        int IsHigh = 0;

        #endregion

        private void FrmMain_Load(object sender, EventArgs e)
        {
            var serverUrl = "http://10.60.101.59:8013/";
            var updateXmlFileName = "ZPUpdate.xml";
            var updater = new AutoUpdater();
            if (updater.CheckUpdateLoad(serverUrl, updateXmlFileName))
            {
                Environment.Exit(0);
            }

            Control.CheckForIllegalCrossThreadCalls = false;

            timer1.Interval = Convert.ToInt32(ConfigurationManager.AppSettings["InterVal"]);
            labErrMessage.Text = "";
            //this.WindowState = FormWindowState.Maximized;
            Thread t = new Thread(new ThreadStart(TimeGo));
            t.Start();
            labStationNo.Text = ConfigurationManager.AppSettings["StationNo"];

            StationBLL sbll=new StationBLL();
            DataTable sdt = sbll.SearchInfoByNo(labStationNo.Text);
            if (sdt != null && sdt.Rows.Count > 0)
            {
                stationID = sdt.Rows[0]["StationID"].ToString();
            }
            else
            {
                stationID = "";
            }
            
            initPlan();
            LoadStep();
            ControlButton(labPartNo.Text, currentStep + maxSetp - 1);
            textBox1.Text = "";
            textBox2.Text = "";
            textBox1.Enabled = false;
            textBox2.Focus();

            ZPTagBLL bll = new ZPTagBLL();

            try
            {
                if (CreateServer())
                {
                    if (ConnectServer(strHostIP, "Kepware.KEPServerEX.V6"))
                    {
                        Connected = true;

                        #region 创建组

                        opcGroups = opcServer.OPCGroups;
                        opcGroup1 = opcGroups.Add("Read");
                        opcGroup2 = opcGroups.Add("Write");
                        SetGroupProperty(opcGroup1, 500);
                        SetGroupProperty(opcGroup2, 500);

                        #endregion

                        #region 创建项Read

                        opcItems1 = opcGroup1.OPCItems;
                        opcItems1.DefaultIsActive = true;

                        DataTable dt = bll.SearchRead(labStationNo.Text);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            opcItemm1 = new OPCItem[dt.Rows.Count];
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                opcItemm1[i] = opcItems1.AddItem(dt.Rows[i]["TagName"].ToString(), i);
                            }
                        }

                        #endregion

                        #region 创建项Write

                        opcItems2 = opcGroup1.OPCItems;
                        opcItems2.DefaultIsActive = true;

                        DataTable dt1 = bll.SearchWrite(labStationNo.Text);
                        if (dt1 != null && dt1.Rows.Count > 0)
                        {
                            opcItemm2 = new OPCItem[dt1.Rows.Count];
                            for (int i = 0; i < dt1.Rows.Count; i++)
                            {
                                opcItemm2[i] = opcItems2.AddItem(dt1.Rows[i]["TagName"].ToString(), i);
                            }
                        }

                        #endregion

                        opcGroup1.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(opcGroup1_DataChange);
                    }
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        private void TimeGo()
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 1000;
            timer.Enabled = true;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Tick);
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            labTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            Thread.Sleep(500);
        }

        public void initPlan()
        {
            try
            {
                ZPPlanBLL bll=new ZPPlanBLL();

                labStationNo.Text = ConfigurationManager.AppSettings["StationNo"];

                DataTable dt = bll.GetProductingPlan(labStationNo.Text);
                if (dt != null && dt.Rows.Count > 0)
                {
                    planID = dt.Rows[0]["ID"].ToString();
                    labOrderNo.Text = dt.Rows[0]["OrderNo"].ToString();
                    labPartNo.Text = dt.Rows[0]["PartNo"].ToString();
                    PartNo = labPartNo.Text;
                    labPName.Text = dt.Rows[0]["ProductName"].ToString();
                    labNum.Text = dt.Rows[0]["ProductCount"] + "/" + dt.Rows[0]["OrderCount"];
                    labBadCount.Text = dt.Rows[0]["BadCount"].ToString();
                    this.Tag = dt.Rows[0]["CreateTime"].ToString();
                    IsHigh = dt.Rows[0]["IsHigh"].ToString() == "1" ? 1 : 0;
                    if (dt.Rows[0]["ProductCount"].ToString() == "0")
                    {
                        IsNew = true;
                    }
                    else
                    {
                        IsNew = false;
                    }

                    labErrMessage.Text = "";
                }
                else
                {
                    labOrderNo.Text = "";
                    labPartNo.Text = ""; ;
                    labPName.Text = ""; ;
                    labNum.Text =  "0/0" ;
                    labBadCount.Text = "0";
                    IsNew = true;
                    this.Tag = "";
                    labErrMessage.Text = "没有生产计划,请联系计划员!";
                }

                Program.partNo1 = labPartNo.Text;

                
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        /// <summary>  
        /// 创建服务  
        /// </summary>  
        /// <returns></returns>  
        private bool CreateServer()
        {
            try
            {
                opcServer = new OPCServer();
            }
            catch
            {
                return false;
            }
            return true;
        }

        /// <summary>  
        /// 连接到服务器  
        /// </summary>  
        /// <param name="strHostIP"></param>  
        /// <param name="strHostName"></param>  
        /// <returns></returns>  
        private bool ConnectServer(string strHostIP, string strHostName)
        {
            try
            {
                opcServer.Connect(strHostName, strHostIP);
            }
            catch
            {
                return false;
            }
            return true;
        }

        private void SetGroupProperty(OPCGroup opcGroup, int updateRate)
        {
            opcGroup.IsActive = true;
            opcGroup.DeadBand = 0;
            opcGroup.UpdateRate = updateRate;
            opcGroup.IsSubscribed = true;
        }

        /// <summary>
        /// bool型
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public string ReadSingleValueFromOPC1(int i)
        {
            object ItemValues;
            object Qualities;
            object TimeStamps;

            opcItemm1[i].Read(1, out ItemValues, out Qualities, out TimeStamps);

            if ((ItemValues != null) && (Qualities.ToString() != "Good"))
            {
                return ItemValues.ToString();
            }
            else
            {
                return "";
            }
        }

        public int ReadSingleValueFromOPC2(int i)
        {
            object ItemValues;
            object Qualities;
            object TimeStamps;

            opcItemm1[i].Read(1, out ItemValues, out Qualities, out TimeStamps);

            if ((ItemValues != null) && (Qualities.ToString() != "Good"))
            {
                return Convert.ToInt32(ItemValues.ToString());
            }
            else
            {
                return 0;
            }
        }

        void opcGroup1_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues,ref Array Qualities, ref Array TimeStamps)
        {
            try
            {
                ZPTagValueModel md=new ZPTagValueModel();
                ZPTagValueBLL bll=new ZPTagValueBLL();

                for (int i = 1; i <= NumItems; i++)
                {
                    int handle = Convert.ToInt32(ClientHandles.GetValue(i).ToString().Trim());
                    string value = ItemValues.GetValue(i).ToString();
                    string address = opcItemm1[(Convert.ToInt32(ClientHandles.GetValue(i)))].ItemID;

                    #region 增加value日志

                    md.ID = Guid.NewGuid().ToString();
                    md.TagName = address;
                    md.TagValue = value;

                    bll.AddInfo(md);

                    #endregion
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        void opcGroup2_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues,ref Array Qualities, ref Array TimeStamps)
        {
            try
            {
                ZPTagValueModel md=new ZPTagValueModel();
                ZPTagValueBLL bll=new ZPTagValueBLL();

                for (int i = 1; i <= NumItems; i++)
                {
                    int handle = Convert.ToInt32(ClientHandles.GetValue(i).ToString().Trim());
                    string value = ItemValues.GetValue(i).ToString();
                    string address = opcItemm2[(Convert.ToInt32(ClientHandles.GetValue(i)))].ItemID;


                    #region 增加value日志

                    md.ID = Guid.NewGuid().ToString();
                    md.TagName = address;
                    md.TagValue = value;

                    bll.AddInfo(md);

                    #endregion
                }

            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        /// <summary>
        /// 上一计划
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                IsNew = true;
                ZPPlanBLL bll=new ZPPlanBLL();

                DataTable dt= bll.GetPlan(labStationNo.Text, 1, this.Tag.ToString());
                if (dt != null && dt.Rows.Count > 0)
                {
                    planID = dt.Rows[0]["ID"].ToString();
                    labOrderNo.Text = dt.Rows[0]["OrderNo"].ToString();
                    labPartNo.Text = dt.Rows[0]["PartNo"].ToString();
                    Program.partNo1 = labPartNo.Text;
                    labPName.Text = dt.Rows[0]["ProductName"].ToString();
                    labNum.Text = dt.Rows[0]["ProductCount"].ToString() + "/" + dt.Rows[0]["OrderCount"].ToString();
                    labBadCount.Text = dt.Rows[0]["BadCount"].ToString();
                    this.Tag = dt.Rows[0]["CreateTime"].ToString();
                    ControlButton(labPartNo.Text, currentStep+maxSetp-1);
                }
                else
                {
                    MessageBox.Show("无上一计划!", "提示", MessageBoxButtons.OK);
                    return;
                }
                LoadStep();
                ControlButton(labPartNo.Text, currentStep + maxSetp - 1);
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        /// <summary>
        /// 下一计划
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                IsNew = true;
                ZPPlanBLL bll = new ZPPlanBLL();

                DataTable dt = bll.GetPlan(labStationNo.Text, 2, this.Tag.ToString());
                if (dt != null && dt.Rows.Count > 0)
                {
                    planID = dt.Rows[0]["ID"].ToString();
                    labOrderNo.Text = dt.Rows[0]["OrderNo"].ToString();
                    labPartNo.Text = dt.Rows[0]["PartNo"].ToString();
                    Program.partNo1 = labPartNo.Text;
                    labPName.Text = dt.Rows[0]["ProductName"].ToString();
                    labNum.Text = dt.Rows[0]["ProductCount"].ToString() + "/" + dt.Rows[0]["OrderCount"].ToString();
                    labBadCount.Text = dt.Rows[0]["BadCount"].ToString();
                    this.Tag = dt.Rows[0]["CreateTime"].ToString();
                    ControlButton(labPartNo.Text, currentStep + maxSetp-1);
                }
                else
                {
                    //labErrMessage.Text = "无下一计划!";
                    MessageBox.Show("无下一计划!", "提示", MessageBoxButtons.OK);
                    return;
                }
                //textBox1.SelectAll();
                LoadStep();
                ControlButton(labPartNo.Text, currentStep + maxSetp - 1);
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        /// <summary>
        /// 扫描本体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    ZPBomBLL bombll=new ZPBomBLL();
                    ProductBLL pbll=new ProductBLL();
                    BarCodeBLL barbll=new BarCodeBLL();
                    ZPRecordBLL bll=new ZPRecordBLL();
                    ScanRecordBLL sbll=new ScanRecordBLL();
                    tb_ZPRecord md = new tb_ZPRecord();
                    tb_ZPStepRecord zmd = new tb_ZPStepRecord();
                    ZPStepRecordBLL zpbll=new ZPStepRecordBLL();

                    string barCode="",stockNo="";

                    #region 校验数据

                    if (textBox1.Text.Trim() == "")
                    {
                        //labErrMessage.Text = "条码不能为空!";
                        MessageBox.Show("条码不能为空!", "提示", MessageBoxButtons.OK);
                        textBox1.SelectAll();
                        textBox1.Focus();
                        return;
                    }
                    
                    #endregion

                    #region 判断设备是否准备OK

                    //IsFinish[0] = ReadSingleValueFromOPC1(0).ToLower() == "true" ? 1 : 0;
                    //IsFinish[1] = ReadSingleValueFromOPC1(1).ToLower() == "true" ? 1 : 0;
                    //IsFinish[2] = ReadSingleValueFromOPC1(2).ToLower() == "true" ? 1 : 0;
                    //IsFinish[3] = ReadSingleValueFromOPC1(3).ToLower() == "true" ? 1 : 0;
                    //IsFinish[4] = ReadSingleValueFromOPC1(4).ToLower() == "true" ? 1 : 0;
                    //IsFinish[5] = ReadSingleValueFromOPC1(5).ToLower() == "true" ? 1 : 0;
                    //IsFinish[6] = ReadSingleValueFromOPC1(6).ToLower() == "true" ? 1 : 0;
                    stateOK = ReadSingleValueFromOPC1(28).ToLower() == "true" ? 1 : 0;

                    //if (IsFinish[0] == 0 && IsFinish[1] == 0 && IsFinish[2] == 0 && IsFinish[3] == 0 &&
                    //    IsFinish[4] == 0 && IsFinish[5] == 0 && IsFinish[6] == 0)
                    if (stateOK==0)
                    {
                        //labErrMessage.Text = "条码不能为空!";
                        MessageBox.Show("设备未准备OK,不能扫描条码!", "提示", MessageBoxButtons.OK);
                        textBox1.Focus();
                        textBox1.SelectAll();
                        textBox1.Text = "";
                        return;
                    }

                    #endregion

                    #region 判断是一维码还是二维码

                    if (textBox1.Text.Trim().Contains('.'))    //二维码
                    {
                        string[] aa = textBox1.Text.Split('.');
                        Program.partNo = aa[0];

                        #region 根据二维码查找一维码

                        DataTable dt4 = barbll.searchBarCode(textBox1.Text.Trim(), 2);
                        if (dt4 != null && dt4.Rows.Count > 0)
                        {
                            barCode = dt4.Rows[0]["OneBarCode"].ToString();
                        }
                        else
                        {
                            MessageBox.Show("条码有误,请重新扫描!", "提示", MessageBoxButtons.OK);
                            textBox1.Focus();
                            textBox1.SelectAll();
                            return;
                        }

                        #endregion
                    }
                    else
                    {
                        string barcode = textBox1.Text.Trim(); 

                        DataTable dt4 = barbll.searchBarCode(textBox1.Text.Trim(), 1);
                        if (dt4 != null && dt4.Rows.Count > 0)
                        {
                            barCode = textBox1.Text.Trim();
                            Program.partNo = dt4.Rows[0]["PartNo"].ToString();
                        }
                        else
                        {
                            MessageBox.Show("条码有误,请重新扫描!", "提示", MessageBoxButtons.OK);
                            
                            textBox1.SelectAll();
                            textBox1.Focus();
                            return;
                        } 
                    }

                    #endregion

                    #region 判断是否和计划一致

                    DataTable dt = bombll.IsMath(ConfigurationManager.AppSettings["StationNo"], labPartNo.Text.Trim(), Program.partNo,step+1);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        #region 判断是否更换计划

                        if (IsNew)
                        {
                            FrmMould frm=new FrmMould();
                            frm.ShowDialog();
                        }

                        #endregion

                        if (!Program.IsOK )
                        {
                            #region 发送报警信号

                            opcItemm2[1].Write("1");

                            #endregion
                            
                            MessageBox.Show("胎膜号和计划不一致,请更换胎膜!", "提示", MessageBoxButtons.OK);
                            return;
                        }
                        else
                        {
                            #region 产品高低配

                            //IsHigh = dt.Rows[0]["IsHigh"].ToString() == "0" ? 0 : 1;

                            #endregion

                            #region 判断是否重复扫描

                            //DataTable dt5 = bll.SearchInfobyone(barCode);
                            if (sbll.IsScan(barCode,stationID)>0)     
                            {
                                #region 重复扫描

                                DialogResult result = MessageBox.Show("条码为" + barCode + "的蒙皮已经冲孔,是否重新冲孔?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                                if (result == DialogResult.OK)
                                {
                                    FrmPass pass=new FrmPass();

                                    pass.OkBtnClick += (arg1) =>
                                    {
                                        if (!string.IsNullOrEmpty(arg1) && arg1.ToLower() ==
                                            ConfigurationManager.AppSettings["password"].ToLower())
                                        {
                                            pass.Close();

                                            #region 判断胎膜号是否一致

                                            if (ReadSingleValueFromOPC2(29) != Convert.ToInt32(dt.Rows[0]["MouldNo"].ToString()))
                                            {
                                                #region 发送报警信号

                                                opcItemm2[1].Write("1");

                                                #endregion

                                                MessageBox.Show("胎膜号和计划不一致!", "提示", MessageBoxButtons.OK);
                                                return;
                                            }

                                            #endregion

                                            #region 发送信号给PLC  不区分高低配的产品不发送

                                            opcItemm2[0].Write("1");   //扫描成功

                                            if (IsHigh == 0)
                                            {
                                                opcItemm2[3].Write("1");   //低配启动信号
                                            }
                                            else if (IsHigh == 1)
                                            {
                                                opcItemm2[2].Write("1");   //高配启动信号
                                            }
                                            opcItemm2[4].Write(dt.Rows[0]["MouldNo"].ToString());  //胎膜号

                                            #endregion

                                            #region 删除当前工位该条码的信息,暂时屏蔽

                                            //zpbll.DelInfoByStation(labStationNo.Text, textBox1.Text);

                                            #endregion

                                            #region 重新存步骤信息

                                            zmd.BarCode = textBox1.Text.Trim();
                                            zmd.StationID = stationID;
                                            zmd.MouldNo = ReadSingleValueFromOPC2(29).ToString();
                                            zmd.Step = currentStep + step;
                                            zmd.IsOK = 1;
                                            zmd.CreateTime=DateTime.Now;
                                            zmd.PlanID = planID;

                                            zpbll.AddInfo(zmd);

                                            //md.ID = Guid.NewGuid().ToString();
                                            //md.OneBarCode = barCode;
                                            //md.planID = planID;

                                            //bll.AddInfo(md);

                                            #endregion


                                            #region 更新工位扫描物料对应的条码

                                            zpbll.UpdateBarCode(stationID, textBox1.Text.Trim(), planID);

                                            #endregion

                                            if (step + 1 == maxSetp)
                                            {
                                                #region 存装配记录

                                                md.OneBarCode = textBox1.Text.Trim();
                                                md.PlanID = planID;

                                                bll.AddInfo(md);

                                                #endregion
                                            }

                                        }
                                        else
                                        {
                                            MessageBox.Show("密码错误,请重新输入!", "提示", MessageBoxButtons.OK);
                                            return;
                                        }
                                    };
                                    pass.ShowDialog();
                                    LoadStep();
                                }
                                
                                #endregion

                            }
                            else    
                            {
                                #region 第一次扫描

                                #region 判断胎膜号是否一致

                                if (ReadSingleValueFromOPC2(29) != Convert.ToInt32(dt.Rows[0]["MouldNo"].ToString()))
                                {
                                    #region 发送报警信号

                                    opcItemm2[1].Write("1");

                                    #endregion

                                    MessageBox.Show("胎膜号和计划不一致!", "提示", MessageBoxButtons.OK);
                                    return;
                                }

                                #endregion

                                #region 发送信号给PLC   不邠高度配的产品不发启动信号

                                opcItemm2[0].Write("1");   //扫描成功

                                if (IsHigh == 0)
                                {
                                    opcItemm2[3].Write("1");   //低配启动信号
                                }
                                else if (IsHigh == 1)
                                {
                                    opcItemm2[2].Write("1");   //高配启动信号
                                }

                                opcItemm2[4].Write(dt.Rows[0]["MouldNo"].ToString());  //胎膜号

                                #endregion

                                #region 存步骤信息

                                zmd.BarCode = textBox1.Text.Trim();
                                zmd.StationID = stationID;
                                zmd.MouldNo = ReadSingleValueFromOPC2(29).ToString();
                                zmd.Step = currentStep + 1;
                                zmd.IsOK = 1;
                                zmd.CreateTime = DateTime.Now;
                                zmd.PlanID = planID;

                                zpbll.AddInfo(zmd);

                                #endregion

                                #region 更新物料绑定本体

                                zpbll.UpdateBarCode(stationID, textBox1.Text.Trim(), planID);

                                #endregion

                                if (step + 1 == maxSetp)
                                {
                                    #region 存装配记录

                                    md.OneBarCode = textBox1.Text.Trim();
                                    md.PlanID = planID;

                                    bll.AddInfo(md);

                                    #endregion
                                }
                                
                                LoadStep();

                                #endregion
                            }

                            #endregion
                        }
                    }
                    else
                    {
                        MessageBox.Show("扫描条码和计划不一致,请重新扫描!", "提示", MessageBoxButtons.OK);
                        textBox1.Focus();
                        textBox1.SelectAll();
                        textBox1.Text = "";
                    }

                    #endregion
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        /// <summary>
        /// 打印标签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                ZPRecordBLL bll=new ZPRecordBLL();
                ProductBLL pbll=new ProductBLL();
                ZPPlanBLL planbll = new ZPPlanBLL();
                ZPBoxBLL boxbll = new ZPBoxBLL();
                ZPRecordModel md=new ZPRecordModel();
                ZPPlanModel zmd=new ZPPlanModel();
                ZPBoxModel boxmd=new ZPBoxModel();

                string stockNo = "", partNo = "", partName = "", barCode = "",  onebarCode = "", batch = "", oldbarCode = "", oldonebarCode = "", filename = "", reportName = "";
                DateTime time;
                int packCount = 0;
                string old_box = "", new_box = "";

                #region 查询存货代码

                DataTable dt = pbll.SearchInfoByPartNo(labPartNo.Text.Trim());
                if (dt != null && dt.Rows.Count > 0)
                {
                    stockNo = dt.Rows[0]["StockNo"].ToString();
                    packCount = Convert.ToInt32(dt.Rows[0]["PackCount"]);
                }
                else
                {
                    stockNo = "";
                    packCount = 0;
                }

                #endregion

                time = GetDateTime();

                if (time.Hour >= 8 && time.Hour < 20)
                {
                    batch = time.ToString("yyMMdd");
                }
                else
                {
                    if (time.Hour >= 0 && time.Hour < 8)
                    {
                        batch = time.AddDays(-1).ToString("yyMMdd");
                    }
                    else if (time.Hour >= 20 && time.Hour <= 23)
                    {
                        batch = time.ToString("yyMMdd");
                    }
                }

                #region 查询当前产品是否有未打印的标签

                DataTable dt1 = bll.SearchPrint(planID);
                if (dt1 != null && dt1.Rows.Count > 0)
                {
                    md.ID = dt1.Rows[0]["ID"].ToString();
                    time = GetDateTime();
                    partNo = labPartNo.Text.Trim();
                    partName = labPName.Text.Trim();

                    DataTable dt2 = bll.SearchBarCode(stockNo, batch);
                    if (dt2 != null && dt2.Rows.Count > 0)
                    {
                        oldonebarCode = dt2.Rows[0]["OneBarCode1"].ToString();
                        oldbarCode = dt2.Rows[0]["BarCode"].ToString();

                        onebarCode = oldonebarCode.Substring(0, oldonebarCode.Length - 4) + (Convert.ToInt32(oldonebarCode.Substring(oldonebarCode.Length - 4, 4)) + 1).ToString().PadLeft(4, '0');
                        barCode = oldbarCode.Substring(0, oldbarCode.Length - 4) +(Convert.ToInt32(oldbarCode.Substring(oldbarCode.Length - 4, 4)) + 1).ToString().PadLeft(4, '0');
                    }
                    else
                    {
                        onebarCode = stockNo + batch + "0001";
                        barCode = labPartNo.Text.Trim() + "." + batch + ".0001";
                    }

                    #region 打印标签

                    filename = System.AppDomain.CurrentDomain.BaseDirectory + "zp.grf";
                    DataTable headTable = new DataTable();
                    headTable.Columns.Add("time");
                    headTable.Columns.Add("partNo");
                    headTable.Columns.Add("PartName");
                    headTable.Columns.Add("OneBarCode");
                    DataRow row = headTable.NewRow();
                    row["time"] = time.ToString("yyyy-MM-dd HH:mm:ss");
                    row["partNo"] = partNo;
                    row["PartName"] = partName;
                    row["OneBarCode"] = onebarCode;

                    reportName = ConfigurationManager.AppSettings["printName"].ToString();
                    headTable.Rows.Add(row);

                    ReportHelper rp = new ReportHelper(filename, headTable, null, (int)GRPaperOrientation.grpoDefault, 1, reportName);

                    rp.Report.Print(false);

                    #endregion

                    #region 更新数据

                    md.IsOK = 1;
                    md.PrintType = 0;
                    md.PrintTime = time;
                    md.OneBarCode1 = onebarCode;
                    md.BarCode = barCode;

                    bll.UpdatePrint(md);

                    zmd.ID = planID;
                    planbll.updateQty(zmd);

                    #endregion

                    #region 查询是否够40根,够则打印箱单   20210412增加

                    DataTable sumdt = bll.GetCountByPartNo(labPartNo.Text.Trim()+'.'+batch);
                    if (sumdt != null && sumdt.Rows.Count > 0)
                    {
                        if (Convert.ToInt32(sumdt.Rows[0]["qty"].ToString()) >= packCount)
                        {
                            #region 生成箱单

                            DataTable boxdt = boxbll.SearchBoxByPartNo(labPartNo.Text.Trim());
                            if (boxdt != null && boxdt.Rows.Count > 0)
                            {
                                old_box = boxdt.Rows[0]["BoxNo"].ToString();
                                new_box = old_box.Substring(0, old_box.Length - 6) + (Convert.ToInt32(old_box.Substring(old_box.Length - 6, 6)) + 1).ToString().PadLeft(6, '0');
                            }
                            else
                            {
                                new_box = labPartNo.Text.Trim() + '.' + batch + ".000001";
                            }

                            #endregion

                            #region 打印箱单

                            filename = System.AppDomain.CurrentDomain.BaseDirectory + "box.grf";
                            DataTable headTable1 = new DataTable();
                            headTable1.Columns.Add("BoxNo");
                            headTable1.Columns.Add("PartName");
                            headTable1.Columns.Add("PartNo");
                            headTable1.Columns.Add("Batch");
                            headTable1.Columns.Add("PackCount");
                            DataRow row1 = headTable1.NewRow();
                            row1["BoxNo"] = new_box;
                            row1["PartName"] = partName;
                            row1["PartNo"] = partNo;
                            row1["Batch"] = batch;
                            row1["PackCount"] = packCount;

                            reportName = ConfigurationManager.AppSettings["printName1"].ToString();
                            headTable1.Rows.Add(row1);

                            ReportHelper rp1 = new ReportHelper(filename, headTable1, null, (int)GRPaperOrientation.grpoDefault, 1, reportName);

                            rp1.Report.Print(false);

                            #endregion

                            #region 插入箱单

                            boxmd.ID = Guid.NewGuid().ToString();
                            boxmd.BoxNo = new_box;
                            boxmd.PartNo = partNo;
                            boxmd.Flag = 0;

                            boxbll.AddInfo(boxmd);

                            #endregion

                            #region 半成品绑定箱单

                            bll.UpdateBox(partNo, new_box);

                            #endregion
                        }
                    }

                    #endregion

                    //initPlan();
                    initProduct();
                    LoadStep();
                    ControlButton(labPartNo.Text, currentStep + step - 1);
                }
                else
                {
                    MessageBox.Show("当前计划没有可以打印的标签!", "提示", MessageBoxButtons.OK);
                    textBox1.SelectAll();
                    textBox1.Text = "";
                    textBox1.Focus();
                    return;
                }

                #endregion
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                textBox1.SelectAll();
                textBox1.Text = "";
                textBox1.Focus();
            }
        }

        private DateTime GetDateTime()
        {
            string sql = "";
            DateTime time;
            DataTable dt;
            try
            {
                sql = @"select  convert(char(23),getdate(),121) as time";

                dt = SqlHelper.ExecuteDataset(SqlHelper.GetConnSting(), CommandType.Text, sql, null).Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    //time = Convert.ToDateTime(dt.Rows[0]["time"].ToString());
                    time = DateTime.ParseExact(dt.Rows[0]["time"].ToString(), "yyyy-MM-dd HH:mm:ss.fff",
                        System.Globalization.CultureInfo.CurrentCulture);

                }
                else
                {
                    time = DateTime.Now;
                }
                return time;
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                return DateTime.Now;
            }
        }

        /// <summary>
        /// 不合格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                timer1.Enabled = true;
                textBox1.SelectAll();
                FrmChooseDamnPosition frm=new FrmChooseDamnPosition();
                
                frm.Show();
                //ZPRecordBLL bll = new ZPRecordBLL();
                //ZPPlanBLL planbll = new ZPPlanBLL();
                //ZPRecordModel md = new ZPRecordModel();
                //ZPPlanModel zmd = new ZPPlanModel();


                //#region 是否有未打印的产品

                //DataTable dt1 = bll.SearchPrint(planID);
                //if (dt1 != null && dt1.Rows.Count > 0)
                //{
                //    md.IsOK = 0;
                //    md.ID = dt1.Rows[0]["ID"].ToString();
                //    bll.UpdateBad(md);

                //    zmd.ID = planID;
                //    planbll.updateBad(zmd);

                //    initPlan();
                //}
                //else
                //{
                //    MessageBox.Show("当前计划没有零件!", "提示", MessageBoxButtons.OK);
                //    return;
                //}

                //#endregion
                
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                string barCode = "", filename = "", partNo = "", partName = "", reportName="",planID="",oneBarCode="",oneBarCode1="";
                ZPRecordBLL bll=new ZPRecordBLL();
                ZPPlanBLL planbll=new ZPPlanBLL();
                DateTime time;
                int IsOK = 0;
                ZPRecordModel md=new ZPRecordModel();

                time = GetDateTime();

                DialogResult result = MessageBox.Show("确定要补打条码?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    FrmBuDa frm=new FrmBuDa();
                    frm.OkBtnClick += (arg1) =>
                    {
                        #region 打印标签


                        //filename = System.AppDomain.CurrentDomain.BaseDirectory + "zp.grf";
                        //DataTable headTable = new DataTable();
                        //headTable.Columns.Add("time");
                        //headTable.Columns.Add("partNo");
                        //headTable.Columns.Add("PartName");
                        //headTable.Columns.Add("OneBarCode");
                        //DataRow row = headTable.NewRow();
                        //row["time"] = time.ToString("yyyy-MM-dd HH:mm:ss");
                        //row["partNo"] = partNo;
                        //row["PartName"] = partName;
                        //row["OneBarCode"] = onebarCode;

                        filename = System.AppDomain.CurrentDomain.BaseDirectory + "zp.grf";
                        DataTable headTable = new DataTable();
                        headTable.Columns.Add("time");
                        headTable.Columns.Add("partNo");
                        headTable.Columns.Add("PartName");
                        headTable.Columns.Add("OneBarCode");
                        DataRow row = headTable.NewRow();
                        row["time"] = time.ToString("yyyy-MM-dd HH:mm:ss");
                        
                        

                        DataTable dt = bll.SearchInfo(arg1);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            planID = dt.Rows[0]["PlanID"].ToString();
                            IsOK = Convert.ToInt32(dt.Rows[0]["IsOK"].ToString());
                            barCode = dt.Rows[0]["BarCode"].ToString();
                            oneBarCode = dt.Rows[0]["OneBarCode"].ToString();
                            oneBarCode1 = dt.Rows[0]["OneBarCode1"].ToString();
                        }
                        else
                        {
                            planID = "";
                        }

                        DataTable dt1 = planbll.SearchPlanInfo(planID);
                        if (dt1 != null && dt1.Rows.Count > 0)
                        {
                            row["partNo"] = dt1.Rows[0]["PartNo"].ToString();
                            row["PartName"] = dt1.Rows[0]["ProductName"].ToString();
                        }
                        row["OneBarCode"] = oneBarCode1;
                        
                        reportName = ConfigurationManager.AppSettings["printName"].ToString();
                        headTable.Rows.Add(row);

                        ReportHelper rp = new ReportHelper(filename, headTable, null, (int)GRPaperOrientation.grpoDefault, 1, reportName);

                        rp.Report.Print(false);

                        #endregion

                        md.ID = Guid.NewGuid().ToString();
                        md.IsOK = 1;
                        md.PrintType = 1;
                        md.PrintTime = time;
                        md.OneBarCode1 = oneBarCode1;
                        md.BarCode = barCode;
                        md.OneBarCode = arg1;
                        md.planID = planID;

                        bll.AddBudaInfo(md);
                        
                    };
                    frm.ShowDialog();
                    textBox1.Text = "";
                    textBox1.SelectAll();
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        private void labTime_Click(object sender, EventArgs e)
        {
            try
            {
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                Environment.Exit(0);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            initProduct();
        }

        private void initProduct()
        {
            try
            {
                ZPPlanBLL bll = new ZPPlanBLL();

                labStationNo.Text = ConfigurationManager.AppSettings["StationNo"].ToString();

                DataTable dt = bll.GetProductingPlan1(labStationNo.Text, labOrderNo.Text);
                if (dt != null && dt.Rows.Count > 0)
                {
                    planID = dt.Rows[0]["ID"].ToString();
                    labNum.Text = dt.Rows[0]["ProductCount"].ToString() + "/" + dt.Rows[0]["OrderCount"].ToString();
                    labBadCount.Text = dt.Rows[0]["BadCount"].ToString();
                    this.Tag = dt.Rows[0]["CreateTime"].ToString();
                    if (dt.Rows[0]["ProductCount"].ToString() == "0")
                    {
                        IsNew = true;
                    }
                    else
                    {
                        IsNew = false;
                    }
                }
                else
                {
                    initPlan();
                    //labOrderNo.Text = "";
                    //labPartNo.Text = "";
                    
                    //labPName.Text = "";
                    
                    //labNum.Text = "0/0";
                    //labBadCount.Text = "0";
                    //IsNew = true;
                    //this.Tag = "";
                    //MessageBox.Show("没有生产计划,请联系计划员!", "提示", MessageBoxButtons.OK);
                }

                Program.partNo1 = labPartNo.Text;
                
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        /// <summary>
        /// 手动打印箱单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime time;
                string batch = "", partNo = "", partName = "", old_box = "", new_box = "", filename = "", reportName = ""; ;

                ZPRecordBLL bll = new ZPRecordBLL();
                ProductBLL pbll = new ProductBLL();
                ZPPlanBLL planbll = new ZPPlanBLL();
                ZPBoxBLL boxbll = new ZPBoxBLL();
                ZPRecordModel md = new ZPRecordModel();
                ZPPlanModel zmd = new ZPPlanModel();
                ZPBoxModel boxmd = new ZPBoxModel();

                time = GetDateTime();

                if (time.Hour >= 8 && time.Hour < 20)
                {
                    batch = time.ToString("yyMMdd");
                }
                else
                {
                    if (time.Hour >= 0 && time.Hour < 8)
                    {
                        batch = time.AddDays(-1).ToString("yyMMdd");
                    }
                    else if (time.Hour >= 20 && time.Hour <= 23)
                    {
                        batch = time.ToString("yyMMdd");
                    }
                }

                partNo = labPartNo.Text.Trim();
                partName = labPName.Text.Trim();

                #region 20210412增加

                DataTable sumdt = bll.GetCountByPartNo(labPartNo.Text.Trim() + '.' + batch);
                if (sumdt != null && sumdt.Rows.Count > 0)
                {
                    #region 生成箱单

                    DataTable boxdt = boxbll.SearchBoxByPartNo(labPartNo.Text.Trim());
                    if (boxdt != null && boxdt.Rows.Count > 0)
                    {
                        old_box = boxdt.Rows[0]["BoxNo"].ToString();
                        new_box = old_box.Substring(0, old_box.Length - 6) + (Convert.ToInt32(old_box.Substring(old_box.Length - 6, 6)) + 1).ToString().PadLeft(6, '0');
                    }
                    else
                    {
                        new_box = labPartNo.Text.Trim() + '.' + batch + ".000001";
                    }

                    #endregion

                    #region 打印箱单

                    filename = System.AppDomain.CurrentDomain.BaseDirectory + "box.grf";
                    DataTable headTable1 = new DataTable();
                    headTable1.Columns.Add("BoxNo");
                    headTable1.Columns.Add("PartName");
                    headTable1.Columns.Add("PartNo");
                    headTable1.Columns.Add("Batch");
                    headTable1.Columns.Add("PackCount");
                    DataRow row1 = headTable1.NewRow();
                    row1["BoxNo"] = new_box;
                    row1["PartName"] = partName;
                    row1["PartNo"] = partNo;
                    row1["Batch"] = batch;
                    row1["PackCount"] = sumdt.Rows[0]["qty"];

                    reportName = ConfigurationManager.AppSettings["printName1"];
                    headTable1.Rows.Add(row1);

                    ReportHelper rp1 = new ReportHelper(filename, headTable1, null, (int)GRPaperOrientation.grpoDefault, 1, reportName);

                    rp1.Report.Print(false);

                    #endregion

                    #region 插入箱单

                    boxmd.ID = Guid.NewGuid().ToString();
                    boxmd.BoxNo = new_box;
                    boxmd.PartNo = partNo;
                    boxmd.Flag = 1;

                    boxbll.AddInfo(boxmd);

                    #endregion

                    #region 半成品绑定箱单

                    bll.UpdateBox(partNo, new_box);

                    #endregion
                }
                else
                {
                    MessageBox.Show("都已装箱,无需打印箱单!", "提示", MessageBoxButtons.OK);
                }

                #endregion
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(),MethodBase.GetCurrentMethod());
            }
        }

        /// <summary>
        /// 补打箱单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(object sender, EventArgs e)
        {
            try
            {
                string filename = "", boxNo = "", reportName = "", PackCount="",partNo="";
                ZPRecordBLL bll=new ZPRecordBLL();
                ZPPlanBLL planbll = new ZPPlanBLL();
                ZPBoxBLL boxbll=new ZPBoxBLL();
                ZPBoxModel md=new ZPBoxModel();

                DialogResult result = MessageBox.Show("确定要补打条码?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    FrmBuDa frm = new FrmBuDa();
                    frm.OkBtnClick += (arg1) =>
                    {
                        #region 根据条码查找对应的箱单

                        DataTable dt = bll.SearchInfo(arg1);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            planID = dt.Rows[0]["PlanID"].ToString();
                            boxNo = dt.Rows[0]["BoxNo"].ToString();
                        }

                        if (string.IsNullOrEmpty(boxNo))
                        {
                            MessageBox.Show("此零件未装箱或不存在,无需打印箱单!", "提示", MessageBoxButtons.OK);
                            return;
                        }

                        string[] aa = boxNo.Split('.');

                        DataTable dt2 = boxbll.SearchCountByBoxNo(boxNo);
                        if (dt2 != null && dt2.Rows.Count > 0)
                        {
                            PackCount = dt2.Rows[0]["Qty"].ToString();
                        }

                        filename = System.AppDomain.CurrentDomain.BaseDirectory + "box.grf";
                        DataTable headTable1 = new DataTable();
                        headTable1.Columns.Add("BoxNo");
                        headTable1.Columns.Add("PartName");
                        headTable1.Columns.Add("PartNo");
                        headTable1.Columns.Add("Batch");
                        headTable1.Columns.Add("PackCount");
                        DataRow row1 = headTable1.NewRow();


                        DataTable dt1 = planbll.SearchPlanInfo(planID);
                        if (dt1 != null && dt1.Rows.Count > 0)
                        {
                            row1["partNo"] = dt1.Rows[0]["PartNo"].ToString();
                            row1["PartName"] = dt1.Rows[0]["ProductName"].ToString();
                            partNo = dt1.Rows[0]["PartNo"].ToString();
                        }
                        row1["PackCount"] = PackCount;
                        row1["Batch"] = aa[1];
                        row1["BoxNo"] = boxNo;

                        reportName = ConfigurationManager.AppSettings["printName1"];
                        headTable1.Rows.Add(row1);

                        ReportHelper rp1 = new ReportHelper(filename, headTable1, null, (int)GRPaperOrientation.grpoDefault, 1, reportName);

                        rp1.Report.Print(false);

                        #endregion

                        #region 插入箱单

                        md.ID = Guid.NewGuid().ToString();
                        md.BoxNo = boxNo;
                        md.PartNo = partNo;
                        md.Flag = 1;

                        boxbll.AddInfo(md);

                        #endregion
                    };
                    frm.ShowDialog();
                    textBox1.Text = "";
                    textBox1.SelectAll();
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        /// <summary>
        /// 根据产品判断当前工位是不是最后一步,是则显示打印标签等按钮
        /// </summary>
        /// <param name="partNo"></param>
        private void ControlButton(string partNo,int step)
        {
            try
            {
                ZPBomBLL bll=new ZPBomBLL();

                bool flag = bll.IsLast(partNo, step);
                if (!flag)
                {
                    button1.Visible = false;
                    button2.Visible = false;
                    button5.Visible = false;
                    button6.Visible = false;
                    button7.Visible = false;
                    IsLast = false;
                    timer1.Enabled = false;
                }
                else
                {
                    button1.Visible = true;
                    button2.Visible = true;
                    button5.Visible = true;
                    button6.Visible = true;
                    button7.Visible = true;
                    IsLast = true;
                    timer1.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(),MethodBase.GetCurrentMethod());
            }
        }

        private void LoadStep()
        {
            try
            {
                ZPStepRecordBLL bll=new ZPStepRecordBLL();
                ZPBomBLL bbll=new ZPBomBLL();

                #region 获取当前步骤

                DataTable dt = bll.SearchStepByStation(labStationNo.Text, planID,textBox1.Text.Trim());
                if (dt != null && dt.Rows.Count > 0)
                {
                    step = dt.Rows.Count;
                }
                else
                {
                    step = 0;
                }

                #endregion
                
                #region 获取当前工位的总步骤数

                DataTable dt1 = bbll.SearchStep(labPartNo.Text, labStationNo.Text);
                if (dt1 != null && dt1.Rows.Count > 0)
                {
                    maxSetp = dt1.Rows.Count;
                    currentStep = Convert.ToInt32(dt1.Rows[0]["Step"]);
                    if (step >= maxSetp)
                    {
                        step = 0;
                    }
                }
                else
                {
                    maxSetp = 0;
                }

                #endregion


                if (maxSetp - 1 == step)
                {
                    textBox2.Text = "";
                    textBox2.Enabled = false;
                    textBox1.Enabled = true;
                    textBox1.Focus();
                    labErrMessage.Text = "请扫描本体";
                }
                else
                {
                    textBox1.Enabled = false;
                    textBox2.Enabled = true;
                    textBox2.SelectAll();
                    textBox2.Text = "";
                    textBox2.Focus();
                    
                    #region 获取下一步的信息

                    DataTable dt2 = bbll.SearchInfoByStep(labStationNo.Text, labPartNo.Text, step + currentStep);
                    if (dt2 != null && dt2.Rows.Count > 0)
                    {
                        labErrMessage.Text = "扫描物料" + dt2.Rows[0]["MaterialNo"];
                    }
                    else
                    {
                        labErrMessage.Text = "";
                    }

                    #endregion
                }

                
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(),MethodBase.GetCurrentMethod());
            }
        }

        /// <summary>
        /// 扫描物料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    ZPBomBLL bll=new ZPBomBLL();
                    ZPStepRecordBLL srbll = new ZPStepRecordBLL();
                    ScanRecordBLL sbll=new ScanRecordBLL();
                    tb_ZPStepRecord md = new tb_ZPStepRecord();
                    tb_ScanRecord smd=new tb_ScanRecord();

                    int IsBox = 0; //1是箱单0是单个条码
                    string code = "";


                    #region 判断当前步骤校验是箱单还是单个条码

                    DataTable dt = bll.SearchInfoByStep(labStationNo.Text, labPartNo.Text, currentStep+step);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        IsBox = dt.Rows[0]["IsScanCode"].ToString() == "0" ? 1 : 0;
                    }

                    #endregion

                    #region 校验是否扫描过\物料是否和计划匹配

                    DataTable dt1=new DataTable();

                    if (IsBox == 1)
                    {
                        //TODO 无需校验
                        string[] a = textBox2.Text.Trim().Split('.');
                        code = a[0];
                    }
                    else
                    {
                        //TODO 校验条码是否用过

                        if (sbll.IsScan(textBox2.Text.Trim(),"") > 0)
                        {
                            MessageBox.Show("物料条码使用过,请更换物料!", "提示", MessageBoxButtons.OK);
                            textBox2.SelectAll();
                            textBox2.Text = "";
                            textBox2.Focus();
                            return;
                        }
                        else
                        {
                            code = textBox2.Text.Trim();
                        }
                    }

                    dt1 = bll.IsMath(labStationNo.Text, labPartNo.Text, code, currentStep + step);
                    if (dt1 != null && dt1.Rows.Count > 0)
                    {
                        //TODO 是单个条码的记录扫描记录

                        #region 存扫描记录

                        smd.BarCode = textBox2.Text.Trim();
                        smd.CreateTime = DateTime.Now;

                        sbll.AddInfo(smd);

                        #endregion

                        #region 存步骤日志

                        md.StationID = stationID;
                        md.KeyBarCode = textBox2.Text.Trim();
                        md.CreateTime = DateTime.Now;
                        md.IsOK = 1;
                        md.Step = currentStep + step;
                        md.PlanID = planID;

                        srbll.AddInfo(md);

                        #endregion
                    }
                    else
                    {
                        MessageBox.Show("物料与计划不匹配!", "提示", MessageBoxButtons.OK);
                        textBox2.SelectAll();
                        textBox2.Text = "";
                        textBox2.Focus();
                        return;
                    }

                    #endregion

                    LoadStep();
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(),MethodBase.GetCurrentMethod());
            }
        }

    }
}