using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using gregn6Lib;
using MESClassLibrary.BLL.Log;
using MESClassLibrary.BLL.PunchAndWeld;
using OPCAutomation;
using PunchAndWeld.DataSouce;
using static System.Windows.Forms.AxHost;

namespace PunchAndWeld
{
    public partial class FrmHybridS : Form
    {
        private string oneBarCode = "";
        private string productID2 = "";
        private string barcode = "";
        private string productID = "";
        string zcPartNo = "", productName="";
        private GridppReport Report = new GridppReport();
        string stationNo = "", stationId = "";
        OPCHelper opcHelper = new OPCHelper();
        private string strHostIP = "";
        PunchAdressBLL bll = new PunchAdressBLL();

        int heartFlag = 0;

        string lbState = "";

        public FrmHybridS()
        {
            InitializeComponent();
        }

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

            label5.Text = "当前版本:" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            stationNo = ConfigurationManager.AppSettings["StationNo"].ToString();
            stationId = ProScreenFunc.GetStationId(stationNo);
            label1.Text = ProScreenFunc.GetStation(stationNo);

            Control.CheckForIllegalCrossThreadCalls = false;

            LoadScreen();

            if (stationNo == "ZP77")
            {
                button1.Visible = false;
                button2.Visible = false;

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

                            opcHelper.opcGroups = opcHelper.opcServer.OPCGroups;
                            opcHelper.opcGroup1 = opcHelper.opcGroups.Add("DeviceRead");
                            opcHelper.opcGroup2 = opcHelper.opcGroups.Add("DeviceWrite");
                            opcHelper.SetGroupProperty(opcHelper.opcGroup1, 500);
                            opcHelper.SetGroupProperty(opcHelper.opcGroup2, 500);
                            opcHelper.opcItems1 = opcHelper.opcGroup1.OPCItems;
                            opcHelper.opcItems1.DefaultIsActive = true;

                            DataTable dt = bll.SearchInfo(ConfigurationManager.AppSettings["DeviceNo"], 0);

                            if (dt != null && dt.Rows.Count > 0)
                            {
                                opcHelper.opcItemm1 = new OPCItem[dt.Rows.Count];
                                for (int i = 0; i < dt.Rows.Count; i++)
                                {
                                    opcHelper.opcItemm1[i] = opcHelper.opcItems1.AddItem(dt.Rows[i]["Address"].ToString(), i);
                                }
                            }

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

                            DataTable dt1 = bll.SearchInfo(ConfigurationManager.AppSettings["DeviceNo"], 1);
                            if (dt1 != null && dt1.Rows.Count > 0)
                            {
                                opcHelper.opcItemm2 = new OPCItem[dt1.Rows.Count+1];
                                opcHelper.opcItemm2[0] = opcHelper.opcItems2.AddItem("BBMPT.Punch167.Heart", 0);

                                for (int i = 1; i < dt1.Rows.Count+1; i++)
                                {
                                    opcHelper.opcItemm2[i] = opcHelper.opcItems2.AddItem(dt1.Rows[i-1]["Address"].ToString(), i);
                                }
                                
                            }
                            if (opcHelper.ReadSingleValueFromOPC1(2).ToLower() == "true")
                            {
                                lbState = "等待放件状态";
                            }
                            else
                            {
                                lbState = "设备未准备OK";
                            }

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

                        }
                    }
                    else
                    {
                        MessageBox.Show("创建OPC服务失败!", "提示", MessageBoxButtons.OK);
                        opcHelper.Connected = false;
                        LogHelper.WriteErrLogBase("工位:" + label1.Text + "创建OPC服务失败!", MethodBase.GetCurrentMethod().Name);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrLogBase(ex.ToString(), MethodBase.GetCurrentMethod().Name);
                }
            }

            Thread t = new Thread(new ThreadStart(TimeGo));
            t.Start();

            textBox1.TabIndex = 0;
            textBox1.Select();

            timer1.Enabled = true;
        }

        void opcGroup1_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps)
        {
            try
            {
                for (int i = 1; i <= NumItems; i++)
                {
                    int handle = Convert.ToInt32(ClientHandles.GetValue(i).ToString().Trim());
                    string value = ItemValues.GetValue(i).ToString();
                    string address = opcHelper.opcItemm1[(Convert.ToInt32(ClientHandles.GetValue(i)))].ItemID;



                    if (handle == 2)
                    {
                        if (value == "1" || value.ToUpper() == "TRUE")
                        {
                            lbState = "等待放件状态";
                        }
                        else
                        {
                            lbState = "设备未准备OK";
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase(ex.ToString(), MethodBase.GetCurrentMethod().Name);
            }
        }

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

        private void timer_Tick(object sender, EventArgs e)
        {
            label9.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            if (opcHelper.opcItemm2 == null || opcHelper.opcItemm2.Count() == 0) return;
            if (heartFlag == 0)
            {
                opcHelper.opcItemm2[0].Write(0);
                heartFlag = 1;
            }
            else 
            {
                opcHelper.opcItemm2[0].Write(1);
                heartFlag = 0;
            }

            Thread.Sleep(500);
        }

        public void LoadScreen()
        {
            //string stationNo = ConfigurationManager.AppSettings["StationNo"].ToString();

            DataTable dt = ProScreenFunc.GetProScreen(stationNo);
            if (dt != null && dt.Rows.Count > 0)
            {
                SetPage(dt);
            }
        }

        public void SetPage(DataTable dt)
        {
            textBox2.Text = "";
            textBox2.Visible = false;
            textBox3.Text = "";
            textBox3.Visible = false;
            textBox4.Text = "";
            textBox4.Visible = false;

            textBox5.Text = "";
            textBox5.Visible = false;

            if (dt != null && dt.Rows.Count > 0)
            {
                #region 页面赋值

                label1.Text = dt.Rows[0]["Des"].ToString();
                label2.Text = dt.Rows[0]["OrderNo"].ToString();
                label3.Text = dt.Rows[0]["PartNo"].ToString();
                label4.Text = dt.Rows[0]["ProductName"].ToString();
                //label5.Text = dt.Rows[0]["Des"].ToString();
                label6.Text = dt.Rows[0]["OrderCount"].ToString();
                label7.Text = dt.Rows[0]["CompleteCount"].ToString();
                label8.Text = dt.Rows[0]["OrderNo"].ToString().Substring(0, 1) + "班";
                label10.Text = dt.Rows[0]["BadCount"].ToString();

                this.Tag = dt.Rows[0]["ID"].ToString(); //计划ID
                textBox1.Tag = dt.Rows[0]["ProductID1"].ToString();
                textBox1.Text = "";

                #endregion
            }
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (ConfigurationManager.AppSettings["StationNo"] == "ZP77")
                {
                    if (string.IsNullOrWhiteSpace(lbState) || lbState.Contains("未"))
                    {
                        MessageBox.Show("设备未准备OK");
                        return;
                    }
                    CheckPartAndProduct_1();
                }
                else
                {
                    CheckPartAndProduct();
                }
            }
        }

        private void CheckPartAndProduct_1()
        {
            textBox1.SelectAll();
            barcode = textBox1.Text.Trim();

            if (barcode.Contains("."))
            {
                barcode = ProScreenFunc.UniteBarCodeToOne(barcode);
            }

            if (ProScreenFunc.SjBarCodeIsInStockIn(barcode) == false)
            {
                MessageBox.Show($"扫描条码[{barcode}]不存在喷涂下线记录,请更换其他油漆件重新操作!");
                textBox1.Text = "";
                return;
            }


           

            if (ProScreenFunc.HaveScan(barcode))
            {
                if (ProScreenFunc.IsBad(barcode))
                {
                    MessageBox.Show("条码为" + barcode + "的蒙皮为不良品,请操作不良转合格!");
                    textBox1.SelectAll();
                    return;
                }

                string[] aa = ProScreenFunc.GetSpecialHybrid();
                string[] bb = ProScreenFunc.StockZcCode(barcode).Split('-');
                if (aa.Count(p => p == bb[0]) != 0)
                {
                    DialogResult result1 = MessageBox.Show("条码为" + barcode + "的蒙皮已经铣孔,是否重新铣孔?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    if (result1 == DialogResult.OK)
                    {
                        FrmPassWord pass = new FrmPassWord();
                        pass.OkBtnClick += (arg1) =>
                        {
                            if (!string.IsNullOrEmpty(arg1) &&
                                arg1.ToLower() == ConfigurationManager.AppSettings["password"].ToLower())
                            {
                                pass.Close();
                                textBox4.Visible = true;
                                textBox4.Focus();
                            }
                            else
                            {
                                MessageBox.Show("密码错误,请重新输入!", "提示", MessageBoxButtons.OK);
                            }
                        };
                        pass.ShowDialog();
                    }
                }
                else
                {
                    textBox4.Visible = true;
                    textBox4.Focus();
                }
            }
            else
            {
                textBox4.Visible = true;
                textBox4.Focus();
            }
        }

        public void CheckPartAndProduct()
        {
            textBox1.SelectAll();
            barcode = textBox1.Text.Trim();

          

            if (!ProScreenFunc.CanScan(this.Tag.ToString().Trim()))
            {
                MessageBox.Show("完成数量等于计划数量,不允许扫描!");
                textBox1.SelectAll();
                return;
            }


            if (barcode.Contains("."))
            {
                barcode = ProScreenFunc.UniteBarCodeToOne(barcode);
            }

            if (ProScreenFunc.SjBarCodeIsInStockIn(barcode) == false)
            {
                MessageBox.Show($"扫描条码[{barcode}]不存在喷涂下线记录,请更换其他油漆件重新操作!");
                textBox1.Text = "";
                return;
            }

            if (ProScreenFunc.HaveScan(barcode))
            {
                if (ProScreenFunc.IsBad(barcode))
                {
                    MessageBox.Show("条码为" + barcode + "的蒙皮为不良品,请操作不良转合格!");
                    textBox1.SelectAll();
                    return;
                }

                DialogResult result = MessageBox.Show("条码为" + barcode + "的蒙皮已经装配,是否重新装配?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    FrmPassWord pass = new FrmPassWord();
                    pass.OkBtnClick += (arg1) =>
                    {
                        if (!string.IsNullOrEmpty(arg1) &&
                            arg1.ToLower() == ConfigurationManager.AppSettings["password"].ToLower())
                        {
                            pass.Close();

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

        }


        private void ScanBarcode(string barcode)
        {
            productID = this.textBox1.Tag.ToString().Trim();
            string[] codeSpecial = ProScreenFunc.GetSpecialStockNo();
            string code = barcode.Substring(0, 10);
            if (codeSpecial.Contains(code) && !ProScreenFunc.HaveInspect(barcode) && ProScreenFunc.IsFBC(code, this.label3.Text.Trim()))
            {
                if (ProScreenFunc.HaveScan(barcode))
                {
                    productID2 = ProScreenFunc.GetProductID(barcode);
                    if (!ProScreenFunc.CheckPartAndProduct(productID, productID2))
                    {
                        this.InsLog(productID, productID2);
                        MessageBox.Show("当前扫描的零件与总成不匹配,请检查后再扫描");
                        this.textBox1.Text = "";
                    }
                    else
                    {
                        textBox4.Visible = true;
                        textBox4.Focus();
                    }
                }
                else
                {
                    textBox4.Visible = true;
                    textBox4.Focus();
                    productID2 = ProScreenFunc.GetProductID(code, "");
                }
            }
            else
            {
                productID2 = ProScreenFunc.GetProductID(barcode);
                if (string.IsNullOrWhiteSpace(productID2))
                {
                    string stockNo = barcode.Substring(0, 10);
                    productID2 = ProScreenFunc.GetProductID(stockNo, "");
                }
                if (!ProScreenFunc.CheckPartAndProduct(productID, productID2))
                {
                    this.InsLog(productID, productID2);
                    MessageBox.Show("当前扫描的零件与总成不匹配,请检查后再扫描");
                    this.textBox1.Text = "";
                }
                else
                {
                    ScanAll.ScanResult = false;
                    OtherPart parts = ProScreenFunc.HaveOtherPart(this.label1.Text.Trim(), productID);
                    if (parts != null && (!string.IsNullOrWhiteSpace(parts.productID3) || !string.IsNullOrWhiteSpace(parts.productID4) || !string.IsNullOrWhiteSpace(parts.productID5)))
                    {
                        FrmProScreen3 frm3 = new FrmProScreen3(parts);
                        frm3.ShowDialog();
                    }
                    else
                    {
                        ScanAll.ScanResult = true;
                    }
                    if (ScanAll.ScanResult)
                    {
                        textBox4.Visible = true;
                        textBox4.Focus();
                    }
                }
            }
        }


        public void InsLog(string productID1, string productID2)
        {
            LogHelper.WriteSysLogBase("一码到底【当前扫描的零件与总成不匹配】:productID1:" + productID1 + ",productID2:" + productID2 + ",工位:" + label1.Text + ",计划ID:" + this.Tag.ToString(), MethodBase.GetCurrentMethod().Name);
        }

        private void AfterScanBarcode(string barcode, string productID2, string productID1, string planID,string stationId)
        {
            try
            {
                string stockNo = "";
                string batchNo = "";
                string partNo = "";
                ProScreenFunc.GetCode(barcode, out stockNo, out batchNo, out partNo);

                partNo = label3.Text.Trim();
                batchNo = ProScreenFunc.GetPlanTime(planID).ToString("yyyyMMdd");

                DateTime time = DateTime.Now;
                string tmp = ProScreenFunc.SerialNo(label3.Text.Trim(), time.ToString("yyMMdd"));
                string sn = "";
                if (tmp == "")
                {
                    sn =
                        label3.Text.Trim() + "." + time.ToString("yyMMdd") + ".000001";
                }
                else
                {
                    sn = tmp.Substring(0, tmp.Length - 6) +
                         (int.Parse(tmp.Substring(tmp.Length - 6, 6)) + 1).ToString()
                         .PadLeft(6, '0');
                }

                ProScreenFunc.SavePartAndProduct1(barcode, productID2, productID1, label2.Text, label8.Text, planID, sn, stationId, ConfigurationManager.AppSettings["StationDescription"]);
                ProScreenFunc.SaveZcCode(barcode, label3.Text.Trim());
                ProScreenFunc.AddCompleteCount(this.Tag.ToString().Trim());


                if (ProScreenFunc.CheckPlanCompleted(this.Tag.ToString().Trim()))
                {
                    LoadScreen();
                }
                else
                {
                    label7.Text = ProScreenFunc.GetCompleteCount(this.Tag.ToString().Trim());
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        private void AfterScanBarCode_1(string barCode)
        {
            try
            {
                string  productId1="", productId2 = "";


                if ((barCode.Substring(0, 10) == "2200000172" || barCode.Substring(0, 10) == "2200000174" || barCode.Substring(0, 10) == "2200000176") && !string.IsNullOrEmpty(ProScreenFunc.StockZcCode(barcode)))  
                {
                     string tmpZc = ProScreenFunc.StockZcCode(barcode);

                        string[] aa = ProScreenFunc.GetSpecialHybrid();
                        string[] bb = tmpZc.Split('-');
                        if (aa.Count(p => p == bb[0]) != 0)  
                        {
                            productId2 = ProScreenFunc.GetProductID(barCode);
                        }
                        else
                        {
                            productId2 = ProScreenFunc.GetProductIDByPartNo(tmpZc);
                        }
                        string stationId = ProScreenFunc.GetStationId(ConfigurationManager.AppSettings["StationNo"]);
                        DataTable dt = ProScreenFunc.GetProductInfo1(productId2, stationId);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            productId1 = dt.Rows[0]["ProductID1"].ToString();
                            zcPartNo = dt.Rows[0]["PartNo"].ToString();
                            productName = dt.Rows[0]["ProductName"].ToString();

                            DateTime time = DateTime.Now;
                            string tmp = ProScreenFunc.SerialNo(zcPartNo, time.ToString("yyMMdd"));
                            string sn = "";
                            if (tmp == "")
                            {
                                sn =
                                    zcPartNo + "." + time.ToString("yyMMdd") + ".000001";
                            }
                            else
                            {
                                sn = tmp.Substring(0, tmp.Length - 6) +
                                     (int.Parse(tmp.Substring(tmp.Length - 6, 6)) + 1).ToString()
                                     .PadLeft(6, '0');
                            }

                            if (ProScreenFunc.SavePartAndProduct1(barcode, productID2, productId1, "", "", "", sn,stationId, ConfigurationManager.AppSettings["StationDescription"]) <=0)
                            {
                                MessageBox.Show("连接数据库失败!");
                                return;
                            }
                            ProScreenFunc.SaveZcCode(barcode, zcPartNo);

                            if (ConfigurationManager.AppSettings["PrintEnable"].ToLower() == "true")
                            {
                                string path = Application.StartupPath + @"\aaa.grf";
                                Report.Initialize += new _IGridppReportEvents_InitializeEventHandler(ReportInitialize_New);
                                Report.Register("");
                                Report.LoadFromFile(path);

                                Report.Print(false);
                            }

                            textBox1.Text = "";
                            textBox1.Focus();
                        }
                        else
                        {
                            MessageBox.Show("当前扫描的零件未设置对应的总成,请检查后再扫描");
                            textBox1.SelectAll();
                            textBox1.Focus();
                        }
                }
                else
                {
                    productId2 = ProScreenFunc.GetProductID(barCode);
                    string stationId = ProScreenFunc.GetStationId(ConfigurationManager.AppSettings["StationNo"]);
                    DataTable dt = ProScreenFunc.GetProductInfo1(productId2, stationId);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        productId1 = dt.Rows[0]["ProductID1"].ToString();
                        zcPartNo = dt.Rows[0]["PartNo"].ToString();
                        productName = dt.Rows[0]["ProductName"].ToString();

                        DateTime time = DateTime.Now;
                        string tmp = ProScreenFunc.SerialNo(zcPartNo, time.ToString("yyMMdd"));
                        string sn = "";
                        if (tmp == "")
                        {
                            sn =
                                zcPartNo + "." + time.ToString("yyMMdd") + ".000001";
                        }
                        else
                        {
                            sn = tmp.Substring(0, tmp.Length - 6) +
                                 (int.Parse(tmp.Substring(tmp.Length - 6, 6)) + 1).ToString()
                                 .PadLeft(6, '0');
                        }

                        if (ProScreenFunc.SavePartAndProduct1(barcode, productID2, productId1, "", "", "", sn, stationId, ConfigurationManager.AppSettings["StationDescription"]) <=0)
                        {
                            MessageBox.Show("连接数据库失败!");
                            return;
                        }
                        ProScreenFunc.SaveZcCode(barcode, zcPartNo);

                        if (ConfigurationManager.AppSettings["PrintEnable"].ToLower() == "true")
                        {
                            string path = Application.StartupPath + @"\aaa.grf";
                            Report.Initialize += new _IGridppReportEvents_InitializeEventHandler(ReportInitialize_New);
                            Report.Register("");
                            Report.LoadFromFile(path);

                            Report.Print(false);
                        }

                        textBox1.Text = "";
                        textBox1.Focus();
                    }
                    else
                    {
                        MessageBox.Show("当前扫描的零件未设置对应的总成,请检查后再扫描");
                        textBox1.SelectAll();
                        textBox1.Focus();
                    }
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        private void ReportInitialize_New()
        {
            Report.ParameterByName("oneBarCode").Value = barcode;
            Report.ParameterByName("zcPartNo").Value = zcPartNo;
            Report.ParameterByName("zcName").Value = productName;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (this.Tag.ToString() == "")
            {
                MessageBox.Show("无上一计划!", "提示");
            }
            else
            {
                LoadPlanScreen(this.Tag.ToString(), "上一计划");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (this.Tag.ToString() == "")
            {
                MessageBox.Show("无下一计划!", "提示");
            }
            else
            {
                LoadPlanScreen(this.Tag.ToString(), "下一计划");
            }
        }

        public void LoadPlanScreen(string id, string plan)
        {

            DataTable dt = ProScreenFunc.GetProScreenPlan(id, stationNo, plan);
            if (dt != null && dt.Rows.Count > 0)
            {
                SetPage(dt);
            }
            else
            {
                if (plan == "下一计划")
                    MessageBox.Show("无下一计划");
                else
                    MessageBox.Show("无上一计划");
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            textBox2.Visible = true;
            textBox2.Focus(); 
        }

        private void textBox2_DoubleClick(object sender, EventArgs e)
        {
            textBox2.Text = "";
            textBox2.Visible = false;
        }

        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    string barcode = textBox2.Text.Trim();
                    if (barcode.Contains("."))
                    {
                        barcode = ProScreenFunc.UniteBarCodeToOne(barcode);
                    }

                 
                    if (ProScreenFunc.HaveScan(barcode))
                    {
                        if (ProScreenFunc.IsBad(barcode))
                        {
                            MessageBox.Show("该条码已经做过报废处理!", "提示");
                            textBox2.Text = "";
                            textBox2.Visible = false;
                            return;
                        }
                        string planID = ProScreenFunc.GetPlanIDByBarcode(barcode);
                        ProScreenFunc.AddBadCount(planID.Trim());
                        ProScreenFunc.SubCompleteCount(planID.Trim());

                        ProScreenFunc.SaveRecord2(barcode, "0", planID);

                        DataTable dt = ProScreenFunc.GetProScreenByPlanID(this.Tag.ToString().Trim());
                        SetPage(dt);

                        textBox2.Text = "";
                        textBox2.Visible = false;
                    }
                    else
                    {
                        MessageBox.Show("还未进行装配!", "提示");

                        textBox2.Text = "";
                        textBox2.Visible = false;
                    }

                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrLogBase(ex.ToString(), MethodBase.GetCurrentMethod().Name);
                }
            }
            else if (e.KeyCode == Keys.Escape)
            {
                textBox2.Text = "";
                textBox2.Visible = false;
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            textBox3.Visible = true;
            textBox3.Focus(); 
        }

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

        private void textBox3_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    try
                    {
                        string barcode = textBox3.Text.Trim();
                        if (barcode.Contains("."))
                        {
                            barcode = ProScreenFunc.UniteBarCodeToOne(barcode);
                        }

                        if (ProScreenFunc.IsBad(barcode))
                        {
                            string planID = ProScreenFunc.GetPlanIDByBarcode(barcode);
                            if (!ProScreenFunc.CheckPlanCompleted(planID))
                            {
                                ProScreenFunc.SubBadCount(planID.Trim());
                                ProScreenFunc.AddCompleteCount(planID.Trim());

                                ProScreenFunc.SaveRecord2(barcode, "1", planID);
                            }
                            else
                            {
                                string partNo = ProScreenFunc.GetPaintCode(barcode);
                                if (partNo == label3.Text.Trim())
                                {
                                    ProScreenFunc.AddCompleteCount(Tag.ToString().Trim());
                                    ProScreenFunc.SaveRecord2(barcode, "1", Tag.ToString().Trim());
                                }
                                else
                                {
                                    MessageBox.Show("当前扫描的零件与总成不匹配,请检查后再扫描!");
                                }
                            }
                            if (ProScreenFunc.CheckPlanCompleted(this.Tag.ToString().Trim()))
                            {
                                LoadScreen();
                            }
                            else
                            {
                                DataTable dt = ProScreenFunc.GetProScreenByPlanID(this.Tag.ToString().Trim());
                                SetPage(dt);
                            }

                            textBox3.Text = "";
                            textBox3.Visible = false;
                        }
                        else
                        {
                            MessageBox.Show("该条码未做过报废处理,无法转合格!", "提示");
                            textBox3.Text = "";
                            textBox3.Visible = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteErrLogBase(ex.ToString(), MethodBase.GetCurrentMethod().Name);
                    }
                }
                else if (e.KeyCode == Keys.Escape)
                {
                    textBox3.Text = "";
                    textBox3.Visible = false;
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            ProScreenFunc.SetPlanComplete(this.Tag.ToString().Trim());
            LoadScreen();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            FrmProScreen2 frm = new FrmProScreen2();
            frm.Show();
        }

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

        private void textBox4_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {

                    if (string.IsNullOrEmpty(textBox4.Text))
                    {
                        MessageBox.Show("盖板条码不能为空!");
                        textBox4.Focus();
                        return;
                    }

                    if (ConfigurationManager.AppSettings["StationNo"] == "ZP57")
                    {
                        if (textBox4.Text.Trim().Substring(0, 11) != "A2068853104")
                        {
                            MessageBox.Show("盖板条码有误!");
                            textBox4.SelectAll();
                            textBox4.Focus();
                            return;
                        }
                    }

                    if (ConfigurationManager.AppSettings["StationNo"] != "ZP77")
                    {
                        string[] aa = textBox4.Text.Trim().Split('-');
                        string[] bb = label3.Text.Trim().Split('-');

                        if (aa[1].Substring(0, 4) != bb[1])
                        {
                            MessageBox.Show("盖板条码颜色不符!");
                            textBox4.SelectAll();
                            textBox4.Focus();
                            return;
                        }
                        AfterScanBarcode(barcode, productID2, productID, base.Tag.ToString().Trim(),stationId);
                    }
                    else
                    {
                        string[] aa = textBox4.Text.Trim().Split('-');
                        string[] bb = ProScreenFunc.GetPaintCode(textBox1.Text.Trim()).Split('-');

                        if (aa[1].Substring(0, 4) != bb[1])
                        {
                            MessageBox.Show("盖板条码颜色不符!");
                            textBox4.SelectAll();
                            textBox4.Focus();
                            return;
                        }
                        opcHelper.opcItemm2[4].Write(1);   
                        opcHelper.opcItemm2[3].Write(0);   
                        opcHelper.opcItemm2[2].Write(1);  

                        AfterScanBarCode_1(barcode);
                    }

                    textBox4.Text = "";
                    textBox4.Visible = false;
                    textBox1.Focus();
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

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

        /// <summary>
        /// 补打标签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox5_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    string barcode = textBox5.Text.Trim();
                    if (barcode.Contains("."))
                    {
                        barcode = ProScreenFunc.UniteBarCodeToOne(barcode);
                    }

                    DataTable dtHg = ProScreenFunc.GetGh(barcode);
                    if (dtHg == null || dtHg.Rows.Count < 1)
                    {
                        MessageBox.Show("未装配,不能补打标签!");
                        textBox4_DoubleClick(sender, e);
                        return;
                    }

                    DataTable dtBl = ProScreenFunc.GetBl(barcode);
                    if (dtBl != null && dtBl.Rows.Count > 0)
                    {
                        DateTime hgTime = (DateTime)Tools.NumericParse.StringToDateTime("1900-01-01 00:00:00");
                        DataTable dtHG1 = ProScreenFunc.GetHG_New(barcode);
                        if (dtHG1 != null && dtHG1.Rows.Count > 0)
                        {
                            hgTime = (DateTime)Tools.NumericParse.StringToDateTime(dtHG1.Rows[0]["CreateTime"].ToString());
                        }

                        DateTime blTime = (DateTime)Tools.NumericParse.StringToDateTime(dtBl.Rows[0]["createTime"].ToString());
                        if (DateTime.Compare(blTime, hgTime) > 0)
                        {
                            MessageBox.Show("产品不良,不能补打标签!");
                            textBox5_DoubleClick(sender, e);
                            return;
                        }
                    }

                    LogSysBLL.AddInfo("条码:" + barcode + "补打标签", MethodBase.GetCurrentMethod());
                    string zcID = dtHg.Rows[0]["ZcID"].ToString();
                    ZcPrintLabel zl = ProScreenFunc.GetZcPrintLabel(zcID);
                    if (zl != null && zl.zcPartNo != null && zl.zcName != null)
                    {
                        if (ConfigurationManager.AppSettings["PrintEnable"].ToString().ToLower() == "true")
                        {
                            if (zl.zcPartNo.Contains("A2477900588-") || zl.zcPartNo.Contains("A2477900000-"))
                            {
                                string path = System.Windows.Forms.Application.StartupPath + @"\aaa1.grf";

                                GridppReport Report2 = new GridppReport();
                                Report2.Register("");
                                Report2.LoadFromFile(path);
                                if (zl.zcPartNo.Contains("A2477900588-"))
                                {
                                    Report2.ParameterByName("Des").Value = "X247S";
                                }
                                if (zl.zcPartNo.Contains("A2477900000-"))
                                {
                                    Report2.ParameterByName("Des").Value = "H247S";
                                }
                                Report2.ParameterByName("PartNo").Value = zl.zcPartNo;
                                Report2.ParameterByName("PartName").Value = zl.zcName;
                                string sn = dtHg.Rows[0]["SerialNo"].ToString();
                                Report2.ParameterByName("SerialNo").Value = sn;
                                string[] tmp = sn.Split('.');
                                Report2.ParameterByName("BarCode").Value = sn + ";24;2217;;.0;" + tmp[1];
                                Report2.ParameterByName("oneBarCode").Value = barcode;
                                Report2.ParameterByName("BatchNo").Value = tmp[1];
                                Report2.Print(false);
                                textBox4.SelectAll();
                            }
                            else
                            {
                                string path = System.Windows.Forms.Application.StartupPath + @"\aaa.grf";

                                GridppReport Report1 = new GridppReport();
                                Report1.Register("");
                                Report1.LoadFromFile(path);
                                Report1.ParameterByName("oneBarCode").Value = barcode;
                                Report1.ParameterByName("zcPartNo").Value = zl.zcPartNo;
                                Report1.ParameterByName("zcName").Value = zl.zcName;
                                Report1.Print(false);
                                textBox4.SelectAll();
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("根据总成号找不到对应名称,请维护基础数据!");
                        textBox4_DoubleClick(sender, e);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            textBox5.Text = "";
            textBox5.Visible = true;
            textBox5.Focus();
        }

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