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 System.Net.Mime;
using System.Net.NetworkInformation;
using gregn6Lib;
using MESClassLibrary;
using MESClassLibrary.EFModel;

namespace InjectionPC
{
    public partial class FrmMain2411 : Form
    {
        #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;
        private BasicBLL1 _basicBLL1 = new BasicBLL1();
        private UniqueBll _uniqueBll = new UniqueBll();
        private bool _isPrintPackage = true;
        private BarCodeBLL _barCodeBLL = new BarCodeBLL();
        private InjectionBoxBLL _injectionBoxBLL = new InjectionBoxBLL();
        private PLCMouldBLL _PLCbll = new PLCMouldBLL();
        private PLCBreakBLL _bbll = new PLCBreakBLL();
        private DataTable  tb_Plastic = new DataTable();
        private string _currentStationID = string.Empty;
        private const string _leftType = "0"; //模具1
        private const string _rightType = "1";//模具2
        private DateTime _loginTime = DateTime.Now;
       
        private WmsBLL _wmsBll = new WmsBLL(); 
        //零件用的打印机编号  <零件号+工位ID,打印机编号>
        private Dictionary<string, string> _printNameDict = new Dictionary<string, string>();
        private PlasticBLL _plasticBLL = new PlasticBLL();
        private int _plcRate = 100; //500
        #endregion

        public FrmMain2411()
        {
            InitializeComponent();
            this.Size = new Size(1280, 920);
        }

        public string planID = "", productID = "", nextPlanID = "", nextproductID = "",aa="";

        public static int ID = 0;
        DateTime lastTime = DateTime.Now;
        //public string Conn = ConfigurationManager.ConnectionStrings["SqlConnStringWeight"].ConnectionString;

        bool status = false;

        private static int InterVal_Seconds = 0;

