using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using MESClassLibrary.BLL;
using MESClassLibrary.BLL.BasicInfo;
using MESClassLibrary.BLL.Injection;
using MESClassLibrary.BLL.Inspection;
using MESClassLibrary.BLL.Log;
using MESClassLibrary.BLL.Mistake247;
using MESClassLibrary.BLL.Weight;
using MESClassLibrary.DAL;
using MESClassLibrary.Model;
using OPCAutomation;
using System.IO;
using System.IO.Ports;
using gregn6Lib;
using MESClassLibrary;

namespace InjectionPC
{
    public partial class FrmMainNew : Form
    {
        public FrmMainNew()
        {
            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;

        #endregion

        public string planID = "", productID = "", nextPlanID = "", nextproductID = "";
        public static int ID = 0;
        public string Conn = ConfigurationManager.ConnectionStrings["SqlConnStringWeight"].ConnectionString;

        private void FrmMain_Load(object sender, EventArgs e)
        {
            try
            {
                Control.CheckForIllegalCrossThreadCalls = false;
                Thread t = new Thread(new ThreadStart(TimeGo));
                t.Start();
                timer1.Interval = Program.interVal;
                timer1.Enabled=false;
                panel44.Visible = false;
                panel45.Visible = false;
                textBox4.Text = "";
                textBox3.Text = "";
                label6.Text = Program.station;          //工位
                label8.Text = Program.OperatorName;     //用户
                GetClass();
                comboBox1.Text = Program.Shift;         //班次
                initProduct();
                textBox1.Text = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) +
                                Program.ProductDate.Substring(8, 2);     //批次
                initBarCode();

                if (Convert.ToInt32(Program.station.Substring(2, 2)) <= 4)
                {
                    timer1.Start();
                }
                else
                {
                    timer1.Stop();

                    #region 设置串口属性

                    serialPort1.PortName = ConfigurationManager.AppSettings["PortName"].ToString();
                    serialPort1.BaudRate = 9600;
                    serialPort1.DataBits = 8;
                    serialPort1.StopBits = (StopBits)1;
                    serialPort1.Parity = 0;
                    serialPort1.ReadTimeout = 5000;

                    if (serialPort1.IsOpen)
                    {
                        serialPort1.Close();
                        serialPort1.Open();
                    }
                    else
                    {
                        serialPort1.Open();
                    }

                    #endregion
                }

                #region 连接PLC 暂时注销

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

                //        #region 创建组

                //        opcGroups = opcServer.OPCGroups;
                //        opcGroup1 = opcGroups.Add("Mould");
                //        SetGroupProperty(opcGroup1, 500);
                //        opcGroup2 = opcGroups.Add("Break");
                //        SetGroupProperty(opcGroup2, 500);

                //        #endregion

                //        #region 创建项
                        
                //        opcItems1 = opcGroup1.OPCItems;
                //        opcItems1.DefaultIsActive = true;

                //        PLCMouldBLL bll = new PLCMouldBLL();
                //        PLCBreakBLL bbll=new PLCBreakBLL();

                //        DataTable dt = bll.SearchMould();
                //        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]["Address"].ToString(), i);
                //            }
                //        }

                //        Thread.Sleep(200);

                //        opcItems2 = opcGroup2.OPCItems;
                //        opcItems2.DefaultIsActive = true;
                //        DataTable dt1 = bbll.SearchBreak();

                //        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]["Address"].ToString(), i);
                //            }
                //        }

                //        Thread.Sleep(200);

                //        opcGroup1.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(opcGroup1_DataChange);


                //        #endregion
                //    }
                //    else
                //    {
                //        MessageBox.Show("连接到OPC服务器失败!", "提示", MessageBoxButtons.OK);
                //        Connected = false;
                //        LogHelper.WriteLog("连接到OPC服务器失败!");
                //        return;
                //    }
                //}
                //else
                //{
                //    MessageBox.Show("创建OPC服务失败!", "提示", MessageBoxButtons.OK);
                //    Connected = false;
                //    LogHelper.WriteLog("创建OPC服务失败!");
                //    return;
                //}

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

        }

        void opcGroup1_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues,ref Array Qualities, ref Array TimeStamps)
        {
            try
            {
                InjectionPlanBLL bll = new InjectionPlanBLL();
                BarCodeBLL brbll = new BarCodeBLL();
                BarCodeModel md = new BarCodeModel();
                ProductBLL productBll = new ProductBLL();
                PlasticBLL pbll=new PlasticBLL();
                InjectionBoxBLL boxbll=new InjectionBoxBLL();
                InjectionBoxModel boxmd=new InjectionBoxModel();
                DataTable dt2 = null;
                string code = "", OneCode = "";
                string newcode = "", newcode1 = "", NewOneCode = "", NewOneCode1 = "";
                string IsPack = "", IsOne = "", QLevel="",IsPaint="",PartName="";
                string filename = "",printName="";
                int MaxCount = 0, CurrentCount = 0;
                 
                for (int i = 1; i <= NumItems; i++)
                {
                    if (opcItemm1[(Convert.ToInt32(ClientHandles.GetValue(i)))].ItemID == "BBMPT1.IM01.Mould")
                    {
                        if (ItemValues.GetValue(i).ToString() == "True")
                        {
                            #region 查找当前计划

                            DataTable dt = bll.SearchInfoByName(Program.station);
                            if (dt != null && dt.Rows.Count > 0)
                            {
                                planID = dt.Rows[0]["InjectionPlanID"].ToString();
                                string[] partNo = dt.Rows[0]["PartNo"].ToString().Split(',');
                                string[] stockNo = dt.Rows[0]["StockNo"].ToString().Split(',');
                                string[] ProductNature = dt.Rows[0]["ProductNature"].ToString().Split(',');

                                #region 判断有几个零件号

                                for (int j = 0; j < partNo.Length; j++)
                                {
                                    dt2 = brbll.SearchInfoByPartNo(partNo[j].ToString().Trim());
                                    if (dt2 != null && dt2.Rows.Count > 0)
                                    {
                                        code = dt2.Rows[0]["BarCode"].ToString().Trim();
                                        newcode = code.Substring(0, code.Length - 4) +
                                                  (Convert.ToInt32(code.Substring(code.Length - 4, 4)) + 1).ToString()
                                                  .PadLeft(4, '0');
                                        OneCode = dt2.Rows[0]["OneBarCode"].ToString().Trim();
                                        NewOneCode = OneCode.Substring(0, OneCode.Length - 4) + (Convert.ToInt32(OneCode.Substring(OneCode.Length - 4, 4)) + 1).ToString().PadLeft(4, '0');
                                    }
                                    else
                                    {
                                        newcode = partNo[j].ToString().Trim() + "." + Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2) + "." + "0001";
                                        NewOneCode = stockNo[j].ToString().Trim() + Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2) + "0001";
                                    }

                                    #region 插入数据tb_barCode

                                    md.ID = Guid.NewGuid().ToString();
                                    md.StationID = dt.Rows[0]["StationID"].ToString();
                                    md.OneBarCode = NewOneCode;
                                    md.BarCode = newcode;
                                    md.StockNo = stockNo[j].ToString().Trim();
                                    md.PartNo = partNo[j].ToString().Trim();
                                    md.PrintType = 0;
                                    md.PlanID = planID;
                                    md.ProductNature = ProductNature[j].ToString().Trim();

                                    DataTable pdt = productBll.SearchIsImportByPartNo(partNo[j].ToString());
                                    if (pdt != null && pdt.Rows.Count > 0)
                                    {
                                        if (pdt.Rows[0]["isImport"].ToString() == "1")
                                        {
                                            md.Import = "国产料Kingfa";
                                        }
                                        else
                                        {
                                            md.Import = "";
                                        }
                                    }

                                    brbll.Add_Info_New(md, Program.tableName);

                                    #endregion

                                    #region 打印条码,判断是否打印单个条码

                                    DataTable dt3 = productBll.SearchInfoByPartNo(partNo[j].ToString().Trim());
                                    if (dt3 != null && dt3.Rows.Count > 0)
                                    {
                                        QLevel = dt3.Rows[0]["QLevel"].ToString();
                                        IsOne = dt3.Rows[0]["IsPrintOneTag"].ToString();
                                        IsPack = dt3.Rows[0]["IsPrintPackList"].ToString();
                                        IsPaint = dt3.Rows[0]["IsPlating"].ToString();
                                        PartName=dt3.Rows[0]["ProductName"].ToString();
                                        MaxCount = Convert.ToInt32(dt3.Rows[0]["PackCount"].ToString());
                                    }

                                    #region 打印单个标签

                                    if (IsOne == "1")
                                    {
                                        filename = System.AppDomain.CurrentDomain.BaseDirectory + "单个条码.grf";
                                        DataTable headTable = new DataTable();
                                        headTable.Columns.Add("PrintTime");
                                        headTable.Columns.Add("PartNo");
                                        headTable.Columns.Add("PartName");
                                        headTable.Columns.Add("OneBarCode");
                                        headTable.Columns.Add("BarCode");
                                        DataRow row = headTable.NewRow();
                                        row["PrintTime"] = GetDateTime().ToString("yyyy/MM/dd HH:mm:ss");
                                        row["PartNo"] = partNo[j].ToString().Trim();
                                        row["PartName"] = PartName;
                                        row["OneBarCode"] = NewOneCode;
                                        row["BarCode"] = newcode;

                                        DataTable dt4 = pbll.SearchInfo(partNo[j].ToString().Trim(),
                                            dt.Rows[0]["StationID"].ToString());
                                        if (dt4 != null && dt4.Rows.Count > 0)
                                        {
                                            printName ="Printer"+ dt4.Rows[0]["PrinterNo"].ToString();
                                        }

                                        string 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

                                    DataTable dt5 = brbll.SearchBoxIsNull(partNo[j].ToString().Trim(),
                                            dt.Rows[0]["StationID"].ToString(), Program.tableName,ProductNature[j].ToString().Trim());
                                   
                                    if (dt5 != null && dt5.Rows.Count > 0)
                                    {
                                        CurrentCount = Convert.ToInt32(dt5.Rows[0]["SumCount"].ToString());
                                    }

                                    if (CurrentCount >= MaxCount)
                                    {
                                        #region 判断是否满箱,满箱打印箱单

                                        DialogResult result = MessageBox.Show("是否打印装箱单?", "提示", MessageBoxButtons.OKCancel,
                                            MessageBoxIcon.Information);
                                        if (result == DialogResult.OK)
                                        {
                                            filename = System.AppDomain.CurrentDomain.BaseDirectory + "装箱单.grf";
                                            DataTable headTable = new DataTable();
                                            headTable.Columns.Add("BoxNo");
                                            headTable.Columns.Add("PartName");
                                            headTable.Columns.Add("PartNo");
                                            headTable.Columns.Add("BatchNo");
                                            headTable.Columns.Add("PackCount");
                                            headTable.Columns.Add("QLevel");
                                            DataRow row = headTable.NewRow();

                                            row["BatchNo"] = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2);

                                            #region 查询当前批次装箱单

                                            DataTable dt6 = boxbll.SeachInfoByBox(partNo[j].ToString().Trim(), Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2));
                                            if (dt6 != null && dt6.Rows.Count > 0)
                                            {
                                                row["BoxNo"] =
                                                    dt6.Rows[0]["BoxNo"].ToString().Substring(0,
                                                        dt6.Rows[0]["BoxNo"].ToString().Length - 6) +
                                                    (Convert.ToInt32(dt6.Rows[0]["BoxNo"].ToString()
                                                         .Substring(dt6.Rows[0]["BoxNo"].ToString().Length - 6, 6)) + 1)
                                                    .ToString().PadLeft(6, '0');
                                            }
                                            else
                                            {
                                                row["BoxNo"] =
                                                    partNo[j].ToString().Trim() + "." +
                                                    Program.ProductDate.Substring(2, 2) +
                                                    Program.ProductDate.Substring(5, 2) +
                                                    Program.ProductDate.Substring(8, 2) + "." + "000001";
                                            }

                                            #endregion

                                            row["PartNo"] = partNo[j].ToString().Trim();
                                            row["PartName"] = PartName;
                                            row["PackCount"] = MaxCount.ToString() + "  EA";
                                            row["QLevel"] = QLevel;

                                            #region 更新barCode表中BoxNo的绑定关系

                                            brbll.UpdateBoxNo(Program.tableName, row["BoxNo"].ToString(),
                                                partNo[j].ToString().Trim());

                                            #endregion

                                            #region 保存箱单记录

                                            boxmd.ID = Guid.NewGuid().ToString();
                                            boxmd.BoxNo = row["BoxNo"].ToString();
                                            boxmd.IsFlag = 0;
                                            boxmd.BoxCount = MaxCount;

                                            boxbll.AddInfo(boxmd);

                                            #endregion

                                            #region 打印箱单

                                            string 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 给WMS传递接口
                                            string jsonParam = " [{\"ServiceType\":\"AddMesData\",\"OperName\":\"ADMIN\"}]";
                                            string strJson = "";

                                            //WebService.WebReference.JsonService webService = new WebService.WebReference.JsonService();
                                            //webService.Url = ConfigurationManager.AppSettings["WMSWebServiceURL"].ToString();
                                            //webService.Timeout = 1200000;

                                            #region 组织参数

                                            List<WMS_InjectionModel> list1=new List<WMS_InjectionModel>();
                                            WMS_InjectionModel md1=new WMS_InjectionModel();

                                            md1.BarCode = boxmd.BoxNo;
                                            md1.PartCode = partNo[j].ToString().Trim();
                                            md1.ProjectId = "";
                                            md1.Batch = Program.ProductDate.Substring(2, 2) +
                                                        Program.ProductDate.Substring(5, 2) +
                                                        Program.ProductDate.Substring(8, 2);
                                            md1.FromLocCode = "S03";
                                            md1.ToLocCode = "";
                                            md1.Qty = MaxCount;
                                            md1.GoodQty = MaxCount;
                                            md1.LineId = ConfigurationManager.AppSettings["LineID"].ToString();
                                            md1.ProduceDate=DateTime.Now;
                                            md1.State = 2;
                                            md1.Remark = "";

                                            list1.Add(md1);

                                            #endregion

                                            if (IsOne == "1")    //大件
                                            {

                                            }
                                            else                //小件
                                            {
                                                strJson = "[116," + JSONTools.ScriptSerialize<List<WMS_InjectionModel>>(list1) + "]";
                                            }

                                            #endregion
                                        }
                                        else
                                        {
                                            
                                        }

                                        #endregion

                                        
                                    }
                                    #endregion

                                    initBarCode();
                                }

                                #endregion
                            }

                            #endregion
                        }
                    }
                }
            }
            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)
        {
            label2.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            Thread.Sleep(500);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            int wID = 0;
            WeightRecordBLL wrbll = new WeightRecordBLL();
            WeightBLL wbll = new WeightBLL();
            WeightRecordModel wmd=new WeightRecordModel();
            InjectionPlanBLL bll = new InjectionPlanBLL();
            BarCodeBLL brbll = new BarCodeBLL();
            BarCodeModel md = new BarCodeModel();
            ProductBLL productBll = new ProductBLL();
            PlasticBLL pbll = new PlasticBLL();
            InjectionBoxBLL boxbll = new InjectionBoxBLL();
            InjectionBoxModel boxmd = new InjectionBoxModel();
            InjectionQtyBLL qbll=new InjectionQtyBLL();
            InjectionQtyModel qmd = new InjectionQtyModel();
            StationBLL sbll=new StationBLL();

            DataTable dt2 = null;
            string code = "", OneCode = "";
            string newcode = "", newcode1 = "", NewOneCode = "", NewOneCode1 = "";
            string IsPack = "", IsOne = "", QLevel = "", IsPaint = "", PartName = "";
            string filename = "", printName = "",StationID="";
            int MaxCount = 0, CurrentCount = 0;

            try
            {
                timer1.Enabled=false; 
                GetClass();

                #region 查找MES数据库总存储的最大ID

                DataTable wrdt = wrbll.SearchMaxIDByDevice(Program.station);
                if (wrdt != null && wrdt.Rows.Count > 0)
                {
                    ID = Convert.ToInt32(wrdt.Rows[0]["ID"].ToString());
                }
                else
                {
                    ID = 0;
                }

                #endregion

                #region 查找称重数据库的最大ID

                DataTable wdt = wbll.SearchInfo(Conn);
                if (wdt != null && wdt.Rows.Count > 0)
                {
                    wID = Convert.ToInt32(wdt.Rows[0]["ID"].ToString());
                }
                else
                {
                    wID = 0;
                }

                #endregion

                #region 如果称重数据库里的ID大于MES数据库中的ID,打印条码,并将称重数据库中的ID存入MES数据库

                if (wID > ID)
                {
                    #region 打印

                    #region 查找当前计划

                    DataTable dt = bll.SearchInfoByName(Program.station);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        planID = dt.Rows[0]["InjectionPlanID"].ToString();
                        string[] partNo = dt.Rows[0]["PartNo"].ToString().Split(',');
                        string[] stockNo = dt.Rows[0]["StockNo"].ToString().Split(',');
                        string[] ProductNature = dt.Rows[0]["ProductNature"].ToString().Split(',');

                        #region 判断有几个零件号

                        for (int j = 0; j < partNo.Length; j++)
                        {
                            dt2 = brbll.SearchInfoByPartNo(partNo[j].ToString().Trim());
                            if (dt2 != null && dt2.Rows.Count > 0)
                            {
                                code = dt2.Rows[0]["BarCode"].ToString().Trim();
                                newcode = code.Substring(0, code.Length - 4) +
                                          (Convert.ToInt32(code.Substring(code.Length - 4, 4)) + 1).ToString()
                                          .PadLeft(4, '0');
                                OneCode = dt2.Rows[0]["OneBarCode"].ToString().Trim();
                                NewOneCode = OneCode.Substring(0, OneCode.Length - 4) + (Convert.ToInt32(OneCode.Substring(OneCode.Length - 4, 4)) + 1).ToString().PadLeft(4, '0');
                            }
                            else
                            {
                                newcode = partNo[j].ToString().Trim() + "." + Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2) + "." + "0001";
                                NewOneCode = stockNo[j].ToString().Trim() + Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2) + "0001";
                            }

                            #region 插入数据tb_barCode

                            md.ID = Guid.NewGuid().ToString();
                            md.StationID = dt.Rows[0]["StationID"].ToString();
                            md.OneBarCode = NewOneCode;
                            md.BarCode = newcode;
                            md.StockNo = stockNo[j].ToString().Trim();
                            md.PartNo = partNo[j].ToString().Trim();
                            md.PrintType = 0;
                            md.PlanID = planID;
                            md.ProductNature = ProductNature[j].ToString().Trim();

                            DataTable pdt = productBll.SearchIsImportByPartNo(partNo[j].ToString());
                            if (pdt != null && pdt.Rows.Count > 0)
                            {
                                if (pdt.Rows[0]["isImport"].ToString() == "1")
                                {
                                    md.Import = "国产料Kingfa";
                                }
                                else
                                {
                                    md.Import = "";
                                }
                            }

                            brbll.Add_Info_New(md, Program.tableName);

                            #endregion

                            #region 增加产量

                            qmd.ID = Guid.NewGuid().ToString();
                            qmd.PlanID = planID;
                            qmd.StationID = getStationID(Program.station);
                            qmd.ProductDate = Program.ProductDate;
                            qmd.ClassName = Program.Shift;
                            qmd.StockNo = stockNo[j].ToString().Trim();
                            qmd.PartNo = partNo[j].ToString().Trim();
                            if (ProductNature[j].ToString().Trim() == "售后件")
                            {
                                qmd.MarketCount = 1;
                            }
                            else
                            {
                                qmd.MarketCount = 0;
                            }

                            DataTable isExistdt = qbll.SearchInfo(qmd);
                            if (isExistdt != null && isExistdt.Rows.Count > 0)
                            {
                                qbll.UpdateQty(qmd);
                            }
                            else
                            {
                                qmd.ProductCount = 1;
                                qbll.AddInfo(qmd);
                            }
                            
                            #endregion

                            #region 打印条码,判断是否打印单个条码

                            DataTable dt3 = productBll.SearchInfoByPartNo(partNo[j].ToString().Trim());
                            if (dt3 != null && dt3.Rows.Count > 0)
                            {
                                QLevel = dt3.Rows[0]["QLevel"].ToString();
                                IsOne = dt3.Rows[0]["IsPrintOneTag"].ToString();
                                IsPack = dt3.Rows[0]["IsPrintPackList"].ToString();
                                IsPaint = dt3.Rows[0]["IsPlating"].ToString();
                                PartName = dt3.Rows[0]["ProductName"].ToString();
                                MaxCount = Convert.ToInt32(dt3.Rows[0]["PackCount"].ToString());
                            }

                            #region 打印单个标签

                            if (IsOne == "1")
                            {
                                filename = System.AppDomain.CurrentDomain.BaseDirectory + "单个条码.grf";
                                DataTable headTable = new DataTable();
                                headTable.Columns.Add("PrintTime");
                                headTable.Columns.Add("PartNo");
                                headTable.Columns.Add("PartName");
                                headTable.Columns.Add("OneBarCode");
                                headTable.Columns.Add("BarCode");
                                DataRow row = headTable.NewRow();
                                row["PrintTime"] = GetDateTime().ToString("yyyy/MM/dd HH:mm:ss");
                                row["PartNo"] = partNo[j].ToString().Trim();
                                row["PartName"] = PartName;
                                row["OneBarCode"] = NewOneCode;
                                row["BarCode"] = newcode;

                                DataTable dt4 = pbll.SearchInfo(partNo[j].ToString().Trim(),
                                    dt.Rows[0]["StationID"].ToString());
                                if (dt4 != null && dt4.Rows.Count > 0)
                                {
                                    printName = "Printer" + dt4.Rows[0]["PrinterNo"].ToString();
                                }

                                string 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 暂时注销自动打印箱单

                            //DataTable dt5 = brbll.SearchBoxIsNull(partNo[j].ToString().Trim(),
                            //        dt.Rows[0]["StationID"].ToString(), Program.tableName, ProductNature[j].ToString().Trim());

                            //if (dt5 != null && dt5.Rows.Count > 0)
                            //{
                            //    CurrentCount = Convert.ToInt32(dt5.Rows[0]["SumCount"].ToString());
                            //}

                            //if (CurrentCount >= MaxCount)
                            //{
                            //    #region 判断是否满箱,满箱打印箱单

                            //    DialogResult result = MessageBox.Show("是否打印装箱单?", "提示", MessageBoxButtons.OKCancel,
                            //        MessageBoxIcon.Information);
                            //    if (result == DialogResult.OK)
                            //    {
                            //        filename = System.AppDomain.CurrentDomain.BaseDirectory + "装箱单.grf";
                            //        DataTable headTable = new DataTable();
                            //        headTable.Columns.Add("BoxNo");
                            //        headTable.Columns.Add("PartName");
                            //        headTable.Columns.Add("PartNo");
                            //        headTable.Columns.Add("BatchNo");
                            //        headTable.Columns.Add("PackCount");
                            //        headTable.Columns.Add("QLevel");
                            //        DataRow row = headTable.NewRow();

                            //        row["BatchNo"] = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2);

                            //        #region 查询当前批次装箱单

                            //        DataTable dt6 = boxbll.SeachInfoByBox(partNo[j].ToString().Trim(), Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2));
                            //        if (dt6 != null && dt6.Rows.Count > 0)
                            //        {
                            //            row["BoxNo"] =
                            //                dt6.Rows[0]["BoxNo"].ToString().Substring(0,
                            //                    dt6.Rows[0]["BoxNo"].ToString().Length - 6) +
                            //                (Convert.ToInt32(dt6.Rows[0]["BoxNo"].ToString()
                            //                     .Substring(dt6.Rows[0]["BoxNo"].ToString().Length - 6, 6)) + 1)
                            //                .ToString().PadLeft(6, '0');
                            //        }
                            //        else
                            //        {
                            //            row["BoxNo"] =
                            //                partNo[j].ToString().Trim() + "." +
                            //                Program.ProductDate.Substring(2, 2) +
                            //                Program.ProductDate.Substring(5, 2) +
                            //                Program.ProductDate.Substring(8, 2) + "." + "000001";
                            //        }

                            //        #endregion

                            //        row["PartNo"] = partNo[j].ToString().Trim();
                            //        row["PartName"] = PartName;
                            //        row["PackCount"] = MaxCount.ToString() + "  EA";
                            //        row["QLevel"] = QLevel;

                            //        #region 更新barCode表中BoxNo的绑定关系

                            //        brbll.UpdateBoxNo(Program.tableName, row["BoxNo"].ToString(),
                            //            partNo[j].ToString().Trim());

                            //        #endregion

                            //        #region 保存箱单记录

                            //        boxmd.ID = Guid.NewGuid().ToString();
                            //        boxmd.BoxNo = row["BoxNo"].ToString();
                            //        boxmd.IsFlag = 0;
                            //        boxmd.BoxCount = MaxCount;

                            //        boxbll.AddInfo(boxmd);

                            //        #endregion

                            //        #region 打印箱单

                            //        string 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
                            //    }
                            //    else
                            //    {

                            //    }

                            //    #endregion
                            //}

                            #endregion
                            
                            #endregion

                            initBarCode();
                        }

                        #endregion
                    }

                    #endregion

                    #endregion

                    #region 存ID

                    wmd.GID = Guid.NewGuid().ToString();
                    wmd.ID = wID;
                    wmd.DeviceNo = Program.station;
                    wrbll.AddInfo(wmd);

                    #endregion
                }

                #endregion

                timer1.Enabled = true;
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
            
        }

        private void initProduct()
        {
            comboBox2.Items.Clear();

            PlasticBLL bll=new PlasticBLL();

            try
            {
                DataTable dt = bll.SearchPartByStation(Program.station);
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        comboBox2.Items.Add(dt.Rows[i]["ProductName"].ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
            
        }

        private void GetClass()
        {
            try
            {
                DateTime aa = GetDateTime();

                if (GetDateTime().Hour >= 8 && GetDateTime().Hour < 20)
                {
                    Program.Shift = "A班";
                    Program.ProductDate = DateTime.Now.ToString("yyyy-MM-dd");
                     
                }
                else
                {
                    Program.Shift = "B班";
                    if (GetDateTime().Hour >= 0 && GetDateTime().Hour < 8)
                    {
                        Program.ProductDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                    }
                    else
                    {
                        Program.ProductDate = DateTime.Now.ToString("yyyy-MM-dd");
                    }
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

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

        private void initBarCode()
        {
            BarCodeBLL bll = new BarCodeBLL();

            try
            {
                glacialList1.Items.Clear();
                DataTable dt = bll.SearchInfo(Program.station);
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        glacialList1.Items.Add(i.ToString());
                        glacialList1.Items[i].SubItems[0].Text = dt.Rows[i]["BarCode"].ToString();
                        glacialList1.Items[i].SubItems[1].Text = dt.Rows[i]["ProductName"].ToString();
                        glacialList1.Items[i].SubItems[2].Text = dt.Rows[i]["PrintType"].ToString();
                        glacialList1.Items[i].SubItems[3].Text = dt.Rows[i]["CreateTime"].ToString() == "" ? "" : Convert.ToDateTime(dt.Rows[i]["CreateTime"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                    }
                }
            }
            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;
        }

        /// <summary>  
        /// 设置组的属性   
        /// </summary>  
        /// <param name="opcGroup"></param>  
        /// <param name="updateRate"></param>
        
        private void SetGroupProperty(OPCGroup opcGroup, int updateRate)
        {
            opcGroup.IsActive = true;
            opcGroup.DeadBand = 0;
            opcGroup.UpdateRate = updateRate;
            opcGroup.IsSubscribed = true;
        }

        #region 调用键盘

        private const Int32 WM_SYSCOMMAND = 274;

        private const UInt32 SC_CLOSE = 61536;

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]

        private static extern bool PostMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]

        private static extern bool PostMessage(IntPtr hWnd, int Msg, uint wParam, uint lParam);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]

        private static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]

        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]

        private static extern int RegisterWindowMessage(string lpString);



        //显示屏幕键盘

        public static int ShowInputPanel()
        {

            try
            {

                dynamic file = "C:\\Program Files\\Common Files\\microsoft shared\\ink\\TabTip.exe";

                if (!System.IO.File.Exists(file))

                    return -1;

                Process.Start(file);

                //return SetUnDock(); //不知SetUnDock()是什么,所以直接注释返回1

                return 1;

            }

            catch (Exception)
            {

                return 255;

            }

        }

        #endregion

        private void label2_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        
        /// <summary>
        /// 手工打印箱单,暂时不需要
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label17_Click(object sender, EventArgs e)
        {
            try
            {
                InjectionPlanBLL bll = new InjectionPlanBLL();
                InjectionBoxBLL boxbll = new InjectionBoxBLL();
                InjectionBoxModel boxmd=new InjectionBoxModel();
                ProductBLL productBll = new ProductBLL();
                BarCodeBLL brbll = new BarCodeBLL();
                PlasticBLL pbll = new PlasticBLL();
                string planID = "", filename = "", QLevel = "", IsOne = "", IsPack = "", IsPaint = "", PartName = "", printName="";
                int CurrentCount = 0, MaxCount = 0;

                DataTable dt = bll.SearchInfoByName(Program.station);
                if (dt != null && dt.Rows.Count > 0)
                {
                    planID = dt.Rows[0]["InjectionPlanID"].ToString();
                    string[] partNo = dt.Rows[0]["PartNo"].ToString().Split(',');
                    string[] stockNo = dt.Rows[0]["StockNo"].ToString().Split(',');
                    string[] ProductNature = dt.Rows[0]["ProductNature"].ToString().Split(',');

                    DataTable dt5 = null;
                    for (int i = 0; i < partNo.Length; i++)
                    {
                        if (ProductNature[i].ToString().Trim() == "正常件")
                        {
                            #region 判断是否有市场件,有:提示打印;无:不提示直接打印

                            DataTable dt7 = brbll.IsHave(partNo[i].ToString().Trim(),
                                dt.Rows[0]["StationID"].ToString(), Program.tableName);
                            if (dt7 != null && dt7.Rows.Count > 0)
                            {
                                DialogResult result = MessageBox.Show("是否打印" + ProductNature[i].ToString().Trim() + "的箱单?",
                                    "提示", MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Information);
                                if (result == DialogResult.Yes)
                                {
                                    dt5 = brbll.SearchBoxIsNull(partNo[i].ToString().Trim(),
                                        dt.Rows[0]["StationID"].ToString(), Program.tableName, ProductNature[i].ToString().Trim());
                                }
                                else
                                {
                                    dt5 = brbll.SearchBoxIsNull(partNo[i].ToString().Trim(),
                                        dt.Rows[0]["StationID"].ToString(), Program.tableName, "售后件");
                                }
                            }
                            else
                            {
                                dt5 = brbll.SearchBoxIsNull(partNo[i].ToString().Trim(),
                                    dt.Rows[0]["StationID"].ToString(), Program.tableName, ProductNature[i].ToString().Trim());
                            }
                            #endregion
                            
                        }
                        else
                        {
                            dt5 = brbll.SearchBoxIsNull(partNo[i].ToString().Trim(),
                                dt.Rows[0]["StationID"].ToString(), Program.tableName, ProductNature[i].ToString().Trim() );
                        }
                        
                        if (dt5 != null && dt5.Rows.Count > 0)
                        {
                            CurrentCount = Convert.ToInt32(dt5.Rows[0]["SumCount"].ToString());
                            if (CurrentCount == 0)
                            {
                                MessageBox.Show("当前零件数量为0,不需要打印箱单", "提示", MessageBoxButtons.OK);
                                return;
                            }
                        }

                        DataTable dt3 = productBll.SearchInfoByPartNo(partNo[i].ToString().Trim());
                        if (dt3 != null && dt3.Rows.Count > 0)
                        {
                            QLevel = dt3.Rows[0]["QLevel"].ToString();
                            IsOne = dt3.Rows[0]["IsPrintOneTag"].ToString();
                            IsPack = dt3.Rows[0]["IsPrintPackList"].ToString();
                            IsPaint = dt3.Rows[0]["IsPlating"].ToString();
                            PartName = dt3.Rows[0]["ProductName"].ToString();
                            MaxCount = Convert.ToInt32(dt3.Rows[0]["PackCount"].ToString());
                        }

                        DataTable dt4 = pbll.SearchInfo(partNo[i].ToString().Trim(),
                            dt.Rows[0]["StationID"].ToString());
                        if (dt4 != null && dt4.Rows.Count > 0)
                        {
                            printName = "Printer" + dt4.Rows[0]["PrinterNo"].ToString();
                        }

                        #region 生成箱单并打印

                        filename = System.AppDomain.CurrentDomain.BaseDirectory + "装箱单.grf";
                        DataTable headTable = new DataTable();
                        headTable.Columns.Add("BoxNo");
                        headTable.Columns.Add("PartName");
                        headTable.Columns.Add("PartNo");
                        headTable.Columns.Add("BatchNo");
                        headTable.Columns.Add("PackCount");
                        headTable.Columns.Add("QLevel");
                        DataRow row = headTable.NewRow();

                        row["BatchNo"] = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2);

                        #region 查询当前批次装箱单

                        DataTable dt6 = boxbll.SeachInfoByBox(partNo[i].ToString().Trim(), Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2));
                        if (dt6 != null && dt6.Rows.Count > 0)
                        {
                            row["BoxNo"] =
                                dt6.Rows[0]["BoxNo"].ToString().Substring(0,
                                    dt6.Rows[0]["BoxNo"].ToString().Length - 6) +
                                (Convert.ToInt32(dt6.Rows[0]["BoxNo"].ToString()
                                     .Substring(dt6.Rows[0]["BoxNo"].ToString().Length - 6, 6)) + 1)
                                .ToString().PadLeft(6, '0');
                        }
                        else
                        {
                            row["BoxNo"] =
                                partNo[i].ToString().Trim() + "." +
                                Program.ProductDate.Substring(2, 2) +
                                Program.ProductDate.Substring(5, 2) +
                                Program.ProductDate.Substring(8, 2) + "." + "000001";
                        }

                        #endregion

                        row["PartNo"] = partNo[i].ToString().Trim();
                        row["PartName"] = PartName;
                        row["PackCount"] = CurrentCount.ToString() + "  EA";
                        row["QLevel"] = QLevel;

                        #region 更新barCode表中BoxNo的绑定关系

                        brbll.UpdateBoxNo(Program.tableName, row["BoxNo"].ToString(),
                            partNo[i].ToString().Trim());

                        #endregion 

                        #region 保存箱单记录

                        boxmd.ID = Guid.NewGuid().ToString();
                        boxmd.BoxNo = row["BoxNo"].ToString();
                        boxmd.IsFlag = 0;
                        boxmd.BoxCount = CurrentCount;

                        boxbll.AddInfo(boxmd);

                        #endregion

                        #region 打印箱单

                        string 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

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

        /// <summary>
        /// 手工打印条码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label23_Click(object sender, EventArgs e)
        {
            string code = "",stationID="",OneCode="";
            string newcode = "",partNo="",stockNo="",NewOneCode="";
            string IsPack = "", IsOne = "", QLevel = "", IsPaint = "", PartName = "";
            string filename = "", printName = "";
            int MaxCount = 0, CurrentCount = 0;

            ProductBLL pbll = new ProductBLL();
            BarCodeBLL bll = new BarCodeBLL();
            BarCodeModel md = new BarCodeModel();
            PlasticBLL plbll=new PlasticBLL();
            InjectionBoxBLL boxbll = new InjectionBoxBLL();
            InjectionBoxModel boxmd = new InjectionBoxModel();

            try
            {
                #region 数据合法性判断

                if (comboBox2.Text.Trim() == "")
                {
                    MessageBox.Show("请选择产品!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (textBox1.Text.Trim() == "")
                {
                    MessageBox.Show("请输入批次!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (textBox1.Text.Trim().Length != 6)
                {
                    MessageBox.Show("批次格式不正确!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (textBox2.Text.Trim() == "")
                {
                    MessageBox.Show("请输入数量!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (!IsNumeric(textBox2.Text.Trim()))
                {
                    MessageBox.Show("数量格式不正确!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (Convert.ToInt32(textBox2.Text.Trim()) > 10)
                {
                    MessageBox.Show("数量不能大于10!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                #endregion

                #region 获取工位编号

                StationBLL sbll = new StationBLL();
                DataTable sdt = sbll.SearchInfoByNo(Program.station);
                if (sdt != null && sdt.Rows.Count > 0)
                {
                    stationID = sdt.Rows[0]["StationID"].ToString();
                }

                #endregion

                DialogResult result = MessageBox.Show("确定手工打印条码?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    #region 查询零件号

                    DataTable pdt = pbll.SearchInfoByName(comboBox2.Text, "2000");
                    if (pdt != null && pdt.Rows.Count > 0)
                    {
                        partNo = pdt.Rows[0]["PartNo"].ToString().Trim();
                        stockNo = pdt.Rows[0]["StockNo"].ToString().Trim();
                    }

                    #endregion

                    DataTable dt = bll.SearchSerialNoByBarCodeNew(partNo + "." + textBox1.Text.Trim(),Program.tableName);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        OneCode = dt.Rows[0]["OneBarCode"].ToString().Trim();
                        code = dt.Rows[0]["BarCode"].ToString().TrimEnd();
                        for (int i = 1; i <= Convert.ToInt32(textBox2.Text.Trim()); i++)
                        {
                            newcode = code.Substring(0, code.Length - 4) +
                                      (Convert.ToInt32(code.Substring(code.Length - 4, 4)) + i)
                                      .ToString()
                                      .PadLeft(4, '0');
                            NewOneCode = OneCode.Substring(0, OneCode.Length - 4) +
                                         (Convert.ToInt32(OneCode.Substring(OneCode.Length - 4, 4)) + i).ToString()
                                         .PadLeft(4, '0');
                            string[] part = newcode.Split('.');

                            #region 插入数据tb_barCode

                            md.ID = Guid.NewGuid().ToString();
                            md.StationID = stationID;
                            md.OneBarCode = NewOneCode;
                            md.BarCode = newcode;
                            md.StockNo = stockNo;
                            md.PartNo = partNo;
                            md.PrintType = 1;
                            md.ProductNature = "正常件";
                            //md.PlanID = planID;

                            DataTable dt2 = pbll.SearchIsImportByPartNo(partNo);
                            if (dt2 != null && dt2.Rows.Count > 0)
                            {
                                if (dt2.Rows[0]["isImport"].ToString() == "1")
                                {
                                    md.Import = "国产料Kingfa";
                                }
                                else
                                {
                                    md.Import = "";
                                }
                            }

                            bll.Add_Info_New(md, Program.tableName);

                            #endregion

                            #region 判断是否打印单个条码

                            DataTable dt3 = pbll.SearchInfoByPartNo(partNo);
                            if (dt3 != null && dt3.Rows.Count > 0)
                            {
                                QLevel = dt3.Rows[0]["QLevel"].ToString();
                                IsOne = dt3.Rows[0]["IsPrintOneTag"].ToString();
                                IsPack = dt3.Rows[0]["IsPrintPackList"].ToString();
                                IsPaint = dt3.Rows[0]["IsPlating"].ToString();
                                PartName = dt3.Rows[0]["ProductName"].ToString();
                                MaxCount = Convert.ToInt32(dt3.Rows[0]["PackCount"].ToString());
                            }

                            #endregion

                            #region 打印单个标签

                            if (IsOne == "1")
                            {
                                filename = System.AppDomain.CurrentDomain.BaseDirectory + "单个条码.grf";
                                DataTable headTable = new DataTable();
                                headTable.Columns.Add("PrintTime");
                                headTable.Columns.Add("PartNo");
                                headTable.Columns.Add("PartName");
                                headTable.Columns.Add("OneBarCode");
                                headTable.Columns.Add("BarCode");
                                DataRow row = headTable.NewRow();
                                row["PrintTime"] = GetDateTime().ToString("yyyy/MM/dd HH:mm:ss");
                                row["PartNo"] = partNo;
                                row["PartName"] = PartName;
                                row["OneBarCode"] = NewOneCode;
                                row["BarCode"] = newcode;

                                DataTable dt4 = plbll.SearchInfo(partNo,stationID);
                                if (dt4 != null && dt4.Rows.Count > 0)
                                {
                                    printName = "Printer" + dt4.Rows[0]["PrinterNo"].ToString();
                                }

                                string 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 判断是否满箱,满箱打印箱单   暂时屏蔽

                            //DataTable dt5 = bll.SearchBoxIsNull(partNo, stationID, Program.tableName,"正常件");
                            //if (dt5 != null && dt5.Rows.Count > 0)
                            //{
                            //    CurrentCount = Convert.ToInt32(dt5.Rows[0]["SumCount"].ToString());
                            //}

                            //if (CurrentCount >= MaxCount)
                            //{
                            //    filename = System.AppDomain.CurrentDomain.BaseDirectory + "装箱单.grf";
                            //    DataTable headTable = new DataTable();
                            //    headTable.Columns.Add("BoxNo");
                            //    headTable.Columns.Add("PartName");
                            //    headTable.Columns.Add("PartNo");
                            //    headTable.Columns.Add("BatchNo");
                            //    headTable.Columns.Add("PackCount");
                            //    headTable.Columns.Add("QLevel");
                            //    DataRow row = headTable.NewRow();

                            //    row["BatchNo"] = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2);

                            //    #region 查询当前批次装箱单

                            //    DataTable dt6 = boxbll.SeachInfoByBox(part[0].ToString().Trim(), Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2));
                            //    if (dt6 != null && dt6.Rows.Count > 0)
                            //    {
                            //        row["BoxNo"] =
                            //            dt6.Rows[0]["BoxNo"].ToString().Substring(0,
                            //                dt6.Rows[0]["BoxNo"].ToString().Length - 6) +
                            //            (Convert.ToInt32(dt6.Rows[0]["BoxNo"].ToString()
                            //                 .Substring(dt6.Rows[0]["BoxNo"].ToString().Length - 6, 6)) + 1)
                            //            .ToString().PadLeft(6, '0');
                            //    }
                            //    else
                            //    {
                            //        row["BoxNo"] =
                            //            part[0].ToString().Trim() + "." +
                            //            Program.ProductDate.Substring(2, 2) +
                            //            Program.ProductDate.Substring(5, 2) +
                            //            Program.ProductDate.Substring(8, 2) + "." + "000001";
                            //    }

                            //    #endregion

                            //    row["PartNo"] = partNo;
                            //    row["PartName"] = PartName;
                            //    row["PackCount"] = MaxCount.ToString() + "  EA";
                            //    row["QLevel"] = QLevel;

                            //    #region 更新barCode表中BoxNo的绑定关系

                            //    bll.UpdateBoxNo(Program.tableName, row["BoxNo"].ToString(),
                            //        partNo);

                            //    #endregion

                            //    #region 保存箱单记录

                            //    boxmd.ID = Guid.NewGuid().ToString();
                            //    boxmd.BoxNo = row["BoxNo"].ToString();
                            //    boxmd.IsFlag = 0;
                            //    boxmd.BoxCount = MaxCount;

                            //    boxbll.AddInfo(boxmd);

                            //    #endregion

                            //    #region 打印箱单

                            //    string 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
                            //}

                            #endregion
                        }
                    }
                    else
                    {
                        for (int i = 1; i <= Convert.ToInt32(textBox2.Text.Trim()); i++)
                        {
                            newcode = partNo + "." + textBox1.Text.Trim() + "." + i.ToString().PadLeft(4, '0');
                            NewOneCode = stockNo + textBox1.Text.Trim() + i.ToString().PadLeft(4, '0');
                            string[] part = newcode.Split('.');

                            #region 插入数据tb_barCode

                            md.ID = Guid.NewGuid().ToString();
                            md.StationID = stationID;
                            md.OneBarCode = NewOneCode;
                            md.BarCode = newcode;
                            md.StockNo = stockNo;
                            md.PartNo =partNo;
                            md.PrintType = 1;
                            //md.PlanID = planID;

                            DataTable dt2 = pbll.SearchIsImportByPartNo(partNo);
                            if (dt2 != null && dt2.Rows.Count > 0)
                            {
                                if (dt2.Rows[0]["isImport"].ToString() == "1")
                                {
                                    md.Import = "国产料Kingfa";
                                }
                                else
                                {
                                    md.Import = "";
                                }
                            }

                            bll.Add_Info_New(md, Program.tableName);

                            #endregion

                            #region 判断是否打印单个条码

                            DataTable dt3 = pbll.SearchInfoByPartNo(partNo);
                            if (dt3 != null && dt3.Rows.Count > 0)
                            {
                                QLevel = dt3.Rows[0]["QLevel"].ToString();
                                IsOne = dt3.Rows[0]["IsPrintOneTag"].ToString();
                                IsPack = dt3.Rows[0]["IsPrintPackList"].ToString();
                                IsPaint = dt3.Rows[0]["IsPlating"].ToString();
                                PartName = dt3.Rows[0]["ProductName"].ToString();
                                MaxCount = Convert.ToInt32(dt3.Rows[0]["PackCount"].ToString());
                            }

                            #endregion

                            #region 打印单个标签

                            if (IsOne == "1")
                            {
                                filename = System.AppDomain.CurrentDomain.BaseDirectory + "单个条码.grf";
                                DataTable headTable = new DataTable();
                                headTable.Columns.Add("PrintTime");
                                headTable.Columns.Add("PartNo");
                                headTable.Columns.Add("PartName");
                                headTable.Columns.Add("OneBarCode");
                                headTable.Columns.Add("BarCode");
                                DataRow row = headTable.NewRow();
                                row["PrintTime"] = GetDateTime().ToString("yyyy/MM/dd HH:mm:ss");
                                row["PartNo"] = partNo;
                                row["PartName"] = PartName;
                                row["OneBarCode"] = NewOneCode;
                                row["BarCode"] = newcode;

                                DataTable dt4 = plbll.SearchInfo(partNo, stationID);
                                if (dt4 != null && dt4.Rows.Count > 0)
                                {
                                    printName = "Printer" + dt4.Rows[0]["PrinterNo"].ToString();
                                }

                                string 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 判断是否满箱,满箱打印箱单  暂时屏蔽

                            //DataTable dt5 = bll.SearchBoxIsNull(partNo, stationID, Program.tableName,"正常件");
                            //if (dt5 != null && dt5.Rows.Count > 0)
                            //{
                            //    CurrentCount = Convert.ToInt32(dt5.Rows[0]["SumCount"].ToString());
                            //}

                            //if (CurrentCount >= MaxCount)
                            //{
                            //    filename = System.AppDomain.CurrentDomain.BaseDirectory + "装箱单.grf";
                            //    DataTable headTable = new DataTable();
                            //    headTable.Columns.Add("BoxNo");
                            //    headTable.Columns.Add("PartName");
                            //    headTable.Columns.Add("PartNo");
                            //    headTable.Columns.Add("BatchNo");
                            //    headTable.Columns.Add("PackCount");
                            //    headTable.Columns.Add("QLevel");
                            //    DataRow row = headTable.NewRow();

                            //    row["BatchNo"] = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2);

                            //    #region 查询当前批次装箱单

                            //    DataTable dt6 = boxbll.SeachInfoByBox(partNo, Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2));
                            //    if (dt6 != null && dt6.Rows.Count > 0)
                            //    {
                            //        row["BoxNo"] =
                            //            dt6.Rows[0]["BoxNo"].ToString().Substring(0,
                            //                dt6.Rows[0]["BoxNo"].ToString().Length - 6) +
                            //            (Convert.ToInt32(dt6.Rows[0]["BoxNo"].ToString()
                            //                 .Substring(dt6.Rows[0]["BoxNo"].ToString().Length - 6, 6)) + 1)
                            //            .ToString().PadLeft(6, '0');
                            //    }
                            //    else
                            //    {
                            //        row["BoxNo"] =
                            //            part[0].ToString().Trim() + "." +
                            //            Program.ProductDate.Substring(2, 2) +
                            //            Program.ProductDate.Substring(5, 2) +
                            //            Program.ProductDate.Substring(8, 2) + "." + "000001";
                            //    }

                            //    #endregion

                            //    row["PartNo"] = partNo;
                            //    row["PartName"] = PartName;
                            //    row["PackCount"] = MaxCount.ToString() + "  EA";
                            //    row["QLevel"] = QLevel;

                            //    #region 更新barCode表中BoxNo的绑定关系

                            //    bll.UpdateBoxNo(Program.tableName, row["BoxNo"].ToString(),
                            //        partNo);

                            //    #endregion

                            //    #region 保存箱单记录

                            //    boxmd.ID = Guid.NewGuid().ToString();
                            //    boxmd.BoxNo = row["BoxNo"].ToString();
                            //    boxmd.IsFlag = 0;
                            //    boxmd.BoxCount = MaxCount;

                            //    boxbll.AddInfo(boxmd);

                            //    #endregion

                            //    #region 打印箱单

                            //    string 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
                            //}

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

        private static bool IsNumeric(string str)
        {
            System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[0-9]\d*$");
            return reg1.IsMatch(str);
        }

        private static string getStationID(string stationName)
        {
            try
            {
                string id = "";
                StationBLL bll=new StationBLL();

                DataTable dt = bll.SearchInfoByNo(stationName);
                if (dt != null && dt.Rows.Count > 0)
                {
                    id = dt.Rows[0]["StationID"].ToString();
                }
                else
                {
                    id = "";
                }

                return id;

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

        /// <summary>
        /// 补打条码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label22_Click(object sender, EventArgs e)
        {
            string code = "", filename = "", printName = "";
            BarCodeModel md = new BarCodeModel();
            BarCodeBLL bll = new BarCodeBLL();
            ProductBLL pbll = new ProductBLL();
            PlasticBLL plbll = new PlasticBLL();
            try
            {
                if (glacialList1.SelectedItems.Count == 0)
                {
                    MessageBox.Show("请选择要补打的条码!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    GlacialComponents.Controls.GLItem gv;
                    gv = glacialList1.SelectedItems[0] as GlacialComponents.Controls.GLItem;
                    code = gv.Text;

                    DataTable dt = bll.SearchInfoByBarCodeNew(code, Program.tableName);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        md.ID = Guid.NewGuid().ToString();
                        md.BarCode = code;
                        md.StationID = dt.Rows[0]["StationID"].ToString();
                        md.StockNo = dt.Rows[0]["StockNo"].ToString();
                        md.OneBarCode = dt.Rows[0]["OneBarCode"].ToString();
                        //md.BoxNo = dt.Rows[0]["BoxNo"].ToString();
                        md.PartNo = dt.Rows[0]["PartNo"].ToString();

                        md.PrintType = 2;

                        DataTable pdt = pbll.SearchIsImportByPartNo(md.PartNo);
                        if (pdt != null && pdt.Rows.Count > 0)
                        {
                            if (pdt.Rows[0]["isImport"].ToString() == "1")
                            {
                                md.Import = "国产料Kingfa";
                            }
                            else
                            {
                                md.Import = "";
                            }
                        }
                    }

                    bll.Add_Info_New(md, Program.tableName);
                    glacialList1.SelectedItems.Clear();
                    initBarCode();

                    #region 打印条码

                    filename = System.AppDomain.CurrentDomain.BaseDirectory + "单个条码.grf";
                    DataTable headTable = new DataTable();
                    headTable.Columns.Add("PrintTime");
                    headTable.Columns.Add("PartNo");
                    headTable.Columns.Add("PartName");
                    headTable.Columns.Add("OneBarCode");
                    headTable.Columns.Add("BarCode");
                    DataRow row = headTable.NewRow();
                    row["PrintTime"] = GetDateTime().ToString("yyyy/MM/dd HH:mm:ss");
                    row["PartNo"] = md.PartNo;

                    DataTable dt2 = pbll.SearchInfoByPartNo(md.PartNo);
                    if (dt2 != null && dt2.Rows.Count > 0)
                    {
                        row["PartName"] = dt2.Rows[0]["ProductName"].ToString();
                    }
                    else
                    {
                        row["PartName"] = "";
                    }

                    row["OneBarCode"] = md.OneBarCode;
                    row["BarCode"] = md.BarCode;

                    DataTable dt4 = plbll.SearchInfo(md.PartNo, md.StationID);
                    if (dt4 != null && dt4.Rows.Count > 0)
                    {
                        printName = "Printer" + dt4.Rows[0]["PrinterNo"].ToString();
                    }

                    string 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
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        /// <summary>
        /// 补打箱单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label16_Click(object sender, EventArgs e)
        {
            panel44.Visible = true;
            textBox3.Focus();
        }

        /// <summary>
        /// 删除条码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label15_Click(object sender, EventArgs e)
        {
            BarCodeBLL bll = new BarCodeBLL();
            BarCodeModel md = new BarCodeModel();

            try
            {
                if (glacialList1.SelectedItems.Count == 0)
                {
                    MessageBox.Show("请选择要删除的条码!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    GlacialComponents.Controls.GLItem gv;
                    gv = glacialList1.SelectedItems[0] as GlacialComponents.Controls.GLItem;
                    md.BarCode = gv.Text;

                    bll.DelBarCode_New(md,Program.tableName);
                    initBarCode();
                }
            }
            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
            {
                InjectionBoxBLL boxbll=new InjectionBoxBLL();
                InjectionBoxModel boxmd=new InjectionBoxModel();
                BarCodeBLL bll=new BarCodeBLL();
                ProductBLL pbll=new ProductBLL();
                PlasticBLL plbll=new PlasticBLL();
                string filename = "",printName="";
                 
                #region 验证输入合法性

                if (textBox3.Text.Trim() == "")
                {
                    MessageBox.Show("请输入箱单号", "提示", MessageBoxButtons.OK);
                    return;
                }

                DataTable dt = boxbll.SearchBox(textBox3.Text.Trim());
                if (dt != null && dt.Rows.Count > 0)
                {
                    DataTable dt1 = bll.SearchCountByBox(textBox3.Text.Trim(), Program.tableName);
                    if (dt1 != null && dt1.Rows.Count > 0)
                    {
                        #region 查找该箱单内容

                        filename = System.AppDomain.CurrentDomain.BaseDirectory + "装箱单.grf";
                        DataTable headTable = new DataTable();
                        headTable.Columns.Add("BoxNo");
                        headTable.Columns.Add("PartName");
                        headTable.Columns.Add("PartNo");
                        headTable.Columns.Add("BatchNo");
                        headTable.Columns.Add("PackCount");
                        headTable.Columns.Add("QLevel");
                        DataRow row = headTable.NewRow();

                        string[] box = textBox3.Text.Trim().Split('.');
                        row["BoxNo"] = textBox3.Text.Trim();
                        row["PartNo"] = box[0].Trim();

                        DataTable dt2 = pbll.SearchInfoByPartNo(row["PartNo"].ToString());
                        if (dt2 != null && dt2.Rows.Count > 0)
                        {
                            row["PartName"] = dt2.Rows[0]["ProductName"].ToString();
                        }

                        row["BatchNo"] = box[1].Trim();
                        row["PackCount"] = dt1.Rows[0]["SumCount"].ToString();
                        row["QLevel"] = dt2.Rows[0]["QLevel"].ToString();

                        #endregion

                        #region 保存箱单

                        boxmd.ID = Guid.NewGuid().ToString();
                        boxmd.BoxNo = textBox3.Text.Trim();
                        boxmd.IsFlag = 1;
                        boxmd.BoxCount = Convert.ToInt32(dt1.Rows[0]["SumCount"].ToString());

                        boxbll.AddInfo(boxmd);

                        #endregion

                        #region 打印箱单

                        #region 查询打印机名称

                        DataTable dt3 = plbll.SearchInfo(row["PartNo"].ToString(), Program.station);
                        if (dt3 != null && dt3.Rows.Count > 0)
                        {
                            printName = "Printer" + dt3.Rows[0]["PrinterNo"].ToString();
                        }

                        #endregion

                        string 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

                        panel44.Visible = false;
                        textBox3.Text = "";
                    }
                }
                else
                {
                    MessageBox.Show("此箱单不存在,请重新输入", "提示", MessageBoxButtons.OK);
                    textBox3.Focus();
                    return;
                }

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

        private void button2_Click(object sender, EventArgs e)
        {
            panel44.Visible = false;
            textBox3.Text = "";
            textBox5.Text = "";
            
        }

        /// <summary>
        /// 下一计划
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label14_Click(object sender, EventArgs e)
        {
            try
            {
                InjectionPlanBLL planbll=new InjectionPlanBLL();
                
                #region 查询有无下一计划

                DataTable dt = planbll.NextSearchInfoByName(Program.station);
                if (dt != null && dt.Rows.Count > 0)
                {
                    planID = dt.Rows[0]["InjectionPlanID"].ToString();
                    productID = dt.Rows[0]["ProductID"].ToString();
                    nextproductID = dt.Rows[1]["ProductID"].ToString();
                    panel45.Visible = true;
                }
                else
                {
                    MessageBox.Show("暂无下一计划,请联系计划员!", "提示", MessageBoxButtons.OK);
                    return;
                }

                #endregion
            }
            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
            {
                ModelInfoBLL bll=new ModelInfoBLL();
                ModelProductBLL mbll=new ModelProductBLL();
                InjectionPlanBLL ibll=new InjectionPlanBLL();
                InjectionPlanModel md=new InjectionPlanModel();

                #region 验证数据有效性

                if (textBox4.Text.Trim() == "")
                {
                    MessageBox.Show("请扫描模具条码!", "提示", MessageBoxButtons.OK);
                    textBox4.Focus();
                    return;
                }

                #endregion

                #region 判断模具编号是否存在

                DataTable dt = bll.SearchInfo(textBox4.Text.Trim());
                if (dt != null && dt.Rows.Count > 0)
                {
                    #region 校验模具和下一计划是否匹配

                    DataTable dt1 = mbll.SearchInfo(dt.Rows[0]["ID"].ToString(), nextPlanID);
                    if (dt1 != null && dt1.Rows.Count > 0)
                    {
                        #region 更新上一计划为完成

                        #region 获取工位编号

                        StationBLL sbll = new StationBLL();
                        DataTable sdt = sbll.SearchInfoByNo(Program.station);
                        if (sdt != null && sdt.Rows.Count > 0)
                        {
                            md.StationID = sdt.Rows[0]["StationID"].ToString();
                        }

                        #endregion

                        ibll.UpdateFinish(md);

                        #endregion

                        panel45.Visible = false;
                        textBox4.Text = "";

                    }
                    else
                    {
                        MessageBox.Show("模具和计划不匹配!", "提示", MessageBoxButtons.OK);
                        textBox4.Focus();
                        return;
                    }

                    #endregion
                }
                else
                {
                    MessageBox.Show("模具条码不存在!", "提示", MessageBoxButtons.OK);
                    textBox4.Focus();
                    return;
                }

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

        private void button3_Click(object sender, EventArgs e)
        {
            panel45.Visible = false;
            textBox4.Text = "";
        }

        /// <summary>
        /// 暂停打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label13_Click(object sender, EventArgs e)
        {
            try
            {
                if (label13.Text == "暂停打印")
                {
                    DialogResult result = MessageBox.Show("确认暂停打印?", "提示", MessageBoxButtons.OKCancel,
                        MessageBoxIcon.Information);
                    if (result == DialogResult.OK)
                    {
                        opcServer.OPCGroups.RemoveAll();
                        opcServer.Disconnect();
                        label13.Text = "开始打印";
                        label13.BackColor = System.Drawing.Color.Gray;
                        timer1.Enabled = false;
                    }
                    else
                    {
                        return;
                    }
                }

                else
                {
                    DialogResult result = MessageBox.Show("确认开始打印?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    if (result == DialogResult.OK)
                    {
                        #region 连接PLC

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

                                #region 创建组

                                opcGroups = opcServer.OPCGroups;
                                opcGroup1 = opcGroups.Add("Mould");
                                SetGroupProperty(opcGroup1, 500);
                                opcGroup2 = opcGroups.Add("Break");
                                SetGroupProperty(opcGroup2, 500);

                                #endregion

                                #region 创建项

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

                                PLCMouldBLL bll = new PLCMouldBLL();
                                PLCBreakBLL bbll = new PLCBreakBLL();

                                DataTable dt = bll.SearchMould(Program.station);
                                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]["Address"].ToString(), i);
                                    }
                                }

                                Thread.Sleep(200);

                                opcItems2 = opcGroup2.OPCItems;
                                opcItems2.DefaultIsActive = true;
                                DataTable dt1 = bbll.SearchBreak();

                                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]["Address"].ToString(), i);
                                    }
                                }

                                Thread.Sleep(200);

                                opcGroup1.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(opcGroup1_DataChange);


                                #endregion
                            }
                            else
                            {
                                MessageBox.Show("连接到OPC服务器失败!", "提示", MessageBoxButtons.OK);
                                Connected = false;
                                LogHelper.WriteLog("连接到OPC服务器失败!");
                                return;
                            }
                        }
                        else
                        {
                            MessageBox.Show("创建OPC服务失败!", "提示", MessageBoxButtons.OK);
                            Connected = false;
                            LogHelper.WriteLog("创建OPC服务失败!");
                            return;
                        }

                        #endregion

                        label13.Text = "暂停打印";
                        label13.BackColor = System.Drawing.Color.DeepSkyBlue;
                        timer1.Enabled = true;
                    }
                    else
                    {
                        return;
                    }
                }
                
            }
        
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        /// <summary>
        /// 质量录入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label9_Click(object sender, EventArgs e)
        {
            Form fr = new FrmQuality();
            fr.Show();
        }

        /// <summary>
        /// 停机录入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label10_Click(object sender, EventArgs e)
        {
            Form fr = new FrmDown();
            fr.Show();
        }

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string _code_meca = "";
            try
            {
                Thread.Sleep(1500);
                char[] buffer = new char[serialPort1.BytesToRead];
                serialPort1.Read(buffer, 0, serialPort1.BytesToRead);
                for (int i = 0; i < buffer.Length; i++)
                {
                    _code_meca = _code_meca + buffer[i];
                }
                string aa = _code_meca;

                var result1 = System.Text.RegularExpressions.Regex.Replace(aa, @"\s*\n\s*", ",");
                result1 = System.Text.RegularExpressions.Regex.Replace(aa, @"\s*\f\s*", ",");
                result1 = System.Text.RegularExpressions.Regex.Replace(aa, @"\s*\r\s*", ",");
                result1 = result1.Remove(result1.LastIndexOf(","), 1);
                result1 = result1.Remove(result1.LastIndexOf("g"), 1);
                int idxStart = result1.LastIndexOf(" ");
                string value = result1.Substring(idxStart, result1.Length - idxStart).Trim();
                string[] b = value.Split('.');
                string c = b[0];
                string d = b[1];
                int chengzhong = Convert.ToInt32(c);
                int chengzhong1 = Convert.ToInt32(d);
                if (chengzhong1 >= 5)
                {
                    chengzhong = chengzhong + 1;     //重量
                }


                InjectionPlanBLL bll = new InjectionPlanBLL();
                BarCodeBLL brbll = new BarCodeBLL();
                BarCodeModel md = new BarCodeModel();
                ProductBLL productBll = new ProductBLL();
                PlasticBLL pbll = new PlasticBLL();
                InjectionBoxBLL boxbll = new InjectionBoxBLL();
                InjectionBoxModel boxmd = new InjectionBoxModel();
                DataTable dt2 = null;
                string code = "", OneCode = "";
                string newcode = "", newcode1 = "", NewOneCode = "", NewOneCode1 = "";
                string IsPack = "", IsOne = "", QLevel = "", IsPaint = "", PartName = "";
                string filename = "", printName = "";
                int MaxCount = 0, CurrentCount = 0;
                
                #region 查找当前计划

                DataTable dt = bll.SearchInfoByName(Program.station);
                if (dt != null && dt.Rows.Count > 0)
                {
                    planID = dt.Rows[0]["InjectionPlanID"].ToString();
                    string[] partNo = dt.Rows[0]["PartNo"].ToString().Split(',');
                    string[] stockNo = dt.Rows[0]["StockNo"].ToString().Split(',');
                    string[] ProductNature = dt.Rows[0]["ProductNature"].ToString().Split(',');

                    #region 判断有几个零件号

                    for (int j = 0; j < partNo.Length; j++)
                    {
                        dt2 = brbll.SearchInfoByPartNo(partNo[j].ToString().Trim());
                        if (dt2 != null && dt2.Rows.Count > 0)
                        {
                            code = dt2.Rows[0]["BarCode"].ToString().Trim();
                            newcode = code.Substring(0, code.Length - 4) +
                                      (Convert.ToInt32(code.Substring(code.Length - 4, 4)) + 1).ToString()
                                      .PadLeft(4, '0');
                            OneCode = dt2.Rows[0]["OneBarCode"].ToString().Trim();
                            NewOneCode = OneCode.Substring(0, OneCode.Length - 4) + (Convert.ToInt32(OneCode.Substring(OneCode.Length - 4, 4)) + 1).ToString().PadLeft(4, '0');
                        }
                        else
                        {
                            newcode = partNo[j].ToString().Trim() + "." + Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2) + "." + "0001";
                            NewOneCode = stockNo[j].ToString().Trim() + Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2) + "0001";
                        }

                        #region 插入数据tb_barCode

                        md.ID = Guid.NewGuid().ToString();
                        md.StationID = dt.Rows[0]["StationID"].ToString();
                        md.OneBarCode = NewOneCode;
                        md.BarCode = newcode;
                        md.StockNo = stockNo[j].ToString().Trim();
                        md.PartNo = partNo[j].ToString().Trim();
                        md.PrintType = 0;
                        md.PlanID = planID;
                        md.ProductNature = ProductNature[j].ToString().Trim();

                        DataTable pdt = productBll.SearchIsImportByPartNo(partNo[j].ToString());
                        if (pdt != null && pdt.Rows.Count > 0)
                        {
                            if (pdt.Rows[0]["isImport"].ToString() == "1")
                            {
                                md.Import = "国产料Kingfa";
                            }
                            else
                            {
                                md.Import = "";
                            }
                        }

                        brbll.Add_Info_New(md, Program.tableName);

                        #endregion

                        #region 打印条码,判断是否打印单个条码

                        DataTable dt3 = productBll.SearchInfoByPartNo(partNo[j].ToString().Trim());
                        if (dt3 != null && dt3.Rows.Count > 0)
                        {
                            QLevel = dt3.Rows[0]["QLevel"].ToString();
                            IsOne = dt3.Rows[0]["IsPrintOneTag"].ToString();
                            IsPack = dt3.Rows[0]["IsPrintPackList"].ToString();
                            IsPaint = dt3.Rows[0]["IsPlating"].ToString();
                            PartName = dt3.Rows[0]["ProductName"].ToString();
                            MaxCount = Convert.ToInt32(dt3.Rows[0]["PackCount"].ToString());
                        }

                        #region 打印单个标签

                        if (IsOne == "1")
                        {
                            filename = System.AppDomain.CurrentDomain.BaseDirectory + "单个条码.grf";
                            DataTable headTable = new DataTable();
                            headTable.Columns.Add("PrintTime");
                            headTable.Columns.Add("PartNo");
                            headTable.Columns.Add("PartName");
                            headTable.Columns.Add("OneBarCode");
                            headTable.Columns.Add("BarCode");
                            DataRow row = headTable.NewRow();
                            row["PrintTime"] = GetDateTime().ToString("yyyy/MM/dd HH:mm:ss");
                            row["PartNo"] = partNo[j].ToString().Trim();
                            row["PartName"] = PartName;
                            row["OneBarCode"] = NewOneCode;
                            row["BarCode"] = newcode;

                            DataTable dt4 = pbll.SearchInfo(partNo[j].ToString().Trim(),
                                dt.Rows[0]["StationID"].ToString());
                            if (dt4 != null && dt4.Rows.Count > 0)
                            {
                                printName = "Printer" + dt4.Rows[0]["PrinterNo"].ToString();
                            }

                            string 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 暂时屏蔽打印装箱单
                        //DataTable dt5 = brbll.SearchBoxIsNull(partNo[j].ToString().Trim(),
                        //                        dt.Rows[0]["StationID"].ToString(), Program.tableName, ProductNature[j].ToString().Trim());

                        //if (dt5 != null && dt5.Rows.Count > 0)
                        //{
                        //    CurrentCount = Convert.ToInt32(dt5.Rows[0]["SumCount"].ToString());
                        //}

                        //if (CurrentCount >= MaxCount)
                        //{
                        //    #region 判断是否满箱,满箱打印箱单

                        //    DialogResult result = MessageBox.Show("是否打印装箱单?", "提示", MessageBoxButtons.OKCancel,
                        //        MessageBoxIcon.Information);
                        //    if (result == DialogResult.OK)
                        //    {
                        //        filename = System.AppDomain.CurrentDomain.BaseDirectory + "装箱单.grf";
                        //        DataTable headTable = new DataTable();
                        //        headTable.Columns.Add("BoxNo");
                        //        headTable.Columns.Add("PartName");
                        //        headTable.Columns.Add("PartNo");
                        //        headTable.Columns.Add("BatchNo");
                        //        headTable.Columns.Add("PackCount");
                        //        headTable.Columns.Add("QLevel");
                        //        DataRow row = headTable.NewRow();

                        //        row["BatchNo"] = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2);

                        //        #region 查询当前批次装箱单

                        //        DataTable dt6 = boxbll.SeachInfoByBox(partNo[j].ToString().Trim(), Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2));
                        //        if (dt6 != null && dt6.Rows.Count > 0)
                        //        {
                        //            row["BoxNo"] =
                        //                dt6.Rows[0]["BoxNo"].ToString().Substring(0,
                        //                    dt6.Rows[0]["BoxNo"].ToString().Length - 6) +
                        //                (Convert.ToInt32(dt6.Rows[0]["BoxNo"].ToString()
                        //                     .Substring(dt6.Rows[0]["BoxNo"].ToString().Length - 6, 6)) + 1)
                        //                .ToString().PadLeft(6, '0');
                        //        }
                        //        else
                        //        {
                        //            row["BoxNo"] =
                        //                partNo[j].ToString().Trim() + "." +
                        //                Program.ProductDate.Substring(2, 2) +
                        //                Program.ProductDate.Substring(5, 2) +
                        //                Program.ProductDate.Substring(8, 2) + "." + "000001";
                        //        }

                        //        #endregion

                        //        row["PartNo"] = partNo[j].ToString().Trim();
                        //        row["PartName"] = PartName;
                        //        row["PackCount"] = MaxCount.ToString() + "  EA";
                        //        row["QLevel"] = QLevel;

                        //        #region 更新barCode表中BoxNo的绑定关系

                        //        brbll.UpdateBoxNo(Program.tableName, row["BoxNo"].ToString(),
                        //            partNo[j].ToString().Trim());

                        //        #endregion

                        //        #region 保存箱单记录

                        //        boxmd.ID = Guid.NewGuid().ToString();
                        //        boxmd.BoxNo = row["BoxNo"].ToString();
                        //        boxmd.IsFlag = 0;
                        //        boxmd.BoxCount = MaxCount;

                        //        boxbll.AddInfo(boxmd);

                        //        #endregion

                        //        #region 打印箱单

                        //        string 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
                        //    }
                        //    else
                        //    {

                        //    }

                        //    #endregion
                        //} 
                        #endregion
                        #endregion

                        initBarCode();
                    }

                    #endregion
                }

                #endregion

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

        /// <summary>
        /// 校验箱单和塑件零件号是否一致
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox5_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    #region 判断数据有效性
                    if (textBox3.Text.Trim() == "")
                    {
                        MessageBox.Show("请扫描箱单!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        textBox3.Focus();
                        return;
                    }
                    if (textBox5.Text.Trim() == "")
                    {
                        MessageBox.Show("请扫描塑件条码!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        textBox5.Focus();
                        return;
                    }

                    if (textBox3.Text.Trim().Contains('.') == false)
                    {
                        MessageBox.Show("箱单有误,请重新扫描!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        textBox3.Focus();
                        return;
                    }
                    #endregion

                    string[] boxNo = textBox3.Text.Trim().Split('.');
                    string bpartNo = boxNo[0].Trim();
                    
                    string partNo = "";

                    ProductBLL bll = new ProductBLL();


                    if (textBox5.Text.Contains('.'))
                    {
                        string[] part = textBox5.Text.Trim().Split('.');
                        partNo = part[0];
                    }
                    else
                    {
                        DataTable dt = bll.SearchInfoByStock(textBox5.Text.Trim().Substring(0, 10));
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            partNo = dt.Rows[0]["PartNo"].ToString();
                        }
                        else
                        {
                            MessageBox.Show("塑件条码有误,请重新扫描!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            textBox5.Focus();
                            return;
                        }
                    }

                    if (bpartNo == partNo)
                    {
                        panel44.Visible = false;
                        textBox3.Text = "";
                        textBox5.Text = "";
                    }
                    else
                    {
                        MessageBox.Show("箱单信息和塑件信息不一致,请核对!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        textBox5.Select();
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }
    }
}