using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using MESClassLibrary;
using MESClassLibrary.BLL;
using MESClassLibrary.BLL.BasicInfo;
using MESClassLibrary.BLL.Injection;
using MESClassLibrary.BLL.Inspection;
using MESClassLibrary.BLL.Log;
using MESClassLibrary.BLL.TruckBox;
using MESClassLibrary.DAL;
using MESClassLibrary.EFModel;
using MESClassLibrary.Model;
using OPCAutomation;
using System.Configuration;
using System.IO;
using System.Security.Cryptography;
using gregn6Lib;

namespace InjectionPC
{
    public partial class FrmMain_Injection : Form
    {
        public FrmMain_Injection()
        {
            InitializeComponent();
        }

        #region 变量

        private string strHostIP;
        private string strHostName;
        private OPCServer opcServer;
        private OPCGroups opcGroups;
        private OPCGroup opcGroup1;
        private OPCItems opcItems1;
        private OPCItem[] opcItemm1;
        private OPCGroup opcGroup2;
        private OPCItems opcItems2;
        private OPCItem[] opcItemm2;
        private string[] ItemIDs;
        object ItemValues;
        object Qualities;
        object TimeStamps;
        public bool Connected = false;

        #endregion

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

        public static int ID = 0;

        private void FrmMain_Injection_Load(object sender, EventArgs e)
        {
            try
            {
                WorkBll wbll=new WorkBll();

                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 = wbll.WorkClass();          //班次
                Program.cc = comboBox1.Text;
                
                initBarCode();

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


                #region 获取当前生产信息

                InitPlan();

                #endregion

                #region 连接PLC

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

                        #region 创建组

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

                        #endregion

                        #region 创建项

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

                        AddressBLL bll = new AddressBLL();

                        DataTable dt1 = CommonTools.ListToDataTable(bll.SearchInfo("1", 0));
                        //DataTable dt1 = bll.SearchInfo("1", 0);
                        if (dt1 != null && dt1.Rows.Count > 0)
                        {
                            opcItemm1 = new OPCItem[dt1.Rows.Count];
                            for (int i = 0; i < dt1.Rows.Count; i++)
                            {
                                opcItemm1[i] = opcItems1.AddItem(dt1.Rows[i]["Address"].ToString(), i);
                            }
                        }

                        Thread.Sleep(200);

                        opcItems2 = opcGroup2.OPCItems;
                        opcItems2.DefaultIsActive = true;

                        DataTable dt2 = CommonTools.ListToDataTable(bll.SearchInfo("1", 1));
                        if (dt2 != null && dt2.Rows.Count > 0)
                        {
                            opcItemm2 = new OPCItem[dt2.Rows.Count];
                            for (int i = 0; i < dt2.Rows.Count; i++)
                            {
                                opcItemm2[i] = opcItems2.AddItem(dt2.Rows[i]["Address"].ToString(), i);
                            }
                        }

                        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服务失败!");
                }


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

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

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

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

                if (GetDateTime().Hour >= 8 && GetDateTime().Hour < 20)
                {
                    Program.Shift = "白班";
                    Program.ProductDate = aa.ToString("yyyy-MM-dd");

                }
                else
                {
                    Program.Shift = "夜班";
                    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");
                    }
                }

                comboBox1.Text = Program.Shift;
            }
            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 = DateTime.ParseExact(dt.Rows[0]["time"].ToString(), "yyyy-MM-dd HH:mm:ss.fff",
                        System.Globalization.CultureInfo.CurrentCulture);

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


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

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

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

                    label27.Text = bll.GetQtyByPlan(planID).ToString();

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