        private void FrmMain_Load(object sender, EventArgs e)
        {
            try
            {
                _currentStationID = getStationID(Program.station);
                tb_Plastic = GetPlastic();
                Control.CheckForIllegalCrossThreadCalls = false;
                //this.WindowState = FormWindowState.Maximized;
                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;     //用户
                //InterVal_Seconds = GetSeconds(label6.Text);
                GetClass();
                comboBox1.Text = "A班";          //班次
                Program.cc = comboBox1.Text;
                initProduct();
                //textBox1.Text = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) +
                //                Program.ProductDate.Substring(8, 2);     //批次
                textBox1.Text = GetBatch(true);
                initBarCode();
                label23.Enabled = false;
                label23.BackColor = System.Drawing.Color.Gray;

                DataTable plasticTable = GetPlastic();
                foreach(DataRow dr in plasticTable.Rows)
                {
                    string key = dr["PartNo"].ToString() + dr["StationID"].ToString();
                    if (_printNameDict.Keys.Contains(key) == false)
                    {
                        _printNameDict.Add(key, dr["PrinterNo"].ToString());
                    }
                }


                Ping p1 = new Ping();

                PingReply reply = p1.Send("10.60.101.60"); //发送主机名或Ip地址
                StringBuilder sbuilder;
                if (reply.Status == IPStatus.Success)
                {
                    status = true;
                    label2.BackColor = Color.LightGray;
                }
                else
                {
                    status = false;
                    label2.BackColor = Color.Red;
                }

                //comBoxSizeL.DataSource = _basicBLL1.GetPackageSize();
                //comBoxSizeL.DisplayMember = "describe";
                //comBoxSizeL.ValueMember = "Count";
                //comBoxSizeR.DataSource = _basicBLL1.GetPackageSize();
                //comBoxSizeR.DisplayMember = "describe";
                //comBoxSizeR.ValueMember = "Count";

                string devRate = ConfigurationManager.AppSettings["DevRate"];
                if (!string.IsNullOrEmpty(devRate))
                {
                    int i = 0;
                    if(int.TryParse(devRate,out i) == true)
                    {
                        if(i>0)
                        {
                            _plcRate = i;
                        }
                    }
                }

                comboBox2.MouseWheel += new MouseEventHandler(comboBox2_MouseWheel);

                #region 获取当前生产信息

                initPlan();

                #endregion

                #region 连接PLC 

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

                            #region 创建组

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

                            #endregion

                            #region 创建项

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

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

                            DataTable PLCdt = _PLCbll.SearchMould(Program.station);
                            if (PLCdt != null && PLCdt.Rows.Count > 0)
                            {
                                opcItemm1 = new OPCItem[PLCdt.Rows.Count];
                                for (int i = 0; i < PLCdt.Rows.Count; i++)
                                {
                                    opcItemm1[i] = opcItems1.AddItem(PLCdt.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;
                    }
                }
                catch(Exception ex)
                {
                    MessageBox.Show("创建OPC服务失败!", "提示", MessageBoxButtons.OK);
                    Connected = false;
                    LogHelper.WriteLog("创建OPC服务失败!");
                    LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                    return;
                }
               

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

        private DataTable GetPlastic()
        { 
            return _plasticBLL.SearchAllInfo(_currentStationID);
        }

        private void initPlan()
        {
            try
            {
                InjectionPlanBLL bll = new InjectionPlanBLL();
                ProductBLL productBll = new ProductBLL();
                DataTable dt = bll.SearchInfoByName(Program.station);
                if (dt != null && dt.Rows.Count > 0)
                {
                    planID = dt.Rows[0]["InjectionPlanID"].ToString();
                    aa = dt.Rows[0]["PartNo"].ToString();
                    label17.Text = dt.Rows[0]["PlanCount"].ToString();

                    string actualTime = dt.Rows[0]["ActualTime"].ToString();
                    if (string.IsNullOrEmpty(actualTime))
                    {
                        InjectionPlanBLL ibll = new InjectionPlanBLL();
                        ibll.UpdatePlanStartTime(planID);
                    }

                    DataTable dt2 = bll.SearchQty(planID);
                    if (dt2 != null && dt2.Rows.Count > 0)
                    {
                        label27.Text = dt2.Rows[0]["ProductCount"].ToString();
                    }
                    else
                    {
                        label27.Text = "0";
                    }

                    string[] partNo = dt.Rows[0]["PartNo"].ToString().Split(',');

                    label12.Text = "当前生产计划为:";
                     
                    for (int i = 0; i < partNo.Length; i++)
                    {
                        DataTable sdt = productBll.SearchInfoByPartNo(partNo[i].ToString().Trim());
                        if (sdt != null && sdt.Rows.Count > 0)
                        {
                            label12.Text += "零件号" + partNo[i].ToString().Trim() + ",零件名称" + sdt.Rows[0]["ProductName"].ToString() + ";";
                        }
                    }
                }
                else
                {
                    label12.Text = "暂无生产计划";
                    label17.Text = "0";
                    label27.Text = "0";
                }

                if (Convert.ToDouble(label17.Text) < Convert.ToDouble(label27.Text))
                {
                    label27.BackColor = Color.Red;
                }
                else
                {
                    label27.BackColor = Color.DeepSkyBlue;
                }
                
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(),MethodBase.GetCurrentMethod());
            }
        }

        void comboBox2_MouseWheel(object sender, MouseEventArgs e)
        {
            HandledMouseEventArgs h = e as HandledMouseEventArgs;
            if (h != null)
            {
                h.Handled = true;
            }
        }

        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= _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="",IsSame="",IsSupply="";
                string ManufacturerName = "";
                string filename = "", printName = "", printBoxName="";
                int MaxCount = 0, CurrentCount = 0;

                
                if (status == false)
                {

                    MessageBox.Show("连接服务器失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                for (int i = 1; i <= NumItems; i++)
                {
                    if ((ItemValues!=null &&  ItemValues.GetValue(i).ToString() == "True") || IsTest ==true)
                    {
                        //LogSysBLL.AddInfo("true" + label6.Text, MethodBase.GetCurrentMethod());

                        try
                        {
                            GetClass();

                            #region 增加时间差判定

                            TimeSpan span = DateTime.Now - lastTime;
                            if (span.TotalSeconds < Convert.ToDouble(ConfigurationManager.AppSettings["InterValT"]))
                            {
                                return;
                            }
                            _bbll.SavePlcReceive(Program.station, TransactionID, NumItems, aa, planID, "2411");
                            #endregion

                            //comboBox1.Text = "A班";         //班次
                            //textBox1.Text = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) +
                            //                Program.ProductDate.Substring(8, 2);     //批次
                            textBox1.Text = GetBatch(true);
                        }
                        catch(Exception ex)
                        {
                            throw new Exception(Program.station + "p383" + ex.Message);
                        }
                       
                        #region 查找当前计划

                        DataTable dt = bll.SearchInfoByName(Program.station);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                           
                            if (aa != dt.Rows[0]["PartNo"].ToString())
                            {
                               
                                DialogResult result=MessageBox.Show("计划有变更,请确认!", "提示", MessageBoxButtons.OKCancel,
                                        MessageBoxIcon.Information);
                                if (result == DialogResult.OK)
                                {
                                    try
                                    {
                                        planID = dt.Rows[0]["InjectionPlanID"].ToString();
                                        string[] partNo = dt.Rows[0]["PartNo"].ToString().Split(',');
                                        //string[] stockNo = dt.Rows[0]["StockNo"].ToString().Split(',');
                                        string[] stockNo = new string[partNo.Length];
                                        string ProductNature = dt.Rows[0]["ProductNature"].ToString();
                                        aa = dt.Rows[0]["PartNo"].ToString();

                                        //ManufacturerName = dt.Rows[0]["ManufacturerName"].ToString();
                                        DataTable dtM = productBll.SearchInfoByPartNo(partNo[0]);
                                        if (dtM != null && dtM.Rows.Count > 0)
                                        {
                                            ManufacturerName = dtM.Rows[0]["ManufacturerName"].ToString();
                                        }

                                        #region 判断有几个零件号
                                        string mould = "0";
                                        for (int j = 0; j < partNo.Length; j++)
                                        {
                                            #region 根据零件号查找存货代码

                                            DataTable sdt = productBll.SearchInfoByPartNo(partNo[j].ToString().Trim());
                                            if (sdt != null && sdt.Rows.Count > 0)
                                            {
                                                stockNo[j] = sdt.Rows[0]["StockNo"].ToString();
                                                IsSame = sdt.Rows[0]["IsSame"].ToString();
                                            }
                                            else
                                            {
                                                stockNo[j] = "";
                                            }

                                            #endregion

                                            #region 获取零件属性

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

                                            #endregion

                                            if (IsSame == "1")//一模两压相同的
                                            {
                                                for (int k = 0; k < 2; k++)
                                                {
                                                    #region 非直供件打印

                                                    if (IsSupply != "1")
                                                    {
                                                        if (ManufacturerName.Contains("蔚来"))
                                                        {
                                                            GetSjBarCode(stockNo[j].ToString().Trim(), partNo[j].ToString().Trim(), true, mould, PartName, ref NewOneCode, ref newcode);
                                                        }
                                                        else
                                                        {
                                                            GetSjBarCode(stockNo[j].ToString().Trim(), partNo[j].ToString().Trim(), true, mould, PartName, ref NewOneCode, ref newcode);

                                                        }
                                                    }

                                                    #endregion

                                                    #region 直供件打印

                                                    if (IsSupply == "1")
                                                    {

                                                        GetSupplyCode(stockNo[j].ToString().Trim(), partNo[j].ToString().Trim(), QLevel, true, mould, PartName, ref NewOneCode, ref newcode);
                                                    }

                                                    #endregion

                                                    #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;
                                                    md.Des1 = PartName;
                                                   
                                                    string errMsg = string.Empty;
                                                    bool saveRst = SaveInfo(md, true, mould, false, ref errMsg);
                                                    if (saveRst == false)
                                                    {
                                                        //MessageBox.Show("条码" + md.OneBarCode + "存储时发生错误,原因:" + errMsg);
                                                        //return;
                                                    }

                                                    #endregion

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

                                                    #region 打印单个标签

                                                    if (IsOne == "1")
                                                    {
                                                        if (IsSupply != "1")
                                                        {
                                                            filename = ManufacturerName.Contains("蔚来")
                                                                ? System.AppDomain.CurrentDomain.BaseDirectory +
                                                                  "wl.grf"
                                                                : System.AppDomain.CurrentDomain.BaseDirectory +
                                                                  PrintMoudleName("0"); //new
                                                        }
                                                        else
                                                        {
                                                            filename = System.AppDomain.CurrentDomain.BaseDirectory +
                                                                       PrintMoudleName("1");
                                                        }

                                                        printName = "Printer" + _printNameDict[partNo[j].ToString().Trim() + dt.Rows[0]["StationID"].ToString()];

                                                        string reportName = ConfigurationManager.AppSettings[printName]
                                                            .ToString();

                                                        DataTable headTable = GetPrintHeadTable(partNo[j].ToString().Trim(), PartName, NewOneCode, newcode);

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

                                                        LogSysBLL.AddInfo(
                                                            GetDateTime().ToString("yyyy/MM/dd HH:mm:ss") + NewOneCode,
                                                            MethodBase.GetCurrentMethod());
                                                        rp.Report.Print(false);

                                                    }

                                                    #endregion

                                                    #endregion

                                                    initBarCode();
                                                }
                                            }
                                            else//一模两压不同的
                                            {
                                                if (IsSupply != "1")
                                                {
                                                    #region 非直供件

                                                    if (ManufacturerName.Contains("蔚来"))
                                                    {
                                                        GetSjBarCode(stockNo[j].ToString().Trim(), partNo[j].ToString().Trim(), true, mould, PartName, ref NewOneCode, ref newcode);

                                                    }
                                                    else
                                                    {
                                                        GetSjBarCode(stockNo[j].ToString().Trim(), partNo[j].ToString().Trim(), true, mould, PartName, ref NewOneCode, ref newcode);

                                                    }

                                                    #endregion
                                                }
                                                else
                                                {
                                                    #region 直供件
                                                    GetSupplyCode(stockNo[j].ToString().Trim(), partNo[j].ToString().Trim(), QLevel, true, mould, PartName, ref NewOneCode, ref newcode);
                                                    #endregion
                                                }

                                                #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;
                                                md.Des1 = PartName;
                                                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 = "";
                                                    }
                                                }

                                                //// if (brbll.Add_Info_New(md, Program.tableName) == false)
                                                //if (SaveBarCode(md, Program.tableName, true, mould) == false)
                                                //{
                                                //    int a = 0;
                                                //    for (int l = 0; l < 5; l++)
                                                //    {
                                                //        //if (brbll.Add_Info_New(md, Program.tableName))
                                                //        if (SaveBarCode(md, Program.tableName, true, mould) == true)
                                                //        {
                                                //            break;
                                                //        }

                                                //        a += 1;
                                                //        Thread.Sleep(200);
                                                //    }

                                                //    if (a >= 4)
                                                //    {
                                                //        return;
                                                //    }
                                                //}

                                                string errMsg = string.Empty;
                                                bool saveRst = SaveInfo(md, true, mould, false, ref errMsg);
                                                if (saveRst == false)
                                                {
                                                    //MessageBox.Show("条码" + md.OneBarCode + "存储时发生错误,原因:" + errMsg);
                                                    //return;
                                                }

                                                #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());
                                                    IsSame = dt3.Rows[0]["IsSame"].ToString();
                                                    IsSupply = dt3.Rows[0]["IsSupply"].ToString();
                                                }

                                                #region 打印单个标签

                                                if (IsOne == "1")
                                                {
                                                    if (IsSupply != "1")
                                                    {
                                                        filename = ManufacturerName.Contains("蔚来")
                                                            ? System.AppDomain.CurrentDomain.BaseDirectory +
                                                              "wl.grf"
                                                            : System.AppDomain.CurrentDomain.BaseDirectory +
                                                              PrintMoudleName("0"); //new
                                                        if (partNo[j].Contains("A2146982300") ||
                                                            partNo[j].Contains("A2146982400"))
                                                        {
                                                            filename = AppDomain.CurrentDomain.BaseDirectory +
                                                                       PrintMoudleName("0");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        filename = System.AppDomain.CurrentDomain.BaseDirectory +
                                                                   PrintMoudleName("1");
                                                    }


                                                    //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();
                                                    //}
                                                    printName = "Printer" + _printNameDict[partNo[j].ToString().Trim() + dt.Rows[0]["StationID"].ToString()];

                                                    string reportName = ConfigurationManager.AppSettings[printName]
                                                        .ToString();
                                                    DataTable headTable = GetPrintHeadTable(partNo[j].ToString().Trim(), PartName, NewOneCode, newcode);


                                                    ReportHelper rp = new ReportHelper(filename, headTable, null,
                                                        (int)GRPaperOrientation.grpoDefault, 1, reportName);
                                                    LogSysBLL.AddInfo(
                                                        GetDateTime().ToString("yyyy/MM/dd HH:mm:ss") + NewOneCode,
                                                        MethodBase.GetCurrentMethod());
                                                    rp.Report.Print(false);

                                                }

                                                #endregion

                                                #endregion

                                                initBarCode();
                                            }
                                        }

                                        #endregion
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception(Program.station + "p704" + ex.Message);
                                    }
                                }
                                else
                                {
                                    return;
                                }
                            }
                            else
                            {
                                try
                                {

                                    planID = dt.Rows[0]["InjectionPlanID"].ToString();
                                    string[] partNo = dt.Rows[0]["PartNo"].ToString().Split(',');
                                    //string[] stockNo = dt.Rows[0]["StockNo"].ToString().Split(',');
                                    string[] stockNo = new string[partNo.Length];
                                    string ProductNature = dt.Rows[0]["ProductNature"].ToString();
                                    //ManufacturerName = dt.Rows[0]["ManufacturerName"].ToString();
                                    DataTable dtM = productBll.SearchInfoByPartNo(partNo[0]);
                                    if (dtM != null && dtM.Rows.Count > 0)
                                    {
                                        ManufacturerName = dtM.Rows[0]["ManufacturerName"].ToString();
                                    }

                                    #region 判断有几个零件号
                                    string mould = "0";
                                    for (int j = 0; j < partNo.Length; j++)
                                    {
                                        try
                                        {
                                            #region 根据零件号查找存货代码
                                            mould = j.ToString();
                                            DataTable sdt = productBll.SearchInfoByPartNo(partNo[j].ToString().Trim());
                                            if (sdt != null && sdt.Rows.Count > 0)
                                            {
                                                stockNo[j] = sdt.Rows[0]["StockNo"].ToString();
                                                IsSame = sdt.Rows[0]["IsSame"].ToString();
                                            }
                                            else
                                            {
                                                stockNo[j] = "";
                                            }

                                            #endregion

                                            #region 查询零件属性

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

                                            #endregion
                                        }
                                        catch (Exception ex)
                                        {
                                            throw new Exception(Program.station + "p768" + ex.Message);
                                        }


                                        if (IsSame == "1")
                                        {
                                            for (int k = 0; k < 2; k++)
                                            {
                                                if (IsSupply != "1")
                                                {
                                                    #region 非直供件

                                                    try
                                                    {
                                                        if (ManufacturerName.Contains("蔚来"))
                                                        {
                                                            GetSjBarCode(stockNo[j].ToString().Trim(), partNo[j].ToString().Trim(), true, mould, PartName, ref NewOneCode, ref newcode);

                                                        }
                                                        else
                                                        {
                                                            GetSjBarCode(stockNo[j].ToString().Trim(), partNo[j].ToString().Trim(), true, mould, PartName, ref NewOneCode, ref newcode);

                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        throw new Exception(Program.station + "p795" + ex.Message);
                                                    }

                                                    #endregion
                                                }
                                                else
                                                {
                                                    #region 直供件

                                                    try
                                                    {
                                                        GetSupplyCode(stockNo[j].ToString().Trim(), partNo[j].ToString().Trim(), QLevel, true, mould, PartName, ref NewOneCode, ref newcode);
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        throw new Exception(Program.station + "p810" + ex.Message);
                                                    }

                                                    #endregion
                                                }

                                                #region 插入数据tb_barCode

                                                try
                                                {
                                                    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;
                                                    md.Des1 = PartName;
                                                    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 = "";
                                                        }
                                                    }

                                                    string errMsg = string.Empty;
                                                    bool saveRst = SaveInfo(md, true, mould, false, ref errMsg);
                                                    if (saveRst == false)
                                                    {
                                                        //MessageBox.Show("条码" + md.OneBarCode + "存储时发生错误,原因:" + errMsg);
                                                        //return;
                                                    }

                                                }
                                                catch (Exception ex)
                                                {
                                                    throw new Exception(Program.station + "p854" + ex.Message);
                                                }

                                                #endregion

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

                                                #region 打印单个标签
                                                try
                                                {
                                                    if (IsOne == "1")
                                                    {
                                                        if (IsSupply != "1")
                                                        {
                                                            filename = ManufacturerName.Contains("蔚来")
                                                                ? System.AppDomain.CurrentDomain.BaseDirectory +
                                                                  "wl.grf"
                                                                : System.AppDomain.CurrentDomain.BaseDirectory +
                                                                  PrintMoudleName("0"); //new
                                                        }
                                                        else
                                                        {
                                                            filename = System.AppDomain.CurrentDomain.BaseDirectory +
                                                                       PrintMoudleName("1");
                                                        }

                                                        //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();
                                                        //}
                                                        printName = "Printer" + _printNameDict[partNo[j].ToString().Trim() + dt.Rows[0]["StationID"].ToString()];

                                                        string reportName = ConfigurationManager.AppSettings[printName]
                                                            .ToString();
                                                        DataTable headTable = GetPrintHeadTable(partNo[j].ToString().Trim(), PartName, NewOneCode, newcode);

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

                                                        LogSysBLL.AddInfo(
                                                            GetDateTime().ToString("yyyy/MM/dd HH:mm:ss") + NewOneCode,
                                                            MethodBase.GetCurrentMethod());
                                                        rp.Report.Print(false);

                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    throw new Exception(Program.station + "p904" + ex.Message);
                                                }
                                               

                                                #endregion

                                                #endregion

                                                initBarCode();
                                            }
                                        }
                                        else
                                        {
                                            if (IsSupply != "1")
                                            {
                                                #region 非直供件

                                                try
                                                {
                                                    if (ManufacturerName.Contains("蔚来"))
                                                    {

                                                        try
                                                        {
                                                            GetSjBarCode(stockNo[j].ToString().Trim(), partNo[j].ToString().Trim(), true, mould, PartName, ref NewOneCode, ref newcode);
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            throw new Exception(Program.station + "p932" + ex.Message);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        try
                                                        {
                                                            GetSjBarCode(stockNo[j].ToString().Trim(), partNo[j].ToString().Trim(), true, mould, PartName, ref NewOneCode, ref newcode);

                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            throw new Exception(Program.station + "p944" + ex.Message);
                                                        }
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    throw new Exception(Program.station + "p950" + ex.Message);
                                                }

                                                #endregion
                                            }
                                            else
                                            {
                                                #region 直供件

                                                try
                                                {
                                                    GetSupplyCode(stockNo[j].ToString().Trim(), partNo[j].ToString().Trim(), QLevel, true, mould, PartName, ref NewOneCode, ref newcode);
                                                }
                                                catch (Exception ex)
                                                {
                                                    throw new Exception(Program.station + "p965" + ex.Message);
                                                }

                                                #endregion
                                            }

                                            #region 插入数据tb_barCode
                                            try
                                            {
                                                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;
                                                md.Des1 = PartName;
                                                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 = "";
                                                    }
                                                }

                                                 string errMsg = string.Empty;
                                                bool saveRst = SaveInfo(md, true, mould, false, ref errMsg);
                                                if (saveRst == false)
                                                {
                                                    SaveLog3(Program.station + "测试保存错误,异常信息:" + md.OneBarCode + errMsg);
                                                    //MessageBox.Show("条码" + md.OneBarCode + "存储时发生错误,原因:" + errMsg);
                                                    //return;
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                throw new Exception(Program.station + "p1009" + ex.Message);
                                            }

                                            #endregion

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

                                            #region 打印单个标签

                                            if (IsOne == "1")
                                            {
                                                try
                                                {
                                                    if (IsSupply != "1")
                                                    {
                                                        filename = ManufacturerName.Contains("蔚来")
                                                            ? System.AppDomain.CurrentDomain.BaseDirectory +
                                                              "wl.grf"
                                                            : System.AppDomain.CurrentDomain.BaseDirectory +
                                                              PrintMoudleName("0");//new
                                                        if (partNo[j].Contains("A2146982300") ||
                                                                partNo[j].Contains("A2146982400"))
                                                        {
                                                            filename = AppDomain.CurrentDomain.BaseDirectory +
                                                                       "Sill.grf";
                                                        }
                                                    }
                                                    else
                                                    {
                                                        filename = System.AppDomain.CurrentDomain.BaseDirectory + PrintMoudleName("1");
                                                    }
                                                    //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();
                                                    //}
                                                    printName = "Printer" + _printNameDict[partNo[j].ToString().Trim() + dt.Rows[0]["StationID"].ToString()];

                                                    string reportName = ConfigurationManager.AppSettings[printName].ToString();
                                                    DataTable headTable = GetPrintHeadTable(partNo[j].ToString().Trim(), PartName, NewOneCode, newcode);

                                                    ReportHelper rp = new ReportHelper(filename, headTable, null, (int)GRPaperOrientation.grpoDefault, 1, reportName);
                                                    LogSysBLL.AddInfo(GetDateTime().ToString("yyyy/MM/dd HH:mm:ss") + NewOneCode, MethodBase.GetCurrentMethod());
                                                    rp.Report.Print(false);
                                                }
                                                catch (Exception ex)
                                                {
                                                    throw new Exception(Program.station + "p1056" + ex.Message);
                                                }
                                               
                                            }

                                            #endregion

                                            #endregion

                                            initBarCode();
                                        }

                                    }

                                    #endregion
                                }
                                catch (Exception ex)
                                {
                                    throw new Exception(Program.station + "p1074" + ex.Message);
                                }

                            }

                        }

                        #endregion

                        #region 修改打印时间

                        //UpdatePrintTime(DateTime.Now, label6.Text);

                        #endregion

                        initPlan();
                        lastTime=DateTime.Now;
                    }
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                MessageBox.Show(ex.ToString());
            }
        }

      

        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)
        {
            try
            {
                label2.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                Thread.Sleep(500);
            }
           catch(Exception ex)
            {
                Console.Write(ex.Message);
            }
        }

        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 = _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="",printBoxName="";
            int MaxCount = 0, CurrentCount = 0,IsSame=0;
            int aa = 0;

