using gregn6Lib;
using PunchAndWeld.DataSouce;
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;
using PunchAndWeld.WebReference;
using System.Reflection.Emit;

namespace PunchAndWeld
{
    public partial class FrmDoorSill_214 : Form
    {
        public bool IsChangeBox = false;
        public bool IsPass = false;
        private string IsHigh = "1";
        public string stationNo = "",stationId="";
        int a = 0;
        int oldState = 0;


        string[] partNo1 = new string[10];
        string planID = "", zcHigh = "";

        private GridppReport Report = new GridppReport();

        public FrmDoorSill_214()
        {
            InitializeComponent();
        }

        private void FrmDoorSill_214_Load(object sender, EventArgs e)
        {
            label5.Text = "当前版本:" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            stationNo = ConfigurationManager.AppSettings["StationNo"].ToString();
            stationId = ProScreenFunc.GetStationId(stationNo);
            label10.Visible = false;
            label10.Text = "";
            //timer2.Enabled = false;

            label1.Text = ProScreenFunc.GetStation(stationNo);

            Control.CheckForIllegalCrossThreadCalls = false;
            Thread t = new Thread(new ThreadStart(TimeGo));
            t.Start();

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

            LoadScreen();
        }

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

            System.Timers.Timer timer3 = new System.Timers.Timer();
            timer3.Interval = 2000;
            timer3.Enabled = true;
            timer3.Elapsed += new System.Timers.ElapsedEventHandler(timer3_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 timer3_Tick(object sender, EventArgs e)
        {
            int newState = ProScreenFunc.VisualState();
            if (newState == oldState)
            {
                if (label10.Text == "")
                { 
                    return; 
                }
            }
            switch (ProScreenFunc.VisualState()) 
            {
                case 0:
                    //timer2.Enabled = false;
                    break;
                case 1:
                    //timer2.Enabled = false;
                    break;
                case 2:
                    if (a == 0)
                    {
                        label10.Visible = true;
                        label10.Text = "OK";
                        label10.BackColor = Color.LightGreen;
                        a++;
                    }
                    else if (a != 0 && label10.Text != "")
                    {
                        label10.Visible = false;
                        label10.Text = "";
                        a = 0;
                    }
                    break;
                case 3:
                    //timer2.Enabled = true;
                    if (a == 0)
                    {
                        label10.Visible = true;
                        label10.Text = "NG";
                        label10.BackColor = Color.Red;
                        a++;
                    }
                    else if (a != 0 && label10.Text != "")
                    {
                        label10.Visible = false;
                        label10.Text = "";
                        a = 0;
                    }
                    break;
            }
            oldState = newState;
        }

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

        private void AfterScanBarcode1()
        {
            try
            {
                string ID = "", barcode = "", planId1 = "", toVisual = "", zcPartNo = "", zcPartName = "", sn = "",flag="";
                DataTable dt1 = ProScreenFunc.HavePrint_1(stationId);
                if (dt1 != null && dt1.Rows.Count > 0)
                {
                    ID = dt1.Rows[0]["ID"].ToString();
                    barcode = dt1.Rows[0]["barcode"].ToString();
                    zcPartNo = dt1.Rows[0]["PartNo"].ToString();
                    zcPartName = dt1.Rows[0]["ProductName"].ToString();
                    planId1 = dt1.Rows[0]["PlanID"].ToString();
                    sn = dt1.Rows[0]["SerialNo"].ToString();
                    toVisual = dt1.Rows[0]["ToVisual"].ToString();
                    flag= dt1.Rows[0]["Flag"].ToString();

                    if (stationNo != "ZP95")
                    {

                        if (!ProScreenFunc.IsNeedVisual(zcPartNo) && flag == "1")
                        {
                            return;
                        }
                    }
                }
                else
                {
                    return;
                }
                if (toVisual == "0")
                {
                    this.Invoke((EventHandler)(delegate
                    {
                        label10.Visible = true;
                        label10.Text = "OK";
                        label10.BackColor = Color.LimeGreen;

                        Thread.Sleep(2000);

                        label10.Visible = false;

                        bool aa = false, toWms = true;

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

                            batchNo = DateTime.Now.ToString("yyyyMMdd");

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

                            aa = webService.WMSInterfaceStockIn(barcode, zcPartNo, batchNo, int.Parse(flag));
                            if (aa)
                            {
                                ProScreenFunc.SaveToWmsRecord(barcode);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.WriteErrLogBase("工位:" + label1.Text.Trim() + ",一码到底调用WMS接口:" + ex.ToString(), MethodBase.GetCurrentMethod().Name);
                        }

                        if (aa)
                        {

                            try
                            {
                                if (ConfigurationManager.AppSettings["PrintEnable"].ToLower() == "true")
                                {
                                    string path = "";

                                    if (!checkBox1.Checked)
                                    {
                                        path = Application.StartupPath + @"\ZC.grf";
                                    }
                                    else
                                    {
                                        path = Application.StartupPath + @"\ZCIndia.grf";
                                    }
                                    DataTable headTable = new DataTable();
                                    headTable.Columns.Add("SerialNo");
                                    headTable.Columns.Add("oneBarCode");
                                    headTable.Columns.Add("zcPartNo");
                                    headTable.Columns.Add("zcName");
                                    headTable.Columns.Add("zcState");
                                    DataRow row = headTable.NewRow();
                                    row["SerialNo"] = sn;
                                    row["oneBarCode"] = barcode;
                                    row["zcPartNo"] = zcPartNo;
                                    row["zcName"] = zcPartName;
                                    //row["zcState"] = "合格";
                                    row["zcState"] = flag;

                                    string reportName = ConfigurationManager.AppSettings["Printer1"];
                                    headTable.Rows.Add(row);

                                    DataTable dtDetail = ProScreenFunc.GetOtherPart(stationNo, zcPartNo);
                                    ReportHelper rp = new ReportHelper(path, headTable, dtDetail,
                                        (int)GRPaperOrientation.grpoDefault, 1, reportName);
                                    rp.Report.Print(false);
                                }
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }


                            ProScreenFunc.UpdatePrintTime_1(ID);

                            if (flag == "1")
                            {
                                ProScreenFunc.AddCompleteCountAndFinish_1(planId1);
                            }


                            if (planID == planId1)
                            {
                                DataTable dt = ProScreenFunc.GetProScreenByPlanID_1(planId1);
                                if (dt != null && dt.Rows.Count > 0)
                                {
                                    label7.Text = dt.Rows[0]["CompleteCount"].ToString();
                                }

                                if (ProScreenFunc.CheckPlanCompleted_1(this.Tag.ToString().Trim()))
                                {
                                    LoadPlanScreen(this.Tag.ToString(), "下一计划");
                                }
                                else
                                {
                                    label7.Text = ProScreenFunc.GetCompleteCount_1(this.Tag.ToString().Trim());
                                }

                            }
                        }
                        else if (!aa)
                        {
                            MessageBox.Show("WMS入库失败");
                        }
                    }));
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        public void LoadScreen()
        {
            DataTable dt = ProScreenFunc.GetProScreen_1(stationId);
            if (dt != null && dt.Rows.Count > 0)
            {
                SetPage(dt, stationNo);
            }
            else
            {
                label1.Text = ProScreenFunc.GetStation(stationNo);
                label2.Text = "";
                label3.Text = "";
                label4.Text = "";
                label6.Text = "0";
                label7.Text = "0";
                label8.Text = "";

                this.Tag = ""; //计划ID
                planID = this.Tag.ToString();
                textBox1.Tag = "";
                textBox1.Text = "";

                MessageBox.Show("无计划!", "提示", MessageBoxButtons.OK);
            }
        }

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

        public void LoadPlanScreen(string id, string plan)
        {
            LogHelper.WriteLog($"ID={id},stationNo={stationNo},plan={plan}");
            DataTable dt = ProScreenFunc.GetProScreenPlan_1(id, stationNo, plan);
            if (dt != null && dt.Rows.Count > 0)
            {
                SetPage(dt, stationNo);
            }
            else
            {
                if (plan == "下一计划")
                {
                    MessageBox.Show("无下一计划");
                }

                else
                {
                    MessageBox.Show("无上一计划.");
                }
            }
        }

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

        /// <summary>
        /// 计划查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            FrmSearchPlan frm = new FrmSearchPlan();
            frm.OkClick += (arg1) =>
            {
                this.Tag = arg1;
                frm.Close();
                LoadPlanScreen(arg1, "当前计划");
            };
            frm.ShowDialog();
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    string zcPartNo = "";


                    if (ConfigurationManager.AppSettings["IsHaveVisual"] == "1")
                    {
                        DataTable dt1 = ProScreenFunc.HavePrint_1(stationId);
                        if (dt1 != null && dt1.Rows.Count > 0)
                        {
                            zcPartNo = dt1.Rows[0]["PartNo"].ToString();


                            if (ProScreenFunc.IsNeedVisual(zcPartNo) && dt1.Rows[0]["Flag"].ToString() == "1")
                            {
                                MessageBox.Show("存在未打印标签的产品,不允许扫描!");
                                textBox1.SelectAll();
                                return;
                            }

                        }
                    }

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

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

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

                #region 查询是否已扫描过,如果扫过,需输入用户名密码,确认过才可以再扫

                if (ProScreenFunc.HaveScan_1(barcode))
                {
                    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);
                }

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

        private void ScanBarcode(string barcode)
        {
            try
            {
                string productId1 = "", productId2 = "", partNo2 = "",sn="";
                bool high = false;
                string zcPartNo = label3.Text;
                string zcPartName = label4.Text;
                string planId = planID;
                string tagId = this.Tag.ToString();


                productId1 = textBox1.Tag.ToString();


                high = ProScreenFunc.IsHigh(zcPartNo);

                if (high && !ProScreenFunc.IsScan(barcode))
                {
                    MessageBox.Show("无法装配,高配需要过激光切割!", "提示", MessageBoxButtons.OK);
                    return;
                }

                if (!high && ProScreenFunc.IsScan(barcode))
                {
                    MessageBox.Show("无法装配,低配不需要过激光切割!", "提示", MessageBoxButtons.OK);
                    return;
                }

                string[] codeSpecial = ProScreenFunc.GetSpecialStockNo();
                string code = barcode.Substring(0, 10);
                if (codeSpecial.Contains(code))
                {
                    productId2 = ProScreenFunc.GetProductID(code, "");
                    partNo2 = ProScreenFunc.GetPartNoByStockNo(code);
                }
                else
                {
                    if (barcode.Substring(0, 2) != "22")
                    {
                        string[] codeSpecial1 = ProScreenFunc.GetSpecialStockNo();
                        string code1 = barcode.Substring(0, 10);
                        if (codeSpecial1.Contains(code1))
                        {
                            productId2 = ProScreenFunc.GetProductID(code, "");
                            partNo2 = ProScreenFunc.GetPartNoByStockNo(code);
                        }
                        else
                        {
                            productId2 = ProScreenFunc.GetProductID(barcode);
                            if (string.IsNullOrWhiteSpace(productId2))
                            {
                                string stockNo = barcode.Substring(0, 10);
                                productId2 = ProScreenFunc.GetProductID(stockNo, "");
                            }
                            partNo2 = ProScreenFunc.GetPartNoByID(productId2);
                        }
                    }

                    if (!ProScreenFunc.CheckPartAndProduct_1(productId1, productId2,stationId))
                    {
                        MessageBox.Show("当前扫描的零件与总成不匹配,请检查后再扫描");
                        textBox1.SelectAll();
                        textBox1.Focus();
                        return;
                    }

                    ListViewItem liv = listView1.Items.Cast<ListViewItem>().First(x => x.SubItems[0].Text == partNo2);
                    int index = liv.Index;
                    if (index != 0)
                    {
                        MessageBox.Show("条码和总成不匹配!");
                        textBox1.SelectAll();
                        textBox1.Focus();
                        return;
                    }
                    listView1.Items[index].SubItems[2].Text = "通过";

                    bool isScan = ProScreenFunc.IsScan(barcode);
                    OtherPart parts = ProScreenFunc.HaveOtherPart_1(stationId, productId1);
                    if ((parts != null) && ((!string.IsNullOrWhiteSpace(parts.productID3)) || (!string.IsNullOrWhiteSpace(parts.productID4)) || (!string.IsNullOrWhiteSpace(parts.productID5)) || (!string.IsNullOrWhiteSpace(parts.productID6)) || (!string.IsNullOrWhiteSpace(parts.productID7)) || (!string.IsNullOrWhiteSpace(parts.productID8))))
                    {
                        FrmOtherParts frm = new FrmOtherParts(parts);
                        frm.ShowDialog();
                    }
                    else
                    {
                        ScanAll.ScanResult = true;
                        ScanAll.barCode1 = "";
                        ScanAll.barCode2 = "";
                        ScanAll.barCode3 = "";
                        ScanAll.barCode4 = "";
                        ScanAll.barCode5 = "";
                        ScanAll.barCode6 = "";
                    }

                    if (ScanAll.ScanResult)
                    {
                        bool aa = false, toWms = true;

                        if (!string.IsNullOrWhiteSpace(ScanAll.partNo1))
                        {
                            ListViewItem liv1 = listView1.Items.Cast<ListViewItem>()
                                .First(x => x.SubItems[0].Text == ScanAll.partNo1);
                            int index1 = liv1.Index;
                            listView1.Items[index1].SubItems[2].Text = "通过";
                        }

                        if (!string.IsNullOrWhiteSpace(ScanAll.partNo2))
                        {
                            ListViewItem liv2 = listView1.Items.Cast<ListViewItem>()
                                .First(x => x.SubItems[0].Text == ScanAll.partNo2);
                            int index2 = liv2.Index;
                            listView1.Items[index2].SubItems[2].Text = "通过";
                        }

                        if (!string.IsNullOrWhiteSpace(ScanAll.partNo3))
                        {
                            ListViewItem liv3 = listView1.Items.Cast<ListViewItem>()
                                .First(x => x.SubItems[0].Text == ScanAll.partNo3);
                            int index3 = liv3.Index;
                            listView1.Items[index3].SubItems[2].Text = "通过";
                        }

                        if (!string.IsNullOrWhiteSpace(ScanAll.partNo4))
                        {
                            ListViewItem liv4 = listView1.Items.Cast<ListViewItem>()
                                .First(x => x.SubItems[0].Text == ScanAll.partNo4);
                            int index4 = liv4.Index;
                            listView1.Items[index4].SubItems[2].Text = "通过";
                        }

                        if (!string.IsNullOrWhiteSpace(ScanAll.partNo5))
                        {
                            ListViewItem liv5 = listView1.Items.Cast<ListViewItem>()
                                .First(x => x.SubItems[0].Text == ScanAll.partNo5);
                            int index5 = liv5.Index;
                            listView1.Items[index5].SubItems[2].Text = "通过";
                        }

                        if (!string.IsNullOrWhiteSpace(ScanAll.partNo6))
                        {
                            ListViewItem liv6 = listView1.Items.Cast<ListViewItem>()
                                .First(x => x.SubItems[0].Text == ScanAll.partNo6);
                            int index6 = liv6.Index;
                            listView1.Items[index6].SubItems[2].Text = "通过";
                        }

                        if (ConfigurationManager.AppSettings["IsHaveVisual"] != "1")
                        {
                            if ((IsChangeBox && IsPass) || (!IsChangeBox))
                            {

                                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;
                                    partNo = zcPartNo;
                                    batchNo = DateTime.Now.ToString("yyyyMMdd");

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

                                    aa = webService.WMSInterfaceStockIn(barcode, partNo, batchNo, 1);
                                    if (aa)
                                    {
                                        ProScreenFunc.SaveToWmsRecord(barcode);
                                    }
                                    //}
                                }
                                catch (Exception ex)
                                {
                                    LogHelper.WriteErrLogBase("工位:" + label1.Text.Trim() + ",一码到底调用WMS接口:" + ex.ToString(), MethodBase.GetCurrentMethod().Name);
                                }

                                if (aa)
                                {
                                    DateTime time = DateTime.Now;
                                    string tmp = ProScreenFunc.SerialNo_1(zcPartNo, time.ToString("yyMMdd"));
                                    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 (checkBox1.Checked)
                                    {
                                        if (ProScreenFunc.SavePartAndProduct_1(barcode, productId2, productId1,
                                        label2.Text.Trim(), label2.Text.Trim().Substring(0, 1) + "班", planId, sn,
                                        ScanAll.barCode1, ScanAll.barCode2, ScanAll.barCode3,
                                        ScanAll.barCode4, ScanAll.barCode5, ScanAll.barCode6, stationId,1)<=0)
                                        {
                                            MessageBox.Show("连接数据库失败!");
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        if (ProScreenFunc.SavePartAndProduct_1(barcode, productId2, productId1,
                                        label2.Text.Trim(), label2.Text.Trim().Substring(0, 1) + "班", planId, sn,
                                        ScanAll.barCode1, ScanAll.barCode2, ScanAll.barCode3,
                                        ScanAll.barCode4, ScanAll.barCode5, ScanAll.barCode6, stationId,0)<=0)
                                        {
                                            MessageBox.Show("连接数据库失败!");
                                            return;
                                        }
                                    }
                                    
                                    ProScreenFunc.SaveZcCode(barcode, zcPartNo);
                                    ProScreenFunc.AddCompleteCountAndFinish_1(planId);

                                    try
                                    {
                                        if (ConfigurationManager.AppSettings["PrintEnable"].ToLower() == "true")
                                        {
                                            string path = "";
                                            
                                            DataTable headTable = new DataTable();
                                            headTable.Columns.Add("SerialNo");
                                            headTable.Columns.Add("oneBarCode");
                                            headTable.Columns.Add("zcPartNo");
                                            headTable.Columns.Add("zcName");
                                            headTable.Columns.Add("zcState");
                                            DataRow row = headTable.NewRow();
                                            row["SerialNo"] = sn;
                                            row["oneBarCode"] = barcode;
                                            row["zcPartNo"] = zcPartNo;
                                            row["zcName"] = zcPartName;
                                            row["zcState"] = "合格";

                                            string reportName = ConfigurationManager.AppSettings["Printer1"];
                                            headTable.Rows.Add(row);

                                            DataTable dtDetail = ProScreenFunc.GetOtherPart(stationNo, zcPartNo);

                                            ReportHelper rp = new ReportHelper(path, headTable, dtDetail,
                                                (int)GRPaperOrientation.grpoDefault, 1, reportName);
                                            rp.Report.Print(false);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        throw ex;
                                    }

                                    ProScreenFunc.UpdatePrintTime_1(ProScreenFunc.SearchIdByBarCode(barcode));

                                    if (ProScreenFunc.CheckPlanCompleted_1(tagId))
                                    {
                                        LoadPlanScreen(this.Tag.ToString(), "下一计划");
                                    }
                                    else
                                    {
                                        label7.Text = ProScreenFunc.GetCompleteCount_1(tagId);
                                    }
                                    DataTable dt = ProScreenFunc.GetProScreenPlan_1(tagId,stationNo,planId);
                                    if (dt != null && dt.Rows.Count > 0)
                                    {
                                        label7.Text = dt.Rows[0]["CompleteCount"].ToString();
                                    }
                                }
                                else if (!aa )
                                {
                                    MessageBox.Show("入库失败!", "提示", MessageBoxButtons.OK);
                                    return;
                                }
                            }
                        }
                        else
                        {
                            DateTime time = DateTime.Now;
                            string tmp = ProScreenFunc.SerialNo_1(zcPartNo, time.ToString("yyMMdd"));
                            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 (checkBox1.Checked)
                            {
                                if (ProScreenFunc.SavePartAndProduct_1(barcode, productId2, productId1,
                                label2.Text.Trim(), label2.Text.Trim().Substring(0, 1) + "班", planId, sn,
                                ScanAll.barCode1, ScanAll.barCode2, ScanAll.barCode3,
                                ScanAll.barCode4, ScanAll.barCode5, ScanAll.barCode6, stationId,1)<=0)
                                {
                                    MessageBox.Show("连接数据库失败!");
                                    return;
                                }
                            }
                            else
                            {
                                if (ProScreenFunc.SavePartAndProduct_1(barcode, productId2, productId1,
                                label2.Text.Trim(), label2.Text.Trim().Substring(0, 1) + "班", planId, sn,
                                ScanAll.barCode1, ScanAll.barCode2, ScanAll.barCode3,
                                ScanAll.barCode4, ScanAll.barCode5, ScanAll.barCode6, stationId,0) <= 0)
                                {
                                    MessageBox.Show("连接数据库失败!");
                                    return;
                                }
                            }
                            ProScreenFunc.SaveZcCode(barcode, zcPartNo);

                            if (!ProScreenFunc.IsNeedVisual(zcPartNo))
                            {
                                if (stationNo != "ZP95")
                                {
                                    try
                                    {
                                        //toWms = ProScreenFunc.IsToWms(barcode);
                                        //if (!toWms)
                                        //{
                                        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;
                                        partNo = zcPartNo;
                                        batchNo = DateTime.Now.ToString("yyyyMMdd");

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

                                        aa = webService.WMSInterfaceStockIn(barcode, partNo, batchNo, 1);
                                        if (aa)
                                        {
                                            ProScreenFunc.SaveToWmsRecord(barcode);
                                        }
                                        //}
                                    }
                                    catch (Exception ex)
                                    {
                                        LogHelper.WriteErrLogBase("工位:" + label1.Text.Trim() + ",一码到底调用WMS接口:" + ex.ToString(), MethodBase.GetCurrentMethod().Name);
                                    }

                                    if (aa)
                                    {
                                        ProScreenFunc.AddCompleteCountAndFinish_1(planId);

                                        try
                                        {
                                            if (ConfigurationManager.AppSettings["PrintEnable"].ToLower() == "true")
                                            {
                                                string path = "";
                                                //path = Application.StartupPath + @"\ZC.grf";
                                                if (!checkBox1.Checked)
                                                {
                                                    path = Application.StartupPath + @"\ZC.grf";
                                                }
                                                else
                                                {
                                                    path = Application.StartupPath + @"\ZCIndia.grf";
                                                }

                                                DataTable headTable = new DataTable();
                                                headTable.Columns.Add("SerialNo");
                                                headTable.Columns.Add("oneBarCode");
                                                headTable.Columns.Add("zcPartNo");
                                                headTable.Columns.Add("zcName");
                                                headTable.Columns.Add("zcState");
                                                DataRow row = headTable.NewRow();
                                                row["SerialNo"] = sn;
                                                row["oneBarCode"] = barcode;
                                                row["zcPartNo"] = zcPartNo;
                                                row["zcName"] = zcPartName;
                                                row["zcState"] = "";

                                                string reportName = ConfigurationManager.AppSettings["Printer1"];
                                                headTable.Rows.Add(row);

                                                DataTable dtDetail = ProScreenFunc.GetOtherPart(stationNo, zcPartNo);

                                                ReportHelper rp = new ReportHelper(path, headTable, dtDetail,
                                                    (int)GRPaperOrientation.grpoDefault, 1, reportName);
                                                rp.Report.Print(false);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            throw ex;
                                        }

                                        ProScreenFunc.UpdatePrintTime_1(ProScreenFunc.SearchIdByBarCode_1(barcode));


                                        if (ProScreenFunc.CheckPlanCompleted_1(tagId))
                                        {
                                            //LoadScreen();
                                            LoadPlanScreen(this.Tag.ToString(), "下一计划");
                                        }
                                        else
                                        {
                                            label7.Text = ProScreenFunc.GetCompleteCount_1(tagId);
                                        }

                                        DataTable dt = ProScreenFunc.GetProScreenByPlanID_1(tagId);
                                        if (dt != null && dt.Rows.Count > 0)
                                        {
                                            label7.Text = dt.Rows[0]["CompleteCount"].ToString();
                                        }
                                    }
                                    else if (!aa)
                                    {
                                        MessageBox.Show("入库失败!", "提示", MessageBoxButtons.OK);
                                        return;
                                    }
                                }
                                else
                                {
                                    ProScreenFunc.UpdateSignal(2, 1, 1);
                                }
                            }
                            else
                            {
                                if (stationNo == "ZP95")
                                {
                                    ProScreenFunc.UpdateSignal(1, 1, 1);

                                    //timer2.Enabled = true;
                                }
                            }
                        }
                        InitList(ConfigurationManager.AppSettings["StationNo"], label3.Text);
                    }
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }


        #region 补打标签

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

        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.GetZp(barcode);
                    if (dtHg == null || dtHg.Rows.Count < 1)
                    {
                        MessageBox.Show("未装配,不能补打标签!");
                        textBox4_DoubleClick(sender, e);
                        return;
                    }

                    LogSysBLL.AddInfo("条码:" + barcode + "补打标签", MethodBase.GetCurrentMethod());

                    string zcID = dtHg.Rows[0]["ZcID"].ToString();
                    string zcSn = dtHg.Rows[0]["SerialNo"].ToString();
                    ZcPrintLabel zl = ProScreenFunc.GetZcPrintLabel(zcID);
                    if (zl != null && zl.zcPartNo != null && zl.zcName != null)
                    {
                        if (ConfigurationManager.AppSettings["PrintEnable"].ToLower() == "true")
                        {
                            string path = "";
                            if (dtHg.Rows[0]["IsIndia"].ToString() == "0")
                            {
                                path = Application.StartupPath + @"\ZC.grf";
                            }
                            else
                            {
                                path = Application.StartupPath + @"\ZCIndia.grf";
                            }

                            DataTable headTable = new DataTable();
                            headTable.Columns.Add("SerialNo");
                            headTable.Columns.Add("oneBarCode");
                            headTable.Columns.Add("zcPartNo");
                            headTable.Columns.Add("zcName");
                            headTable.Columns.Add("zcState");
                            DataRow row = headTable.NewRow();
                            row["SerialNo"] = zcSn;
                            row["oneBarCode"] = barcode;
                            row["zcPartNo"] = zl.zcPartNo;
                            row["zcName"] = zl.zcName;
                            //row["zcState"] = dtHg.Rows[0]["ToVisual"].ToString() == "1" ? "" : "合格";
                            row["zcState"] = dtHg.Rows[0]["Flag"].ToString() == "0" ? "不合格" : "合格";

                            string reportName = ConfigurationManager.AppSettings["Printer1"];
                            headTable.Rows.Add(row);

                            DataTable dtDetail = ProScreenFunc.GetOtherPart(stationNo, zl.zcPartNo);

                            ReportHelper rp = new ReportHelper(path, headTable, dtDetail,
                                (int)GRPaperOrientation.grpoDefault, 1, reportName);
                            rp.Report.Print(false);
                            textBox4.SelectAll();
                        }
                    }
                    else
                    {
                        MessageBox.Show("根据总成号找不到对应名称,请维护基础数据!");
                        textBox4_DoubleClick(sender, e);
                    }
                }
                catch (Exception ex)
                {
                    LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                }
            }
        }

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

        #endregion


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

        private void textBox3_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    string zcId = "", zcPartNo = "",tempPlanId="";

                    if (string.IsNullOrWhiteSpace(textBox3.Text))
                    {
                        MessageBox.Show("条码不能为空");
                        textBox3.SelectAll();
                        textBox3.Focus();
                        return;
                    }

                    string barcode = "";
                    if (barcode.Contains("."))
                    {
                        barcode = ProScreenFunc.UniteBarCodeToOne(barcode);
                    }
                    else
                    {
                        barcode = textBox3.Text.Trim();
                    }

                    DataTable dtHg = ProScreenFunc.GetZp(barcode);
                    if (dtHg == null || dtHg.Rows.Count < 1)
                    {
                        MessageBox.Show("未装配,不能删除!");
                        textBox3.SelectAll();
                        textBox3.Focus();
                        return;
                    }
                    else
                    {
                        if (dtHg.Rows[0]["Flag"].ToString()=="0")
                        {
                            MessageBox.Show("该产品已是不合格件,无需操作!");
                            textBox3_DoubleClick(sender, e);
                            return;
                        }
                        tempPlanId = dtHg.Rows[0]["PlanID"].ToString();
                    }

                    ZcPrintLabel zl = ProScreenFunc.GetZcPrintLabel(zcId);
                    if (zl != null)
                    {
                        zcPartNo = zl.zcPartNo;
                    }

                    ProScreenFunc.UpdateFlag(barcode, 0);
                    ProScreenFunc.AddBadCount_1(tempPlanId);


                    if (ProScreenFunc.CheckPlanCompleted_1(this.Tag.ToString()))
                    {
                        LoadPlanScreen(this.Tag.ToString(), "下一计划");
                    }
                    else
                    {
                        label7.Text = ProScreenFunc.GetCompleteCount_1(this.Tag.ToString());
                    }

                    DataTable dt = ProScreenFunc.GetProScreenPlan_1(this.Tag.ToString(), stationNo, planID);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        label7.Text = dt.Rows[0]["CompleteCount"].ToString();
                    }

                    

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

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

        /// <summary>
        /// 重新数据检测
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult result = MessageBox.Show("是否重新视觉检测?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    ProScreenFunc.UpdateSignal(2, 1, 1);
                    int a = ProScreenFunc.VisualReset_1(stationId);
                    if (a > 0)
                    {
                        MessageBox.Show("重置成功!");
                    }
                    else
                    {
                        MessageBox.Show("重置失败!");
                    }
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        private void label9_Click(object sender, EventArgs e)
        {
            if (ConfigurationManager.AppSettings["IsHaveVisual"] == "1")
            {
                SqlDependency.Stop(SqlHelper.SqlConnString);
            }

            Environment.Exit(0);
        }

        private void InitList(string stationNo, string partNo)
        {
            try
            {
                listView1.Items.Clear();
                DataTable dt = ProScreenFunc.GetOtherPart(stationNo, partNo);
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        ListViewItem lvi = new ListViewItem(dt.Rows[i]["PartNo"].ToString());
                        lvi.SubItems.Add(dt.Rows[i]["PartName"].ToString());

                        if (!string.IsNullOrWhiteSpace(dt.Rows[i]["PartNo"].ToString()) && !string.IsNullOrWhiteSpace(dt.Rows[i]["IsCheck"].ToString()))
                        {
                            lvi.SubItems.Add("未通过");
                        }
                        lvi.SubItems.Add(dt.Rows[i]["Qty"].ToString());

                        listView1.Items.Add(lvi);
                    }
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        public void SetPage(DataTable dt, string stationNo)
        {
            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)
            {


                label1.Text = dt.Rows[0]["Des1"].ToString();
                label2.Text = dt.Rows[0]["OrderNo"].ToString();
                label3.Text = dt.Rows[0]["PartNo"].ToString();
                label4.Text = dt.Rows[0]["ProductName"].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) + "班";

                this.Tag = dt.Rows[0]["ID"].ToString(); 
                planID = this.Tag.ToString();
                textBox1.Tag = dt.Rows[0]["ProductID"].ToString();
                textBox1.Text = "";

                InitList(stationNo, label3.Text);

            }
        }

        /// <summary>
        /// 初始化关键零件列表
        /// </summary>
        /// <param name="stationNo">工位编号</param>
        /// <param name="partNo">总成零件号</param>
        
    }
}