using gregn6Lib;
using PunchAndWeld.DataSouce;
using PunchAndWeld.WebReference;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DBUtility;
using MESClassLibrary.BLL.Log;

namespace PunchAndWeld
{
    public partial class FrmProScreen : Form
    {
        private GridppReport Report = new GridppReport();
        private string oneBarCode = "", stationNo = "", stationId = "";

        public FrmProScreen()
        {
            InitializeComponent();
        }

        private void FrmProScreen_Load(object sender, EventArgs e)
        {
            try
            {
                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;
                Thread t = new Thread(new ThreadStart(TimeGo));
                t.Start();

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

                if (ConfigurationManager.AppSettings["IsHaveVisual"].ToString() == "1")
                {
                    SqlStart();
                }

                timer1.Enabled = true;
            }
            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");
            Thread.Sleep(500);
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                CheckPartAndProduct();
            }
        }

        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;

            if (dt != null && dt.Rows.Count > 0)
            {
                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(); 
                textBox1.Tag = dt.Rows[0]["ProductID1"].ToString();
                textBox1.Text = "";
            }
        }

        public void LoadPlanScreen(string id, string plan)
        {
            string stationNo = ConfigurationManager.AppSettings["StationNo"].ToString();

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

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

            if (barcode.Length != 20)
            {
                MessageBox.Show("条码位数有误,请重新扫描!");
                textBox1.SelectAll();
                return;
            }

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


            oneBarCode = barcode;

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

            if (ConfigurationManager.AppSettings["IsHaveVisual"].ToString() == "1")
            {
                DataTable dt = ProScreenFunc.NotPrintBarCode(stationId);
                if (dt!=null && dt.Rows.Count > 0) 
                {
                    MessageBox.Show("存在未打印标签的产品,不允许扫描!条码为:" + dt.Rows[0]["barcode"].ToString() );
                    textBox1.SelectAll();
                    return;
                }
            }


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


            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)
        {
            string 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))
                {
                    string productID2 = ProScreenFunc.GetProductID(barcode);
                    if (!ProScreenFunc.CheckPartAndProduct(productID, productID2))
                    {
                        this.InsLog(productID, productID2);
                        MessageBox.Show("当前扫描的零件与总成不匹配,请检查后再扫描");
                        this.textBox1.Text = "";
                        return;
                    }
                    else
                    {
                        SavePunch(barcode, productID2, productID, base.Tag.ToString().Trim());
                        if (ConfigurationManager.AppSettings["IsHaveVisual"].ToString() != "1")
                        {
                            this.AfterScanBarcode1(barcode, productID2, productID, base.Tag.ToString().Trim());
                        }
                        
                    }
                }
                else
                {
                    string productID2 = ProScreenFunc.GetProductID(code, "");
                    SavePunch(barcode, productID2, productID, base.Tag.ToString().Trim());
                    if (ConfigurationManager.AppSettings["IsHaveVisual"].ToString() != "1")
                    {
                        this.AfterScanBarcode1(barcode, productID2, productID, base.Tag.ToString().Trim());
                    }
                }
            }
            else
            {
                string 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 = "";
                    return;
                }
                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)
                    {
                        
                        if (ConfigurationManager.AppSettings["IsHaveVisual"].ToString() != "1")
                        {
                            this.AfterScanBarcode1(barcode, productID2, productID, base.Tag.ToString().Trim());
                        }
                        else
                        {
                            SavePunch(barcode, productID2, productID, base.Tag.ToString().Trim());
                        }
                    }
                }
            }
        }

        private void AfterScanBarcode()
        {
            string ID = "", barcode = "", productID2="", productID1="";

            DataTable dt1 = ProScreenFunc.HavePrint(stationId);
            if (dt1 != null && dt1.Rows.Count > 0)
            {
                if (dt1.Rows[0]["PlanID"].ToString() != base.Tag.ToString().Trim())
                {
                    MessageBox.Show("产品和计划不匹配");
                    return;
                }
                else
                {
                    ID = dt1.Rows[0]["ID"].ToString();
                    barcode = dt1.Rows[0]["barcode"].ToString();
                    oneBarCode = barcode;
                    productID2 = dt1.Rows[0]["BcpID"].ToString();
                    productID1 = dt1.Rows[0]["ZcID"].ToString();
                }
            }
            else
            {
                return;
            }

            this.Invoke((EventHandler) (delegate
            {
                try
                {
                    LogHelper.WriteSysLogBase("条码号:" + barcode + "工位:" + label1.Text.Trim() + ",一码到底调用WMS接口",
                        MethodBase.GetCurrentMethod().Name);

                    string stockNo = "";
                    string batchNo = "";
                    string partNo = "";
                    ProScreenFunc.GetCode(barcode, out stockNo, out batchNo, out partNo);

                    partNo = label3.Text.Trim();
                    //2020-11-11 由原来的datetime.Now.ToString("yyyyMMdd")修改成计划的录入时间
                    batchNo = ProScreenFunc.GetPlanTime(base.Tag.ToString().Trim()).ToString("yyyyMMdd");

                    WMSWebService webService = new WMSWebService();
                    webService.Url = ConfigurationManager.AppSettings["WMSWebServiceURL"].ToString();

                    bool aa = webService.WMSInterfaceStockIn(barcode, partNo, batchNo, 1);
                    if (aa)
                    {

                        ProScreenFunc.AddCompleteCount(this.Tag.ToString().Trim());

                        try
                        {
                            if (ConfigurationManager.AppSettings["PrintEnable"].ToString().ToLower() == "true")
                            {
                                string path = "";
                                if (label3.Text.Trim().Contains("A2477900588-"))
                                {
                                    path = Application.StartupPath + @"\aaa1.grf";
                                    Report.Initialize += new _IGridppReportEvents_InitializeEventHandler(ReportInitialize1);
                                }
                                else
                                {
                                    path = Application.StartupPath + @"\aaa.grf";
                                    Report.Initialize += new _IGridppReportEvents_InitializeEventHandler(ReportInitialize);
                                }
                                
                                Report.Register("");
                                Report.LoadFromFile(path);
                                
                                //Report.DesignPaperOrientation = GRPaperOrientation.grpoLandscape;
                                //report.PrintPreview(true);
                                Report.Print(false);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }

                        LogHelper.WriteLog("条码号:" + barcode + "工位:" + label1.Text.Trim() + "打印时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                        ProScreenFunc.UpdatePrintTime(ID);

                        if (ProScreenFunc.CheckPlanCompleted(this.Tag.ToString().Trim()))
                        {
                            LoadScreen();
                        }
                        else
                        {
                            label7.Text = ProScreenFunc.GetCompleteCount(this.Tag.ToString().Trim());
                        }

                    }
                    else
                    {
                        MessageBox.Show("WMS入库失败,请稍后重新扫描");
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrLogBase("工位:" + label1.Text.Trim() + ",一码到底调用WMS接口:" + ex.ToString(),
                        MethodBase.GetCurrentMethod().Name);
                }

                ProScreenFunc.SavePartAndProductBF(barcode, productID2, productID1, label2.Text, label8.Text,
                    base.Tag.ToString().Trim());
            }));
        }

        private void AfterScanBarcode1(string barcode, string productID2, string productID1, string planID)
        {

            try
            {
                LogHelper.WriteSysLogBase("条码号:" + barcode + "工位:" + label1.Text.Trim() + ",一码到底调用WMS接口", MethodBase.GetCurrentMethod().Name);

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

                WMSWebService webService = new WMSWebService();
                webService.Url = ConfigurationManager.AppSettings["WMSWebServiceURL"].ToString();

                bool aa = webService.WMSInterfaceStockIn(barcode, partNo, batchNo, 1);
                if (aa)
                {

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



                    try
                    {
                        if (ConfigurationManager.AppSettings["PrintEnable"].ToString().ToLower() == "true")
                        {
                            string path = "";
                            if (label3.Text.Trim().Contains("A2477900588-") || label3.Text.Trim().Contains("A2477900000-"))
                            {
                                path = Application.StartupPath + @"\aaa1.grf";
                                Report.Initialize += new _IGridppReportEvents_InitializeEventHandler(ReportInitialize1);
                            }
                            else
                            {
                                path = Application.StartupPath + @"\aaa.grf";
                                Report.Initialize += new _IGridppReportEvents_InitializeEventHandler(ReportInitialize);
                            }

                            Report.Register("");
                            Report.LoadFromFile(path);

                            //Report.DesignPaperOrientation = GRPaperOrientation.grpoLandscape;
                            //report.PrintPreview(true);
                            Report.Print(false);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }

                    if (ProScreenFunc.CheckPlanCompleted(this.Tag.ToString().Trim()))
                    {
                        LoadScreen();
                    }
                    else
                    {
                        label7.Text = ProScreenFunc.GetCompleteCount(this.Tag.ToString().Trim());
                    }
                }
                else
                {
                    MessageBox.Show("WMS入库失败,请稍后重新扫描");
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase("工位:" + label1.Text.Trim() + ",一码到底调用WMS接口:" + ex.ToString(), MethodBase.GetCurrentMethod().Name);
            }


            ProScreenFunc.SavePartAndProductBF(barcode, productID2, productID1, label2.Text, label8.Text, planID);
        }

        private void SavePunch(string barcode, string productID2, string productID1, string planID)
        {
            #region 存储

            ProScreenFunc.SavePartAndProduct(barcode, productID2, productID1, label2.Text, label8.Text, planID, stationId, ConfigurationManager.AppSettings["StationDescription"]);
            ProScreenFunc.SaveZcCode(barcode, label3.Text.Trim());

            #endregion
        }

        private void ReportInitialize()
        {
            Report.ParameterByName("oneBarCode").Value = oneBarCode;
            Report.ParameterByName("zcPartNo").Value = label3.Text.Trim();
            Report.ParameterByName("zcName").Value = label4.Text.Trim();
        }

        private void ReportInitialize1()
        {
            string barcode = textBox1.Text.Trim();
            if (barcode.Contains("."))
            {
                barcode = ProScreenFunc.UniteBarCodeToOne(barcode);
            }
            DateTime time = DateTime.Now;
            if (label3.Text.Trim().Contains("A2477900588-"))
            {
                Report.ParameterByName("Des").Value = "X247S";
            }
            if (label3.Text.Trim().Contains("A2477900000-"))
            {
                Report.ParameterByName("Des").Value = "H247S";
            }
            Report.ParameterByName("PartNo").Value = label3.Text.Trim();
            Report.ParameterByName("PartName").Value = label4.Text.Trim();
            Report.ParameterByName("BatchNo").Value = time.ToString("yyMMdd");
            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');
            }

            Report.ParameterByName("SerialNo").Value = sn;
            Report.ParameterByName("BarCode").Value = sn + ";24;2217;;.0;" + time.ToString("yyyy/MM/dd");
            Report.ParameterByName("oneBarCode").Value = barcode;
            //Report.ParameterByName("PartName").Value = label4.Text.Trim();
            //Report.ParameterByName("BatchNo").Value = time.ToString("yyMMdd");
            //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');
            //}

            //Report.ParameterByName("SerialNo").Value = sn;
            //Report.ParameterByName("BarCode").Value = sn + ";24;2217;;.0;" + time.ToString("yyyy/MM/dd");
        }

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

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

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

        /// <summary>
        /// 产品不良
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            textBox2.Visible = true;
            textBox2.Focus(); 
        }

        /// <summary>
        /// 不良转合格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            textBox3.Visible = true;
            textBox3.Focus(); 
        }

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

        private void timer1_Tick(object sender, EventArgs e)
        {
            string orderNo = label2.Text.Trim();
            if (string.IsNullOrWhiteSpace(orderNo))
            {
                LoadScreen();
            }
        }

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

                        //label10.Text = (Tools.NumericParse.StringToInt(label10.Text.Trim()) + 1).ToString();
                        //label7.Text = (Tools.NumericParse.StringToInt(label7.Text.Trim()) - 1).ToString();

                        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 textBox3_KeyDown(object sender, KeyEventArgs e)
        {
            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;
            }
        }

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

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

        private void button3_Click(object sender, EventArgs e)
        {
            BusinessHelper.SetRePrint(textBox4);
            //textBox4.Text = "";
            //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 button7_Click(object sender, EventArgs e)
        {
            ProScreenFunc.SetPlanComplete(this.Tag.ToString().Trim());
            LoadScreen();
        }

        private void textBox4_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    string barcode = textBox4.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("产品不良,不能补打标签!");
                            textBox4_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)
                {
                    textBox4_DoubleClick(sender, e);
                }
            }
            else if (e.KeyCode == Keys.Escape)
            {
                textBox4_DoubleClick(sender, e);
            }

            
        }

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

        private void SqlStart()
        {
            try
            {
                SqlDependency.Start(SqlHelper.SqlConnString);
                SqlDependencyWatch();
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase(ex.ToString(),MethodBase.GetCurrentMethod().Name);
            }
        }

        private void SqlDependencyWatch()
        {
            //string sSQL = "SELECT [ToVisual] FROM [dbo].[tb_Punch_Code_Record] where StationId='"+ stationId +@"'";
            string sSQL = "SELECT [ToVisual] FROM [dbo].[tb_Punch_Code_Record] where StationId='"+ stationId +@"'";

            using (SqlConnection connection = new SqlConnection(SqlHelper.SqlConnString))
            {
                using (SqlCommand command = new SqlCommand(sSQL, connection))
                {
                    command.CommandType = CommandType.Text;
                    connection.Open();
                    SqlDependency dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(SQLTableOnChange);
                    SqlDataReader sdr = command.ExecuteReader();
                }
            }
        }

        private void SQLTableOnChange(object sender, SqlNotificationEventArgs e)
        {
            SqlDependencyWatch();
            AfterScanBarcode();
        }
    }
}