            try
            {
                timer1.Enabled=false; 
                
                GetClass();
                aa = aa + 1;

                LogHelper.WriteLog(aa.ToString());

                #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;
                }
                LogHelper.WriteLog(ID.ToString());

                #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 = new string[partNo.Length]; 
                        //string[] stockNo = dt.Rows[0]["StockNo"].ToString().Split(',');
                        string ProductNature = dt.Rows[0]["ProductNature"].ToString();
                        int[] same = new int[partNo.Length];

                        #region 判断有几个零件号
                        int mould = 0;
                        for (int j = 0; j < partNo.Length; j++)
                        {
                            mould = j;
                            #region 根据零件号查找存货代码

                            DataTable sdt = productBll.SearchInfoByPartNo(partNo[j].ToString().Trim());
                            if (sdt != null && sdt.Rows.Count > 0)
                            {
                                stockNo[j] = sdt.Rows[0]["StockNo"].ToString();
                                same[j] = Convert.ToInt32(sdt.Rows[0]["IsSame"].ToString());
                            }
                            else
                            {
                                stockNo[j] = "";
                                same[j] =0;
                            }


                            #endregion

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


                            if (partNo.Length == 1 && same[j] == 1)     //一个零件号,且一模两具生产的是两根一样的产品
                            {
                                for (int k = 0; k < 2; k++)
                                {
                                    GetSjBarCode(stockNo[j].ToString().Trim(), partNo[j].ToString().Trim(), true, mould.ToString(), PartName, ref NewOneCode, ref newcode);


                                    #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;
                                    md.Des1 = PartName;
                                    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 = "";
                                        }
                                    }

                                    ////if (brbll.Add_Info_New(md, Program.tableName) == false)
                                    //if (SaveBarCode(md, Program.tableName, true, same[j].ToString()) == false)
                                    //{
                                    //    int a = 0;
                                    //    for (int l = 0; l < 5; l++)
                                    //    {
                                    //        //if (brbll.Add_Info_New(md, Program.tableName))
                                    //        if (SaveBarCode(md, Program.tableName, true, same[j].ToString()) == true)
                                    //        {
                                    //            break;
                                    //        }

                                    //        a += 1;
                                    //        Thread.Sleep(200);
                                    //    }

                                    //    if (a >= 4)
                                    //    {
                                    //        return;
                                    //    }
                                    //}

                                    string errMsg = string.Empty;
                                    bool saveRst = SaveInfo(md, true, same[j].ToString(), false, ref errMsg);
                                    if (saveRst == false)
                                    {
                                        //MessageBox.Show("条码" + md.OneBarCode + "存储时发生错误,原因:" + errMsg);
                                        //return;
                                    }
                                    #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 == "售后件")
                                    {
                                        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 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();
                                    //}
                                    printName = "Printer" + _printNameDict[partNo[j].ToString().Trim() + dt.Rows[0]["StationID"].ToString()];

                                    #region 打印单个标签

                                    if (IsOne == "1")
                                    {
                                        filename = System.AppDomain.CurrentDomain.BaseDirectory + PrintMoudleName(); //new
                                       
                                        string reportName = ConfigurationManager.AppSettings[printName].ToString();
                                        DataTable headTable = GetPrintHeadTable(partNo[j].ToString().Trim(), PartName, NewOneCode, newcode);


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

                                        rp.Report.Print(false);
                                    }

                                    #endregion

                                    #endregion
                                }
                            }
                            else
                            {
                               
                                GetSjBarCode(stockNo[j].ToString().Trim(), partNo[j].ToString().Trim(), true, mould.ToString(), PartName, ref NewOneCode, ref newcode);

                                #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;
                                md.Des1 = PartName;
                                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 = "";
                                    }
                                }

                              
                                string errMsg = string.Empty;
                                bool saveRst = SaveInfo(md, true, same[j].ToString(), false, ref errMsg);
                                if (saveRst == false)
                                {
                                    //MessageBox.Show("条码" + md.OneBarCode + "存储时发生错误,原因:" + errMsg);
                                    //return;
                                }
                                #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 == "售后件")
                                {
                                    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 打印条码,判断是否打印单个条码

                                printName = "Printer" + _printNameDict[partNo[j].ToString().Trim() + dt.Rows[0]["StationID"].ToString()];

                                #region 打印单个标签

                                if (IsOne == "1")
                                {
                                    filename = System.AppDomain.CurrentDomain.BaseDirectory + PrintMoudleName(); //new
                                    
                                    string reportName = ConfigurationManager.AppSettings[printName].ToString();
                                    DataTable headTable = GetPrintHeadTable(partNo[j].ToString().Trim(), PartName, NewOneCode, newcode);

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

                                    rp.Report.Print(false);
                                }

                                #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= _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 = aa.ToString("yyyy-MM-dd");
                     
                }
                else
                {
                    Program.Shift = "B班";
                    if (GetDateTime().Hour >= 0 && GetDateTime().Hour < 8)
                    {
                        Program.ProductDate = aa.AddDays(-1).ToString("yyyy-MM-dd");
                    }
                    else if (GetDateTime().Hour >= 20 && GetDateTime().Hour <= 23)
                    {
                        Program.ProductDate = aa.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 dt1 = bll.SearchInfo(Program.station);

                DataTable dt = dt1.Clone();
                List<DataRow> list = dt1.AsEnumerable().Where(p => string.IsNullOrEmpty(p.Field<string>("BoxNo")) == true).ToList();
                if (list.Count > 0)
                {
                    dt = list.CopyToDataTable();
                }

                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]["OneBarCode"].ToString();
                        glacialList1.Items[i].SubItems[0].Tag = dt.Rows[i]["BoxNo"].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");
                        //glacialList1.Items[i].SubItems[4].Text = dt.Rows[i]["BoxNo"].ToString();
                        
                    }
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(Program.station + "p1608" + 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)
        {
            try
            {
                if (serialPort1.IsOpen)
                {
                    serialPort1.Close();
                }
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(),MethodBase.GetCurrentMethod());
                Environment.Exit(0);
            }
        }

       
        /// <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 = "", printBoxName="",IsSupply="",ManufacturerName="";
            string filename = "", printName = "";
            int MaxCount = 0, CurrentCount = 0;
            ProductBLL pbll = new ProductBLL();
            BarCodeBLL bll = new BarCodeBLL();
            BarCodeModel md = new BarCodeModel();
            PlasticBLL plbll= _plasticBLL;
            InjectionBoxBLL boxbll = new InjectionBoxBLL();
            InjectionBoxModel boxmd = new InjectionBoxModel();
            InjectionPlanBLL planbll=new InjectionPlanBLL();

            try
            {
                //if (status == false)
                //{
                //    MessageBox.Show("连接服务器失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //    return;
                //}

                #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();
                        ManufacturerName = pdt.Rows[0]["ManufacturerName"].ToString().Trim();
                    }
                    else
                    {
                        MessageBox.Show($"零件[{comboBox2.Text}]在系统中不存在!");
                        return;
                    }

                    #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();
                        PartName = dt3.Rows[0]["ProductName"].ToString();
                        IsSupply = dt3.Rows[0]["IsSupply"].ToString();

                    }

                    #endregion

                    //todo 判断零件号和计划是不是一致

                    DataTable plandt = planbll.searchPlanInfo(planID);
                    if (plandt != null && plandt.Rows.Count > 0)
                    {
                        if (plandt.Rows[0]["PartNo"].ToString().Contains(partNo)==false)
                        {
                            planID = "";
                        }
                    }

                    if (IsSupply != "1")
                    {
                        #region 非直供件
                        int printCount = Convert.ToInt32(textBox2.Text.Trim());
                        for (int i = 1; i <= printCount; i++)
                        {
                            GetSjBarCode(stockNo, partNo,false,"0", PartName, ref NewOneCode, ref newcode);

                            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;
                            
                            md.ProductNature = "正常件"; //第一次没有这个
                            md.Des1 = PartName;
                            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 = "";
                                }
                            }

                            ////if (bll.Add_Info_New(md, Program.tableName) == false)
                            //if (SaveBarCode(md, Program.tableName, false, "0",i== printCount) == false)
                            //{
                            //    return;
                            //}

                            string errMsg = string.Empty;
                            bool saveRst = SaveInfo(md, false, "0", i == printCount, ref errMsg);
                            if (saveRst == false)
                            {
                                //MessageBox.Show("条码" + md.OneBarCode + "存储时发生错误,原因:" + errMsg);
                                //return;
                            }


                            #endregion

                            #region 打印单个标签

                            if (IsOne == "1")
                            {
                                //filename = System.AppDomain.CurrentDomain.BaseDirectory + "单个条码.grf";
                                filename = ManufacturerName.Contains("蔚来")
                                    ? System.AppDomain.CurrentDomain.BaseDirectory +
                                      "wl.grf"
                                    : System.AppDomain.CurrentDomain.BaseDirectory +
                                      PrintMoudleName("0"); //new
                                if (partNo.Contains("A2146982300") ||
                                    partNo.Contains("A2146982400"))
                                {
                                    filename = AppDomain.CurrentDomain.BaseDirectory +
                                               "Sill.grf";
                                }
                                
                                //DataTable dt4 = plbll.SearchInfo(partNo, stationID);
                                //if (dt4 != null && dt4.Rows.Count > 0)
                                //{
                                //    printName = "Printer" + dt4.Rows[0]["PrinterNo"].ToString();
                                //}
                                printName = "Printer" + _printNameDict[partNo + stationID];

                                string reportName = ConfigurationManager.AppSettings[printName].ToString();
                                DataTable headTable = GetPrintHeadTable(partNo, PartName, NewOneCode, newcode);

                                ReportHelper rp = new ReportHelper(filename, headTable, null, (int)GRPaperOrientation.grpoDefault, 1, reportName);
                                LogSysBLL.AddInfo(GetDateTime().ToString("yyyy/MM/dd HH:mm:ss") + NewOneCode, MethodBase.GetCurrentMethod());
                                rp.Report.Print(false);
                            }

                            #endregion


                        }

                        #endregion
                    }
                    else
                    {
                        #region 直供件

                        for (int i = 1; i <= Convert.ToInt32(textBox2.Text.Trim()); i++)
                        {
                            //newcode = code.Substring(0, code.Length - 4) +
                            //          (Convert.ToInt32(code.Substring(23, 3)) +
                            //           i).ToString()
                            //          .PadLeft(3, '0') + "#";
                            GetSupplyCode(stockNo,partNo, QLevel,false, "0", PartName, ref NewOneCode, ref newcode);

                            #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;
                            md.Des1 = PartName;
                            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 = "";
                                }
                            }

                            ////if (bll.Add_Info_New(md, Program.tableName) == false)
                            //if (SaveBarCode(md, Program.tableName, false, "0") == false)
                            //{
                            //    return;
                            //}

                            string errMsg = string.Empty;
                            bool saveRst = SaveInfo(md, false, "0", false, ref errMsg);
                            if (saveRst == false)
                            {
                                //MessageBox.Show("条码" + md.OneBarCode + "存储时发生错误,原因:" + errMsg);
                                //return;
                            }

                            #endregion

                            #region 打印单个标签

                            if (IsOne == "1")
                            {
                                filename = System.AppDomain.CurrentDomain.BaseDirectory + PrintMoudleName("1");
                                
                                //DataTable dt4 = plbll.SearchInfo(partNo, stationID);
                                //if (dt4 != null && dt4.Rows.Count > 0)
                                //{
                                //    printName = "Printer" + dt4.Rows[0]["PrinterNo"].ToString();
                                //}
                                printName = "Printer" + _printNameDict[partNo + stationID];

                                string reportName = ConfigurationManager.AppSettings[printName].ToString();
                                DataTable headTable = GetPrintHeadTable(partNo, PartName, NewOneCode, newcode);

                                ReportHelper rp = new ReportHelper(filename, headTable, null, (int)GRPaperOrientation.grpoDefault, 1, reportName);
                                LogSysBLL.AddInfo(GetDateTime().ToString("yyyy/MM/dd HH:mm:ss") + NewOneCode, MethodBase.GetCurrentMethod());
                                rp.Report.Print(false);
                            }

                            #endregion
                        }

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

        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 = "", ManufacturerName = "";
            string IsSupply = "0";
            BarCodeModel md = new BarCodeModel();
            BarCodeBLL bll = new BarCodeBLL();
            ProductBLL pbll = new ProductBLL();
            PlasticBLL plbll = _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;
                    DialogResult result = MessageBox.Show($"补打条码[{code}]将被新的替换,确定补打条码?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    if (result == DialogResult.OK)
                    {

                        bool exsitWms = _wmsBll.IsReadBarCodeInWms(code);
                        if (exsitWms)
                        {
                            MessageBox.Show($"条码[{code}]在WMS系统已处理,无法补打!");
                            return;
                        }

                        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.PartNo = dt.Rows[0]["PartNo"].ToString();
                            md.BatchNo = dt.Rows[0]["BatchNo"].ToString();
                            string newOneCode = string.Empty;
                            string newBarCode = string.Empty;
                            GetBarCode(md.StockNo, md.BatchNo, md.PartNo, ref newOneCode, ref newBarCode);
                            md.OneBarCode = newOneCode;
                            md.BarCode = newBarCode;
                            md.BoxNo = dt.Rows[0]["BoxNo"].ToString();
                            if (gv.SubItems.Count > 1)
                            {
                                md.Des1 = gv.SubItems[1].Text;
                            }

                            md.PrintType = 2;

                            //DataTable pdt = pbll.SearchIsImportByPartNo(md.PartNo);

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

                                ManufacturerName = pdt.Rows[0]["ManufacturerName"].ToString().Trim();
                                IsSupply = pdt.Rows[0]["IsSupply"].ToString();
                            }
                        }
                        else
                        {
                            MessageBox.Show($"补打失败,条码[{code}]在表[{ Program.tableName}]中不存在!");
                            return;
                        }
                        //补打条码
                        string msg = bll.ReprintSave(md, Program.tableName, dt.Rows[0]["OneBarCode"].ToString(), dt.Rows[0]["BarCode"].ToString(),Program.station,"3");
                        if (!string.IsNullOrEmpty(msg))
                        {
                            MessageBox.Show($"补打失败,原因:" + msg);
                            return;
                        }
                        //if (bll.Add_Info_New(md, Program.tableName) == false)
                        //{
                        //    return;
                        //}
                        glacialList1.SelectedItems.Clear();
                        initBarCode();

                        #region 打印条码

                        //filename = System.AppDomain.CurrentDomain.BaseDirectory + "单个条码.grf";
                        filename = ManufacturerName.Contains("蔚来")
                            ? AppDomain.CurrentDomain.BaseDirectory +
                              "wl.grf"
                            : AppDomain.CurrentDomain.BaseDirectory +
                              PrintMoudleName(IsSupply); //new
                        if (md.PartNo.Contains("A2146982300") ||
                            md.PartNo.Contains("A2146982400"))
                        {
                            filename = AppDomain.CurrentDomain.BaseDirectory +
                                       "Sill.grf";
                        }

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


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

                        string reportName = ConfigurationManager.AppSettings[printName].ToString();
                        DataTable headTable = GetPrintHeadTable(md.PartNo, partName, md.OneBarCode, md.BarCode);


                        ReportHelper rp = new ReportHelper(filename, headTable, null,
                            (int)GRPaperOrientation.grpoDefault, 1, reportName);
                        LogSysBLL.AddInfo(GetDateTime().ToString("yyyy/MM/dd HH:mm:ss") + md.OneBarCode, MethodBase.GetCurrentMethod());
                        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;
        }

        /// <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
                {
                    DialogResult result = MessageBox.Show("确定删除条码?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    if (result == DialogResult.OK)
                    {
                        GlacialComponents.Controls.GLItem gv;
                        gv = glacialList1.SelectedItems[0] as GlacialComponents.Controls.GLItem;
                        md.BarCode = gv.Text;

                        string msg = bll.DelBarCode(gv.Text?.Trim(), Program.tableName,false,"");
                        if (!string.IsNullOrEmpty(msg))
                        {
                            MessageBox.Show(msg);
                        }
                        initBarCode();

                        //bll.DelBarCode_New(md, Program.tableName);
                        //initBarCode();
                    }
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                MessageBox.Show(ex.Message);
            }
        }


        /// <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= _plasticBLL;
                StationBLL sbll=new StationBLL();
                string filename = "", printName = "", printBoxName="",stationID="";
                 
                #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 查询工位ID

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

                        #endregion

                        #region 查询打印机名称

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

                        #endregion

                        printBoxName = "Printer" + (Convert.ToInt32(printName.Substring(7, 1)) + 2).ToString();
                        string reportName = ConfigurationManager.AppSettings[printBoxName].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 = "";
        }

        /// <summary>
        /// 下一计划
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label14_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("确认切换下一计划?", "确认提示", MessageBoxButtons.OKCancel) == DialogResult.Cancel) return;

                InjectionPlanBLL planbll=new InjectionPlanBLL();
                
                #region 查询有无下一计划

                DataTable dt = planbll.NextSearchInfoByName(Program.station);
                if (dt != null && dt.Rows.Count > 1)
                {
                    planID = dt.Rows[0]["InjectionPlanID"].ToString();
                    productID = dt.Rows[0]["ProductID"].ToString();
                    nextproductID = dt.Rows[1]["InjectionPlanID"].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();
                ProductBLL productBll = new ProductBLL();
                string aa = "";
                string[] partNo = null; 
                

                #region 验证数据有效性  模具条码不全暂时先屏蔽

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

                #endregion

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

                //ibll.UpdateFinish(md);

                #endregion

                #region 判断模具编号是否存在 模具条码不全暂时先屏蔽

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

                    DataTable nextdt = ibll.NextSearchInfoByName(Program.station);
                    if (nextdt != null && nextdt.Rows.Count > 1)
                    {
                        nextPlanID = nextdt.Rows[1]["InjectionPlanID"].ToString();
                        aa= nextdt.Rows[1]["PartNo"].ToString();
                        partNo = aa.Split(',');

                        DataTable dt1 = mbll.SearchInfo(textBox4.Text.Trim(), partNo[0]);
                        if (dt1 != null && dt1.Rows.Count > 0)
                        {
                            #region 更新上一计划为完成

                            //#region 获取工位编号

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

                            //#endregion
                            md.InjectionPlanID = planID;
                            ibll.UpdateFinish(md);

                            if (!string.IsNullOrEmpty(nextPlanID) && nextPlanID != planID)
                            {
                                ibll.UpdatePlanStartTime(nextPlanID);
                            }

                            #endregion

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

                        }
                        else
                        {
                            MessageBox.Show("模具和计划不匹配!", "提示", MessageBoxButtons.OK);
                            textBox4.SelectAll();
                            textBox4.Focus();
                            return;
                        }
                        
                    }
                    else
                    {
                        #region 更新上一计划为完成

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

                        //md.InjectionPlanID = planID;
                        //ibll.UpdateFinish(md);

                        #endregion

                        label12.Text = "暂无一下生产计划";
                        return;
                    }

                    

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

                #endregion

                panel45.Visible = false;

                #region 获取当前生产信息

                //DataTable dt = ibll.SearchInfoByName(Program.station);
                //if (dt != null && dt.Rows.Count > 0)
                //{
                //    planID = dt.Rows[0]["InjectionPlanID"].ToString();
                //    string[] partNo1 = dt.Rows[0]["PartNo"].ToString().Split(',');

                //    label12.Text = "当前生产计划为:";
                //    for (int i = 0; i < partNo1.Length; i++)
                //    {
                //        DataTable dt2 = productBll.SearchInfoByPartNo(partNo1[i].ToString().Trim());
                //        if (dt2 != null && dt2.Rows.Count > 0)
                //        {
                //            label12.Text += "零件号" + partNo1[i].ToString().Trim() + ",零件名称" + dt2.Rows[0]["ProductName"].ToString() + ";";
                //        }
                //    }
                //}
                //else
                //{
                //    label12.Text = "暂无生产计划";
                //}
                initPlan();

                #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)
                    {
                        opcGroup1.DataChange -= new DIOPCGroupEvent_DataChangeEventHandler(opcGroup1_DataChange);
                        opcServer.OPCGroups.RemoveAll();
                        opcServer.Disconnect();
                        serialPort1.Close();
                         
                        label23.Enabled = true;
                        label23.BackColor = System.Drawing.Color.DeepSkyBlue;
                        //if (ConfigurationManager.AppSettings["StationMode"].ToString() == "1")
                        //{
                        //    timer1.Enabled = false;
                        //}
                        //if (ConfigurationManager.AppSettings["StationMode"].ToString() == "2")
                        //{
                        //    serialPort1.Close();
                        //}
                        label13.Text = "开始打印";
                        label13.BackColor = System.Drawing.Color.Gray;
                    }
                    else
                    {
                        return;
                    }
                }

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

                        #region 连接PLC  
                        try
                        {
                            if (CreateServer())
                            {
                                if (ConnectServer(strHostIP, "Kepware.KEPServerEX.V6"))
                                {
                                    Connected = true;

                                    #region 创建组

                                    opcGroups = opcServer.OPCGroups;
                                    opcGroup1 = opcGroups.Add("Mould");
                                    SetGroupProperty(opcGroup1, _plcRate);

                                    #endregion

                                    #region 创建项

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

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

                                    DataTable PLCdt = _PLCbll.SearchMould(Program.station);
                                    if (PLCdt != null && PLCdt.Rows.Count > 0)
                                    {
                                        opcItemm1 = new OPCItem[PLCdt.Rows.Count];
                                        for (int i = 0; i < PLCdt.Rows.Count; i++)
                                        {
                                            opcItemm1[i] = opcItems1.AddItem(PLCdt.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;
                            }
                        }
                        catch(Exception ex)
                        {
                            MessageBox.Show("创建OPC服务失败!", "提示", MessageBoxButtons.OK);
                            Connected = false;
                            LogHelper.WriteLog("创建OPC服务失败!");
                            LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                            return;
                        }
                       

                        #endregion

                        
                        //if (ConfigurationManager.AppSettings["StationMode"].ToString() == "1")
                        //{
                        //    timer1.Enabled = true;
                        //}
                        //if (ConfigurationManager.AppSettings["StationMode"].ToString() == "2")
                        //{
                        //    if (serialPort1.IsOpen)
                        //    {
                        //        serialPort1.Close();
                        //        serialPort1.Open();
                        //    }
                        //    else
                        //    {
                        //        serialPort1.Open();
                        //    }
                        //}

                        label13.Text = "暂停打印";
                        label13.BackColor = System.Drawing.Color.DeepSkyBlue;
                        label23.Enabled = false;
                        label23.BackColor = System.Drawing.Color.Gray;
                        textBox2.Text = "";
                    }
                    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)
        {
            FrmQuality fr = new FrmQuality();
            fr.QualityViewClosed += (arg1) =>
            {
                try
                {
                    initBarCode();
                }
               catch(Exception ex)
                {
                    LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                }
            };
            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)
        //{
        //    try
        //    {
        //        base.Invoke(new EventHandler(this.Scan));
        //    }
        //    catch (Exception ex)
        //    {
        //        LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
        //    }

        //}

        //private void Scan(object sender, EventArgs e)
        //{
        //    string _code_meca = "",printBoxName="";
        //    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];
        //        }

        //        GetClass();

        //        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 = _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 = "",IsSupply="";
        //        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 = new string [partNo.Length];
        //            //string[] stockNo = dt.Rows[0]["StockNo"].ToString().Split(',');
        //            string ProductNature = dt.Rows[0]["ProductNature"].ToString();
        //            int IsSame = 0;

        //            #region 判断有几个零件号
        //            string mould = "0";
        //            for (int j = 0; j < partNo.Length; j++)
        //            {
        //                #region 根据零件号查找存货代码

        //                DataTable sdt = productBll.SearchInfoByPartNo(partNo[j].ToString().Trim());
        //                if (sdt != null && sdt.Rows.Count > 0)
        //                {
        //                    stockNo[j] = sdt.Rows[0]["StockNo"].ToString();
        //                    IsSame=Convert.ToInt32(sdt.Rows[0]["IsSame"].ToString());
        //                }
        //                else
        //                {
        //                    stockNo[j] = "";
        //                    IsSame = 0;
        //                }

        //                #endregion

        //                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());
        //                    IsSupply = dt3.Rows[0]["IsSupply"].ToString();
        //                }

        //                if (IsSame == 1)
        //                {
        //                    for (int k = 0; k < 2; k++)
        //                    {

        //                        GetSjBarCode(stockNo[j].ToString().Trim(), partNo[j].ToString().Trim(),true, mould, PartName, ref NewOneCode, ref newcode);

        //                        #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;
        //                        md.Des1 = PartName;
        //                        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 = "";
        //                            }
        //                        }

        //                        ////if (brbll.Add_Info_New(md, Program.tableName)==false)
        //                        //if (SaveBarCode(md, Program.tableName, true, mould) == false)
        //                        //{
        //                        //    return;
        //                        //}

        //                        string errMsg = string.Empty;
        //                        bool saveRst = SaveInfo(md, true, mould, false, ref errMsg);
        //                        if (saveRst == false)
        //                        {
        //                            //MessageBox.Show("条码" + md.OneBarCode + "存储时发生错误,原因:" + errMsg);
        //                            //return;
        //                        }

        //                        #endregion

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

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

        //                        #region 打印单个标签

        //                        if (IsOne == "1")
        //                        {
        //                            if (IsSupply == "1")
        //                            {
        //                                filename = System.AppDomain.CurrentDomain.BaseDirectory + PrintMoudleName(IsSupply);

        //                                string reportName = ConfigurationManager.AppSettings[printName].ToString();
        //                                DataTable headTable = GetPrintHeadTable(partNo[j].ToString().Trim(), PartName, NewOneCode, newcode);

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

        //                                rp.Report.Print(false);
        //                            }
        //                        }

        //                        #endregion



        //                        #endregion
        //                    }
        //                }
        //                else
        //                {
        //                    GetSjBarCode(stockNo[j].ToString().Trim(), partNo[j].ToString().Trim(),true, mould, PartName, ref NewOneCode, ref newcode);

        //                    #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;
        //                    md.Des1 = PartName;
        //                    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 = "";
        //                        }
        //                    }

        //                    ////if (brbll.Add_Info_New(md, Program.tableName)==false)
        //                    //if (SaveBarCode(md, Program.tableName, true, mould) == false)
        //                    //{
        //                    //    return;
        //                    //}

        //                    string errMsg = string.Empty;
        //                    bool saveRst = SaveInfo(md, true, mould, false, ref errMsg);
        //                    if (saveRst == false)
        //                    {
        //                        //MessageBox.Show("条码" + md.OneBarCode + "存储时发生错误,原因:" + errMsg);
        //                        //return;
        //                    }
        //                    #endregion

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

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

        //                    #region 打印单个标签

        //                    if (IsOne == "1")
        //                    {
        //                        if (IsSupply == "1")
        //                        {
        //                            filename = System.AppDomain.CurrentDomain.BaseDirectory + PrintMoudleName(IsSupply);  //new

        //                            string reportName = ConfigurationManager.AppSettings[printName].ToString();
        //                            DataTable headTable = GetPrintHeadTable(partNo[j].ToString().Trim(), PartName, NewOneCode, newcode);

        //                            LogHelper.WriteLog(printName + ";" + reportName + ";" + filename);
        //                            ReportHelper rp = new ReportHelper(filename, headTable, null,
        //                                (int) GRPaperOrientation.grpoDefault, 1, reportName);

        //                            rp.Report.Print(false);
        //                        }
        //                    }

        //                    #endregion


        //                    #endregion
        //                }
        //                initBarCode();
        //            }

        //            #endregion
        //        }

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


        private void timer2_Tick(object sender, EventArgs e)
        {
            Program.ProductDate = _barCodeBLL.GetServiceTime().ToString();
            //initPlan();
        }

        private void comboBox2_TextChanged(object sender, EventArgs e)
        {
            label12.Focus();
        }

        private void glacialList1_Click(object sender, EventArgs e)
        {
            try
            {
                if (glacialList1.SelectedItems.Count > 0)
                {
                    GlacialComponents.Controls.GLItem gv;
                    gv = glacialList1.SelectedItems[0] as GlacialComponents.Controls.GLItem;
                     Program.strBarCode = gv.Text;
                    //Program.strBoxCode = gv.SubItems[4].Text;
                    Program.strBoxCode = gv.SubItems[0].Tag?.ToString();
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }

        }
        /// <summary>
        /// 每隔几秒,连接一下服务器,刷新一下当前计划
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer3_Tick(object sender, EventArgs e)
        {
            try
            {
                Ping p1 = new Ping();

                PingReply reply = p1.Send("10.60.101.60"); //发送主机名或Ip地址
                StringBuilder sbuilder;
                if (reply.Status == IPStatus.Success)
                {
                    status = true;
                    label2.BackColor = Color.LightGray;
                }
                else
                {
                    status = false;
                    label2.BackColor = Color.Red;
                }
                GetClass();


                //textBox1.Text = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) +
                //                Program.ProductDate.Substring(8, 2);     //批次
                textBox1.Text = GetBatch(true);




                #region 获取当前生产信息

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

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Program.cc = comboBox1.Text;
        }



        //private DateTime GetPrintTime(string station)
        //{
        //    try
        //    {
        //        DateTime time = DateTime.Now;
        //        StationBLL bll = new StationBLL();

        //        DataTable dt = bll.SearchInfoByNo(station);
        //        if (dt != null && dt.Rows.Count > 0)
        //        {
        //            if (string.IsNullOrEmpty(dt.Rows[0]["PrintTime"].ToString()))
        //            {
        //                time = DateTime.Now;
        //            }
        //            else
        //            {
        //                time = Convert.ToDateTime(dt.Rows[0]["PrintTime"].ToString());
        //            }
        //        }

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



        //private bool UpdatePrintTime(DateTime time, string station)
        //{
        //    try
        //    {
        //        StationBLL bll = new StationBLL();
        //        return bll.UpdateTime(time, station);
        //    }
        //    catch (Exception ex)
        //    {
        //        LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
        //        return false;
        //    }
        //}

        //private int GetSeconds(string station)
        //{
        //    try
        //    {
        //        int seconds = 0;
        //        StationBLL bll = new StationBLL();

        //        DataTable dt = bll.SearchInfoByNo(station);
        //        if (dt != null && dt.Rows.Count > 0)
        //        {
        //            if (string.IsNullOrEmpty(dt.Rows[0]["Seconds"].ToString()))
        //            {
        //                seconds = 0;
        //            }
        //            else
        //            {
        //                seconds = Convert.ToInt32(dt.Rows[0]["Seconds"].ToString());
        //            }
        //        }

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

        ///// <summary>
        ///// 计算时间差
        ///// </summary>
        ///// <param name="t">时间1</param>
        ///// <param name="t2">时间2</param>
        ///// <returns>返回值:时间差(毫秒为单位)</returns>
        //private long TimeDiff(DateTime t, DateTime t2)
        //{
        //    long lReturn = -1;
        //    System.TimeSpan NowValue = new TimeSpan(t.Ticks);
        //    System.TimeSpan TimeValue = new TimeSpan(t2.Ticks);
        //    System.TimeSpan DateDiff = TimeSpan.Zero;
        //    try
        //    {
        //        //计算时间差
        //        //DateDiff = TimeValue.Subtract(NowValue).Duration();
        //        DateDiff = TimeValue.Subtract(NowValue);
        //        int hours = DateDiff.Hours;
        //        int minutes = DateDiff.Minutes;
        //        int seconds = DateDiff.Seconds;
        //        int milliseconds = DateDiff.Milliseconds;

        //        string TimeDiff = hours.ToString() + ":"
        //                                           + minutes.ToString() + ":"
        //                                           + seconds.ToString() + "."
        //                                           + milliseconds.ToString();
        //        //是否比现在的时间小,如果小就设置成第二天再启动,否则当天启动
        //        if (hours <= 0 && minutes <= 0 && seconds <= 0 && milliseconds <= 0)
        //            hours += 24;

        //        lReturn = hours * 3600
        //                  + minutes * 60
        //                  + seconds;
        //    }
        //    catch (Exception ex)
        //    {
        //        LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
        //    }
        //    return lReturn;
        //}

      

        bool SaveBarCode(BarCodeModel bcm,string tableName, bool isAutoPrint,string mould, ref string errorMsg ,bool handPrint = false )
        {

            string rst = _wmsBll.SaveRecordAndInterface(bcm, Program.tableName,"",Program.station,"4");
            if (string.IsNullOrEmpty(rst))
            {
                return true;
            }
            else
            {
                errorMsg = rst;
                LogErrBLL.AddInfo(Program.station+"-"+ bcm.OneBarCode + ":" + rst, MethodBase.GetCurrentMethod());
                return false;
            } 
        }
        private BarCodeModel _lastbarCodeModel =null;
        bool SaveInfo(BarCodeModel md, bool isAutoPrint, string mould, bool handPrint, ref string errMsg)
        {
            if (_lastbarCodeModel!=null)
            {
               DataTable dt =  _barCodeBLL.SeachInfoByOne(_lastbarCodeModel.OneBarCode, Program.tableName, 1);
                if(dt.Rows.Count == 0)
                {
                    SaveLog3("重发数据"+ Program.station + ",条码" + md.OneBarCode);
                    SaveBarCode(_lastbarCodeModel, Program.tableName, isAutoPrint, mould, ref errMsg, handPrint);
                }
            }
            _lastbarCodeModel = null;
            try
            {
                if (SaveBarCode(md, Program.tableName, isAutoPrint, mould, ref errMsg, handPrint) == false)
                {
                    int a = 0;
                    for (int l = 0; l < 3; l++)
                    {
                        // if (brbll.Add_Info_New(md, Program.tableName))
                        if (SaveBarCode(md, Program.tableName, true, mould, ref errMsg, handPrint) == true)
                        {
                            break;
                        }

                        a += 1;
                        //Thread.Sleep(200);
                        Thread.Sleep(200);
                    }

                    if (a >= 2)
                    {
                        _lastbarCodeModel = md;
                        SaveLog3(Program.station + "保存3次失败,条码" + md.OneBarCode);
                        return false;
                    }
                }
                return true;
            }
            catch(Exception ex)
            {
                _lastbarCodeModel = md;
                errMsg = ex.Message;
                LogErrBLL.AddInfo(Program.station + "保存异常-" + md.OneBarCode + ":" + errMsg, MethodBase.GetCurrentMethod());
                return false;
            }
        }

        /// <summary>
        /// 20位注塑条码
        /// </summary>
        /// <param name="stockNo"></param>
        /// <param name="partNo"></param>
        /// <param name="autoPrint"></param>
        /// <param name="mould"></param>
        /// <param name="newOneCode"></param>
        /// <param name="newCode"></param>
        void GetSjBarCode(string stockNo,string partNo, bool autoPrint,string mould,string partName, ref string newOneCode,ref string newCode)
        {
            string batch = GetBatch(autoPrint);
            GetBarCode(stockNo, batch, partNo, ref newOneCode, ref newCode);
            //newOneCode = _uniqueBll.GetSjBarCodeSerialNo(stockNo, batch);
            //newCode = partNo + "." + batch + "." + newOneCode.Substring(newOneCode.Length - 4, 4);
        }
        void GetBarCode(string stockNo, string batch, string partNo, ref string newOneCode, ref string newCode)
        {
            newOneCode = _uniqueBll.GetSjBarCodeSerialNo(stockNo, batch);
            newCode = partNo + "." + batch + "." + newOneCode.Substring(newOneCode.Length - 4, 4);
        }

        string GetBatch(bool isAutoPrint)
        {
            string batch = string.Empty;
            if (isAutoPrint)
            {
                DateTime dt = DateTime.Now;
                if (DateTime.TryParse(Program.ProductDate, out dt) == false)
                {
                    dt = DateTime.Now;
                }
                batch = dt.ToString("yyMMdd");
                // batch = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2);
            }
            else
            {
                batch = textBox1.Text.Trim();
            }
            return batch;

            //string batch = string.Empty;
            //if (isAutoPrint)
            //{

            //    batch = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2);
            //}
            //else
            //{
            //    batch = textBox1.Text.Trim();
            //}
            //return batch;
        }
        //private object _selectItemL = null;
        //bool _isShowHintL = true;

        //private object _selectItemR = null;
        //bool _isShowHintR = true;
    
       
        /// <summary>
        /// 直供件条码  A2478852600#Q02#240826#001#
        /// </summary>
        /// <param name="partNo"></param>
        /// <param name="qLevel"></param>
        /// <param name="newCode"></param>
        void GetSupplyCode(string stockNo,string partNo,string qLevel, bool autoPrint,string mould,string partName, ref string newOneCode, ref string newCode)
        {
            string batch = string.Empty;
            if (autoPrint)
            {
                //batch = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2);
                batch = GetBatch(true);
            }
            else
            {
                batch = textBox1.Text.Trim();
            }
            newCode = _uniqueBll.GetSupplySerialNo(partNo, qLevel, batch);
            newOneCode = _uniqueBll.GetSjBarCodeSerialNo(stockNo, batch);
             
        }

       
        bool? lastCheckState = null;
       

        /// <summary>
        /// 用户双击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label7_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            string cs = ConfigurationManager.AppSettings["测试"];
            if (!string.IsNullOrEmpty(cs) && cs == "true")
            {
                timer3.Enabled = false;
                //调用测试
                Array a = null;
                Array b = null;
                Array c = null;
                Array d = null;
                status = true;
                IsTest = true;
                bool bbb = true;
                //label23_Click(null, null);
                //textBox1.Text = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) +
                //                            Program.ProductDate.Substring(8, 2);
                textBox1.Text = GetBatch(true);
                if (bbb == true)
                {   //自动
                    opcGroup1_DataChange(1, 1, ref a, ref b, ref c, ref d);
                }
                else
                {   //手动
                    label23_Click(null, null);
                }
            }
        }
        bool IsTest = false;
        /// <summary>
        /// 工位双击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label5_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            string cs = ConfigurationManager.AppSettings["测试"];
            if (!string.IsNullOrEmpty(cs) && cs=="true")
            {
                timer3.Enabled = false;
            }

        }

        private void btnBarCodeWithBox_Click(object sender, EventArgs e)
        {

            if (MessageBox.Show("确定切换为箱码绑定模式?", "切换确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel) return;
            try
            {
                this.FormClosed += (arg1, arg2) => {

                    opcGroup1.DataChange -= new DIOPCGroupEvent_DataChangeEventHandler(opcGroup1_DataChange);
                    opcServer.OPCGroups.RemoveAll();
                    opcServer.Disconnect();
                    serialPort1.Close();

                    FrmMain2408 frm = new FrmMain2408();
                    frm.Show();
                };
                this.Close();
            }
            catch (Exception ex)
            {

            }
        }
         

        private void lbDevState_Click(object sender, EventArgs e)
        {
            if (lbDevState.Text == "设备已连接")
            {
                if (MessageBox.Show("确认断开设备连接?", "设备断开确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel) return;
                lbDevState.Text = "设备已断开";
                lbDevState.BackColor = Color.Red;
                opcGroup1.DataChange -= new DIOPCGroupEvent_DataChangeEventHandler(opcGroup1_DataChange);
                opcServer.OPCGroups.RemoveAll();
                opcServer.Disconnect();
                serialPort1.Close();
                timer3.Enabled = false;
            }
            else
            {
                if (MessageBox.Show("确认连接到注塑设备?", "设备连接确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel) return;

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

                            #region 创建组

                            opcGroups = opcServer.OPCGroups;
                            opcGroup1 = opcGroups.Add("Mould");
                            SetGroupProperty(opcGroup1, _plcRate);

                            #endregion

                            #region 创建项

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

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

                            DataTable PLCdt = _PLCbll.SearchMould(Program.station);
                            if (PLCdt != null && PLCdt.Rows.Count > 0)
                            {
                                opcItemm1 = new OPCItem[PLCdt.Rows.Count];
                                for (int i = 0; i < PLCdt.Rows.Count; i++)
                                {
                                    opcItemm1[i] = opcItems1.AddItem(PLCdt.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;
                        }

                        lbDevState.Text = "设备已连接";
                        lbDevState.BackColor = Color.DeepSkyBlue;
                        timer3.Enabled = true;
                    }
                    else
                    {
                        MessageBox.Show("创建OPC服务失败!", "提示", MessageBoxButtons.OK);
                        Connected = false;
                        LogHelper.WriteLog("创建OPC服务失败!");
                        return;
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show("创建OPC服务失败!", "提示", MessageBoxButtons.OK);
                    Connected = false;
                    LogHelper.WriteLog("创建OPC服务失败!");
                    LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                    return;
                }

            }
        }

        string PrintMoudleName(string isSupply = "0")
        {
            return BussinessHelper.PrintMoudleName(Program.station, isSupply);
            //if ("IM05,IM08,IM10".Contains(Program.station)) //二维小条码
            //{
            //    return "单个条码2.grf";
            //}
            //else if ("IM06,IM07,IM09,IM11,IM12,".Contains(Program.station)) //一维条码
            //{
            //    return "单个条码.grf";
            //}
           
            //else if ("IM01,IM02,IM03,IM04,IM15,IM18,IM20".Contains(Program.station)) //小米大条码
            //{
            //    return "Sill.grf";
            //}
            //else if ("IM13,IM14".Contains(Program.station)) //直供条码
            //{
            //    //return "单个条码1.grf";
            //    if (isSupply == "0") //13,14机台,直供件打二维码 非直供件打一维码
            //    {
            //        return "单个条码.grf";
            //    }
            //    else
            //    {
            //        return "单个条码2.grf";
            //    }
            //}
            //else
            //{
            //    return "单个条码2.grf";
            //}

        } 
       

        DataTable GetPrintLableModel()
        {
            DataTable headTable = new DataTable();
            headTable.Columns.Add("PrintTime");
            headTable.Columns.Add("PartNo");
            headTable.Columns.Add("PartName");
            headTable.Columns.Add("OneBarCode");
            headTable.Columns.Add("BarCode");
            headTable.Columns.Add("Station");
            return headTable;
        }
        DataTable GetPrintHeadTable(string partNo,string partName,string oneBarCode,string barCode)
        {
            DataTable headTable = GetPrintLableModel();
            DataRow row = headTable.NewRow();
            row["PrintTime"] =
                GetDateTime().ToString("yyyy/MM/dd HH:mm:ss");
            row["PartNo"] = partNo;
            row["PartName"] = partName;
            row["OneBarCode"] = oneBarCode;
            row["BarCode"] = barCode;
            row["Station"] = Program.station;
            headTable.Rows.Add(row);
            return headTable;
        }
       
        void SaveLog3(string txt)
        {
            try
            {
                LogSysBLL.AddInfo(txt, MethodBase.GetCurrentMethod());

            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("SaveLog:" + ex.Message);
            }
        }
    }
}