                    for (int i = 0; i < partNo.Length; i++)
                    {
                        DataTable sdt = productBll.SearchInfoByPartNo(partNo[i].ToString().Trim());
                        if (sdt != null && sdt.Rows.Count > 0)
                        {
                            
                        }
                    }
                }
                else
                {
                    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());
            }
        }


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

        /// <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 timer2_Tick(object sender, EventArgs e)
        {
            InitPlan();
            WorkBll bll=new WorkBll();

            comboBox1.Text = bll.WorkClass(); 
        }

        void opcGroup1_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues,ref Array Qualities, ref Array TimeStamps)
        {
            try
            {
                InjectionPlanBLL bll = new InjectionPlanBLL();
                BarCodeBLL brbll = new BarCodeBLL();
                BarCodeModel md = new BarCodeModel();
                ProductBLL productBll = new ProductBLL();
                PlasticBLL pbll = new PlasticBLL();
                AddPartInfoBLL abll = new AddPartInfoBLL();
                InspectionBLL ibll = new InspectionBLL();
                WeightBLL wbll=new WeightBLL();

                tb_Inspection_tx imd = new tb_Inspection_tx();

                string code = "", OneCode = "";
                string newcode = "", newcode1 = "", NewOneCode = "", NewOneCode1 = "";
                string IsPack = "", IsOne = "", QLevel = "", IsPaint = "", PartName = "", IsSame = "", IsSupply = "", IsSend="",partId="";
                string ManufacturerName = "";
                string filename = "", printName = "", printBoxName = "";
                int MaxCount = 0, CurrentCount = 0;
                decimal weigth = 0,min_weight=0,max_weight=0;
                string des1 = "", des2 = "", des3 = "", des4 = "", des5 = "";
                bool isOk = false;

                DataTable dt2 = null;

                //if (status == false)
                //{
                //    MessageBox.Show("连接服务器失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //    return;
                //}
                for (int i = 1; i <= NumItems; i++)
                {
                    int handle = Convert.ToInt32(ClientHandles.GetValue(i).ToString().Trim());
                    string value = ItemValues.GetValue(i).ToString();

                    //TODO 机械手到位后读取称重值,写条码信息,绑定纤维板和螺钉信息
                    
                    #region 机械手到位

                    if (handle == 0)
                    {
                        if (value == "1" || value.ToLower() == "true")
                        {
                            weigth = Convert.ToDecimal(ReadSingleValueFromOPC(opcItemm1, 1))*1000;

                            GetClass();

                            #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)
                                    {
                                        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 判断有几个零件号

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

                                            DataTable sdt = productBll.SearchInfoByPartNo(partNo[j].Trim());
                                            if (sdt != null && sdt.Rows.Count > 0)
                                            {
                                                partId = sdt.Rows[0]["ProductID"].ToString();
                                                DataTable dtw =
                                                    CommonTools.ListToDataTable(wbll.SearchWeightById(partId));
                                                if (dtw != null && dtw.Rows.Count > 0)
                                                {
                                                    min_weight = Convert.ToDecimal(dtw.Rows[0]["LowerWeight"]);
                                                    max_weight = Convert.ToDecimal(dtw.Rows[0]["UpperWeight"]);
                                                }

                                                if (ConfigurationManager.AppSettings["IsWeight"] == "1")
                                                {
                                                    if (min_weight >= weigth && weigth <= max_weight)
                                                    {
                                                        isOk = true;
                                                    }
                                                }
                                                else
                                                {
                                                    isOk = true;
                                                }
                                                stockNo[j] = sdt.Rows[0]["StockNo"].ToString();
                                                IsSame = sdt.Rows[0]["IsSame"].ToString();
                                                QLevel = sdt.Rows[0]["QLevel"].ToString();
                                                IsOne = sdt.Rows[0]["IsPrintOneTag"].ToString();
                                                PartName = sdt.Rows[0]["ProductName"].ToString();
                                                IsSupply = sdt.Rows[0]["IsSupply"].ToString();
                                                IsSend = sdt.Rows[0]["IsSend"].ToString();
                                            }
                                            else
                                            {
                                                stockNo[j] = "";
                                            }

                                            #endregion

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

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

                                                    #endregion

                                                    #region 直供件打印

                                                    if (IsSupply == "1")
                                                    {
                                                        DataTable dts = brbll.SearchInfoByPartNo1(partNo[j].ToString().Trim());
                                                        if (dts != null && dts.Rows.Count > 0)
                                                        {
                                                            code = dts.Rows[0]["BarCode"].ToString().Trim();
                                                            newcode = code.Substring(0, code.Length - 4) +
                                                                      (Convert.ToInt32(code.Substring(23, 3)) +
                                                                       1).ToString()
                                                                      .PadLeft(3, '0') + "#";
                                                        }
                                                        else
                                                        {
                                                            newcode = partNo[j].ToString().Trim() + "#" + QLevel + "#" +
                                                                      Program.ProductDate.Substring(2, 2) +
                                                                      Program.ProductDate.Substring(5, 2) +
                                                                      Program.ProductDate.Substring(8, 2) + "#" + "001" + "#";
                                                        }
                                                    }

                                                    #endregion

                                                    #region 拼接打印内容、获取零件批次信息

                                                    if (IsSend == "1")
                                                    {
                                                        DataTable dtPart =CommonTools.ListToDataTable(abll.SearchInfo());
                                                        if (dtPart != null && dtPart.Rows.Count > 0)
                                                        {
                                                            for (int l = 0; l < 2; l++)
                                                            {
                                                                des1 = dtPart.Rows[0]["BatchNo"].ToString();
                                                                des2 = dtPart.Rows[1]["BatchNo"].ToString();
                                                            }
                                                        }

                                                        if (IsOne == "1")
                                                        {
                                                            string fileName = "test";
                                                            string templatePath = "test.lbl";
                                                            string filePath = string.Format(templatePath,
                                                                Application.StartupPath, fileName);
                                                            string fileContent = string.Empty;
                                                            if (File.Exists(filePath))
                                                            {
                                                                fileContent = File.ReadAllText(filePath,
                                                                    Encoding.Default);
                                                            }
                                                            else
                                                            {
                                                                throw new Exception("找不到对应的文件。");
                                                            }

                                                            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


                                                            string finishedProduct = string.Format(fileContent, time,
                                                                NewOneCode, label6.Text, PartName, partNo[j]);
                                                            LabelPrint myLabelPrint = new LabelPrint();
                                                            //myLabelPrint.PrintLine(finishedProduct, "TCP", "");
                                                            myLabelPrint.PrintLine(finishedProduct, "COM1", "");
                                                        }
                                                        if (isOk)
                                                        {
                                                            opcItemm2[0].Write(1);
                                                        }
                                                        else
                                                        {
                                                            opcItemm2[1].Write(1);
                                                        }
                                                    }

                                                    #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].Trim();
                                                    md.PartNo = partNo[j].Trim();
                                                    md.PrintType = 0;
                                                    md.PlanID = planID;
                                                    md.ProductNature = ProductNature;
                                                    if (IsSend == "1")
                                                    {
                                                        md.Des1 = des1;
                                                        md.Des2 = des2;
                                                        md.Weight = weigth;
                                                    }


                                                    DataTable pdt = productBll.SearchIsImportByPartNo(partNo[j]);
                                                    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)
                                                    {
                                                        int a = 0;
                                                        for (int l = 0; l < 5; l++)
                                                        {
                                                            if (brbll.Add_Info_New(md, Program.tableName))
                                                            {
                                                                break;
                                                            }

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

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

                                                    #endregion

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

                                                    //if (IsSend != "1")
                                                    //{
                                                    //    #region 打印单个标签

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

                                                    //        DataTable headTable = new DataTable();
                                                    //        headTable.Columns.Add("PrintTime");
                                                    //        headTable.Columns.Add("PartNo");
                                                    //        headTable.Columns.Add("PartName");
                                                    //        headTable.Columns.Add("OneBarCode");
                                                    //        headTable.Columns.Add("BarCode");
                                                    //        DataRow row = headTable.NewRow();
                                                    //        row["PrintTime"] =
                                                    //            GetDateTime().ToString("yyyy/MM/dd HH:mm:ss");
                                                    //        row["PartNo"] = partNo[j].ToString().Trim();
                                                    //        row["PartName"] = PartName;
                                                    //        row["OneBarCode"] = NewOneCode;
                                                    //        row["BarCode"] = newcode;

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

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

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

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

                                                    //    }

                                                    //    #endregion
                                                    //}

                                                    #endregion

                                                    #region 插入质检结果

                                                    imd.BarCode = NewOneCode;;
                                                    imd.IsOK = isOk ? 1 : 0;
                                                    imd.Station = 1;

                                                    ibll.AddInfo(imd);

                                                    #endregion

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

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

                                                    #endregion
                                                }
                                                else
                                                {
                                                    #region 直供件

                                                    DataTable dts = brbll.SearchInfoByPartNo1(partNo[j].ToString().Trim());
                                                    if (dts != null && dts.Rows.Count > 0)
                                                    {
                                                        code = dt2.Rows[0]["BarCode"].ToString().Trim();
                                                        newcode = code.Substring(0, code.Length - 4) +
                                                                  (Convert.ToInt32(code.Substring(23, 3)) +
                                                                   1).ToString()
                                                                  .PadLeft(3, '0') + "#";
                                                    }
                                                    else
                                                    {
                                                        newcode = partNo[j].Trim() + "#" + QLevel + "#" +
                                                                  Program.ProductDate.Substring(2, 2) +
                                                                  Program.ProductDate.Substring(5, 2) +
                                                                  Program.ProductDate.Substring(8, 2) + "#" + "001" + "#";
                                                    }
                                                    #endregion
                                                }

                                                #region 给PLC发送条码内容、获取零件批次信息

                                                if (IsSend == "1")
                                                {
                                                    DataTable dtPart = CommonTools.ListToDataTable(abll.SearchInfo());
                                                    if (dtPart != null && dtPart.Rows.Count > 0)
                                                    {
                                                        for (int l = 0; l < 2; l++)
                                                        {
                                                            des1 = dtPart.Rows[0]["BatchNo"].ToString();
                                                            des2 = dtPart.Rows[1]["BatchNo"].ToString();
                                                        }
                                                    }

                                                    if (IsOne == "1")
                                                    {
                                                        string fileName = "test";
                                                        string templatePath = "test.lbl";
                                                        string filePath = string.Format(templatePath,
                                                            Application.StartupPath, fileName);
                                                        string fileContent = string.Empty;
                                                        if (File.Exists(filePath))
                                                        {
                                                            fileContent = File.ReadAllText(filePath,
                                                                Encoding.Default);
                                                        }
                                                        else
                                                        {
                                                            throw new Exception("找不到对应的文件。");
                                                        }

                                                        string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


                                                        string finishedProduct = string.Format(fileContent, time,
                                                            NewOneCode, label6.Text, PartName, partNo[j]);
                                                        LabelPrint myLabelPrint = new LabelPrint();
                                                        //myLabelPrint.PrintLine(finishedProduct, "TCP", "");
                                                        myLabelPrint.PrintLine(finishedProduct, "TCP", "");

                                                    }
                                                    if (isOk)
                                                    {
                                                        opcItemm2[0].Write(1);
                                                    }
                                                    else
                                                    {
                                                        opcItemm2[1].Write(1);
                                                    }
                                                }

                                                #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;
                                                if (IsSend == "1")
                                                {
                                                    md.Des1 = des1;
                                                    md.Des2 = des2;
                                                    md.Weight = weigth;
                                                }

                                                DataTable pdt = productBll.SearchIsImportByPartNo(partNo[j]);
                                                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)
                                                {
                                                    int a = 0;
                                                    for (int l = 0; l < 5; l++)
                                                    {
                                                        if (brbll.Add_Info_New(md, Program.tableName))
                                                        {
                                                            break;
                                                        }

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

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

                                                #endregion

                                                if (IsSend != "1")
                                                {
                                                    #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();
                                                        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 +
                                                                  "单个条码.grf";
                                                        }
                                                        else
                                                        {
                                                            filename = System.AppDomain.CurrentDomain.BaseDirectory +
                                                                       "单个条码1.grf";
                                                        }

                                                        DataTable headTable = new DataTable();
                                                        headTable.Columns.Add("PrintTime");
                                                        headTable.Columns.Add("PartNo");
                                                        headTable.Columns.Add("PartName");
                                                        headTable.Columns.Add("OneBarCode");
                                                        headTable.Columns.Add("BarCode");
                                                        DataRow row = headTable.NewRow();
                                                        row["PrintTime"] =
                                                            GetDateTime().ToString("yyyy/MM/dd HH:mm:ss");
                                                        row["PartNo"] = partNo[j].ToString().Trim();
                                                        row["PartName"] = PartName;
                                                        row["OneBarCode"] = NewOneCode;
                                                        row["BarCode"] = newcode;

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

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

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

                                                    }

                                                    #endregion

                                                    #endregion
                                                }

                                                #region 插入质检结果

                                                imd.BarCode = NewOneCode;
                                                imd.IsOK = isOk ? 1 : 0;
                                                imd.Station = 1;

                                                ibll.AddInfo(imd);

                                                #endregion

                                                initBarCode();
                                            }
                                        }

                                        #endregion
                                    }
                                    else
                                    {
                                        return;
                                    }
                                }
                                else
                                {
                                    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 判断有几个零件号

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

                                        DataTable sdt = productBll.SearchInfoByPartNo(partNo[j].ToString().Trim());
                                        if (sdt != null && sdt.Rows.Count > 0)
                                        {
                                            partId = sdt.Rows[0]["ProductID"].ToString();
                                            DataTable dtw =
                                                CommonTools.ListToDataTable(wbll.SearchWeightById(partId));
                                            if (dtw != null && dtw.Rows.Count > 0)
                                            {
                                                min_weight = Convert.ToDecimal(dtw.Rows[0]["LowerWeight"]);
                                                max_weight = Convert.ToDecimal(dtw.Rows[0]["UpperWeight"]);
                                            }
                                            if (ConfigurationManager.AppSettings["IsWeight"] == "1")
                                            {
                                                if (min_weight <= weigth && weigth <= max_weight)
                                                {
                                                    isOk = true;
                                                }
                                            }
                                            else
                                            {
                                                isOk = true;
                                            }
                                            stockNo[j] = sdt.Rows[0]["StockNo"].ToString();
                                            IsSame = sdt.Rows[0]["IsSame"].ToString();
                                            QLevel = sdt.Rows[0]["QLevel"].ToString();
                                            IsOne = sdt.Rows[0]["IsPrintOneTag"].ToString();
                                            IsPack = sdt.Rows[0]["IsPrintPackList"].ToString();
                                            IsPaint = sdt.Rows[0]["IsPlating"].ToString();
                                            PartName = sdt.Rows[0]["ProductName"].ToString();
                                            //MaxCount = Convert.ToInt32(dt10.Rows[0]["PackCount"].ToString());
                                            IsSupply = sdt.Rows[0]["IsSupply"].ToString();
                                            IsSend = sdt.Rows[0]["IsSend"].ToString();
                                        }
                                        else
                                        {
                                            stockNo[j] = "";
                                        }

                                        #endregion

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

                                                    try
                                                    {
                                                        dt2 = brbll.SearchInfoByPartNo(partNo[j].ToString().Trim());
                                                        if (dt2 != null && dt2.Rows.Count > 0)
                                                        {
                                                            code = dt2.Rows[0]["BarCode"].ToString().Trim();
                                                            newcode = code.Substring(0, code.Length - 4) +
                                                                      (Convert.ToInt32(code.Substring(code.Length - 4,
                                                                           4)) + 1)
                                                                      .ToString()
                                                                      .PadLeft(4, '0');
                                                            OneCode = dt2.Rows[0]["OneBarCode"].ToString().Trim();
                                                            NewOneCode =
                                                                OneCode.Substring(0, OneCode.Length - 4) +
                                                                (Convert.ToInt32(OneCode.Substring(OneCode.Length - 4,
                                                                     4)) + 1)
                                                                .ToString().PadLeft(4, '0');
                                                        }
                                                        else
                                                        {
                                                            newcode = partNo[j].ToString().Trim() + "." +
                                                                      Program.ProductDate.Substring(2, 2) +
                                                                      Program.ProductDate.Substring(5, 2) +
                                                                      Program.ProductDate.Substring(8, 2) + "." +
                                                                      "0001";
                                                            NewOneCode =
                                                                stockNo[j].ToString().Trim() +
                                                                Program.ProductDate.Substring(2, 2) +
                                                                Program.ProductDate.Substring(5, 2) +
                                                                Program.ProductDate.Substring(8, 2) + "0001";
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        MessageBox.Show(ex.ToString());
                                                        LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                                                        return;
                                                    }

                                                    #endregion
                                                }
                                                else
                                                {
                                                    #region 直供件

                                                    try
                                                    {
                                                        DataTable dts = brbll.SearchInfoByPartNo1(partNo[j].ToString().Trim());
                                                        if (dts != null && dts.Rows.Count > 0)
                                                        {
                                                            code = dt2.Rows[0]["BarCode"].ToString().Trim();
                                                            newcode = code.Substring(0, code.Length - 4) +
                                                                      (Convert.ToInt32(code.Substring(23, 3)) +
                                                                       1).ToString()
                                                                      .PadLeft(3, '0') + "#";
                                                        }
                                                        else
                                                        {
                                                            newcode = partNo[j].ToString().Trim() + "#" + QLevel + "#" +
                                                                      Program.ProductDate.Substring(2, 2) +
                                                                      Program.ProductDate.Substring(5, 2) +
                                                                      Program.ProductDate.Substring(8, 2) + "#" + "001" + "#";
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        MessageBox.Show(ex.ToString());
                                                        LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                                                        return;
                                                    }

                                                    #endregion
                                                }

                                                #region 给PLC发送条码内容、获取零件批次信息

                                                if (IsSend == "1")
                                                {
                                                    DataTable dtPart = CommonTools.ListToDataTable(abll.SearchInfo());
                                                    if (dtPart != null && dtPart.Rows.Count > 0)
                                                    {
                                                        for (int l = 0; l < 2; l++)
                                                        {
                                                            des1 = dtPart.Rows[0]["BatchNo"].ToString();
                                                            des2 = dtPart.Rows[1]["BatchNo"].ToString();
                                                        }
                                                    }

                                                    if (IsOne == "1")
                                                    {
                                                        string fileName = "test";
                                                        string templatePath = "test.lbl";
                                                        string filePath = string.Format(templatePath,
                                                            Application.StartupPath, fileName);
                                                        string fileContent = string.Empty;
                                                        if (File.Exists(filePath))
                                                        {
                                                            fileContent = File.ReadAllText(filePath,
                                                                Encoding.Default);
                                                        }
                                                        else
                                                        {
                                                            throw new Exception("找不到对应的文件。");
                                                        }

                                                        string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


                                                        string finishedProduct = string.Format(fileContent, time,
                                                            label6.Text, partNo[j], "V214", PartName, NewOneCode);
                                                        LabelPrint myLabelPrint = new LabelPrint();
                                                        myLabelPrint.PrintLine(finishedProduct, "COM1", "");
                                                    }

                                                    if (isOk)
                                                    {
                                                        opcItemm2[0].Write(1);
                                                    }
                                                    else
                                                    {
                                                        opcItemm2[1].Write(1);
                                                    }
                                                }

                                                #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;
                                                if (IsSend == "1")
                                                {
                                                    md.Des1 = des1;
                                                    md.Des2 = des2;
                                                    md.Weight = weigth;
                                                }

                                                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)
                                                {
                                                    int a = 0;
                                                    for (int l = 0; l < 5; l++)
                                                    {
                                                        if (brbll.Add_Info_New(md, Program.tableName))
                                                        {
                                                            break;
                                                        }

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

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

                                                #endregion

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

                                                if (IsSend != "1")
                                                {
                                                    #region 打印单个标签

                                                    if (IsOne == "1")
                                                    {
                                                        if (IsSupply != "1")
                                                        {
                                                            filename = ManufacturerName.Contains("蔚来")
                                                                ? System.AppDomain.CurrentDomain.BaseDirectory +
                                                                  "wl.grf"
                                                                : System.AppDomain.CurrentDomain.BaseDirectory +
                                                                  "单个条码.grf";
                                                        }
                                                        else
                                                        {
                                                            filename = System.AppDomain.CurrentDomain.BaseDirectory +
                                                                       "单个条码1.grf";
                                                        }

                                                        DataTable headTable = new DataTable();
                                                        headTable.Columns.Add("PrintTime");
                                                        headTable.Columns.Add("PartNo");
                                                        headTable.Columns.Add("PartName");
                                                        headTable.Columns.Add("OneBarCode");
                                                        headTable.Columns.Add("BarCode");
                                                        DataRow row = headTable.NewRow();
                                                        row["PrintTime"] =
                                                            GetDateTime().ToString("yyyy/MM/dd HH:mm:ss");
                                                        row["PartNo"] = partNo[j].ToString().Trim();
                                                        row["PartName"] = PartName;
                                                        row["OneBarCode"] = NewOneCode;
                                                        row["BarCode"] = newcode;

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

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

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

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

                                                    }

                                                    #endregion
                                                }

                                                #endregion

                                                #region 插入质检结果

                                                imd.BarCode = NewOneCode;
                                                imd.IsOK = isOk ? 1 : 0;
                                                imd.Station = 1;

                                                ibll.AddInfo(imd);

                                                #endregion

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

                                                try
                                                {
                                                    dt2 = brbll.SearchInfoByPartNo(partNo[j].ToString().Trim());
                                                    if (dt2 != null && dt2.Rows.Count > 0)
                                                    {
                                                        code = dt2.Rows[0]["BarCode"].ToString().Trim();
                                                        newcode = code.Substring(0, code.Length - 4) +
                                                                  (Convert.ToInt32(code.Substring(code.Length - 4, 4)) +
                                                                   1)
                                                                  .ToString()
                                                                  .PadLeft(4, '0');
                                                        OneCode = dt2.Rows[0]["OneBarCode"].ToString().Trim();
                                                        NewOneCode =
                                                            OneCode.Substring(0, OneCode.Length - 4) +
                                                            (Convert.ToInt32(OneCode.Substring(OneCode.Length - 4, 4)) +
                                                             1)
                                                            .ToString().PadLeft(4, '0');
                                                    }
                                                    else
                                                    {
                                                        newcode = partNo[j].Trim() + "." +
                                                                  Program.ProductDate.Substring(2, 2) +
                                                                  Program.ProductDate.Substring(5, 2) +
                                                                  Program.ProductDate.Substring(8, 2) + "." + "0001";
                                                        NewOneCode =
                                                            stockNo[j].Trim() +
                                                            Program.ProductDate.Substring(2, 2) +
                                                            Program.ProductDate.Substring(5, 2) +
                                                            Program.ProductDate.Substring(8, 2) + "0001";
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    MessageBox.Show(ex.ToString());
                                                    LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                                                    return;
                                                }

                                                #endregion
                                            }
                                            else
                                            {
                                                #region 直供件

                                                try
                                                {
                                                    DataTable dts = brbll.SearchInfoByPartNo1(partNo[j].ToString().Trim());
                                                    if (dts != null && dts.Rows.Count > 0)
                                                    {
                                                        code = dts.Rows[0]["BarCode"].ToString().Trim();
                                                        newcode = code.Substring(0, code.Length - 4) +
                                                                  (Convert.ToInt32(code.Substring(23, 3)) +
                                                                   1).ToString()
                                                                  .PadLeft(3, '0') + "#";
                                                    }
                                                    else
                                                    {
                                                        newcode = partNo[j].ToString().Trim() + "#" + QLevel + "#" +
                                                                  Program.ProductDate.Substring(2, 2) +
                                                                  Program.ProductDate.Substring(5, 2) +
                                                                  Program.ProductDate.Substring(8, 2) + "#" + "001" + "#";
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    MessageBox.Show(ex.ToString());
                                                    LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                                                    return;
                                                }

                                                #endregion
                                            }

                                            #region 给PLC发送条码内容、获取零件批次信息

                                            if (IsSend == "1")
                                            {
                                                DataTable dtPart = CommonTools.ListToDataTable(abll.SearchInfo());
                                                if (dtPart != null && dtPart.Rows.Count > 0)
                                                {
                                                    for (int l = 0; l < 2; l++)
                                                    {
                                                        des1 = dtPart.Rows[0]["BatchNo"].ToString();
                                                        des2 = dtPart.Rows[1]["BatchNo"].ToString();
                                                    }
                                                }

                                                if (IsOne == "1")
                                                {
                                                    string fileName = "test";
                                                    string templatePath = "test.lbl";
                                                    string filePath = string.Format(templatePath,
                                                        Application.StartupPath, fileName);
                                                    string fileContent = string.Empty;
                                                    if (File.Exists(filePath))
                                                    {
                                                        fileContent = File.ReadAllText(filePath,
                                                            Encoding.Default);
                                                    }
                                                    else
                                                    {
                                                        throw new Exception("找不到对应的文件。");
                                                    }

                                                    string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


                                                    //string finishedProduct = string.Format(fileContent, time,
                                                    //    label6.Text, partNo[j], "V214", PartName, NewOneCode);
                                                    string finishedProduct = string.Format(fileContent, time,
                                                        NewOneCode, label6.Text, PartName, partNo[j]);
                                                    
                                                    LabelPrint myLabelPrint = new LabelPrint();
                                                    myLabelPrint.PrintLine(finishedProduct, "COM1", "");
                                                    //myLabelPrint.PrintLine(finishedProduct, "TCP", "");
                                                }

                                                if (isOk)
                                                {
                                                    opcItemm2[0].Write(1);
                                                }
                                                else
                                                {
                                                    opcItemm2[1].Write(1);
                                                }

                                            }

                                            #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;
                                            if (IsSend == "1")
                                            {
                                                md.Des1 = des1;
                                                md.Des2 = des2;
                                                md.Weight = weigth;
                                            }

                                            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)
                                            {
                                                int a = 0;
                                                for (int l = 0; l < 5; l++)
                                                {
                                                    if (brbll.Add_Info_New(md, Program.tableName))
                                                    {
                                                        break;
                                                    }

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

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

                                            #endregion

                                            #region 插入质检结果

                                            imd.BarCode = NewOneCode;
                                            imd.IsOK = isOk ? 1 : 0;
                                            imd.Station = 1;

                                            ibll.AddInfo(imd);

                                            #endregion

                                            initBarCode();
                                        }
                                    }

                                    #endregion
                                }

                            }

                            #endregion
                        }
                    }

                    #endregion

                    #region 条码复读完成,读取条码和数据库中一个条码对比,匹配发1,不匹配发0 ,不需要对比条码,暂时取消

                    //if (handle == 2)
                    //{
                    //    if (value == "1" || value.ToLower() == "true")
                    //    {
                    //        string barCode1 = ReadSingleValueFromOPC(opcItemm1, 3).ToString();

                    //        if (brbll.LastBarCode(Program.tableName) != barCode1)
                    //        {
                    //            opcItemm2[4].Write(1);
                    //        }
                    //        else
                    //        {
                    //            opcItemm2[4].Write(0);
                    //        }
                    //        opcItemm2[5].Write(1);
                    //    }
                    //}

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

        public object ReadSingleValueFromOPC(OPCItem[] item, int i)
        {
            object ItemValues;
            object Qualities;
            object TimeStamps;

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

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

        private void label14_Click(object sender, EventArgs e)
        {
            try
            {
                InjectionPlanBLL planbll = new InjectionPlanBLL();

                #region 查询有无下一计划

                DataTable dt = planbll.NextSearchInfoByName(Program.station);
                if (dt != null && dt.Rows.Count > 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());
            }
        }

        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 更新上一计划为完成

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

                            #endregion

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

                    }
                    else
                    {
                        return;
                    }

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

                #endregion

                panel45.Visible = false;
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

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

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

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

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

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

                            md.PrintType = 2;

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

                                IsSend = pdt.Rows[0]["IsSend"].ToString();
                                partName = pdt.Rows[0]["ProductName"].ToString();
                            }
                        }

                        if (bll.Add_Info_New(md, Program.tableName) == false)
                        {
                            return;
                        }
                        glacialList1.SelectedItems.Clear();
                        initBarCode();

                        if (IsSend == "1")
                        {

                            opcItemm2[0].Write(md.PartNo); //零件号
                            opcItemm2[1].Write(partName); //零件名称
                            opcItemm2[2].Write(md.OneBarCode); //条码号

                        }
                        else
                        {
                            #region 打印条码

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

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

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

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

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

                            ReportHelper rp = new ReportHelper(filename, headTable, null,
                                (int)GRPaperOrientation.grpoDefault, 1, reportName);
                            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());
            }
        }

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

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

        private void label9_Click(object sender, EventArgs e)
        {
            Form fr = new FrmQuality();
            fr.Show();
        }

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

        private void label10_Click(object sender, EventArgs e)
        {
            try
            {
                InjectionPlanBLL planbll = new InjectionPlanBLL();
                InjectionPlanModel md = new InjectionPlanModel();

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

                    md.InjectionPlanID = planID;
                    planbll.UpdateFinish(md);
                    InitPlan();
                }
                else
                {
                    MessageBox.Show("暂无下一计划,请联系计划员!", "提示", MessageBoxButtons.OK);
                    return;
                }

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