using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MESClassLibrary.BLL.BasicInfo;
using System.Net.NetworkInformation;
using System.IO;
using GlacialComponents.Controls;
using MESClassLibrary.Model;
//using grdesLib;
//using grproLib;
using System.Configuration;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using gregn6Lib;
using MESClassLibrary.BLL.Log;
using MESClassLibrary.DAL;
using MESClassLibrary.EFModel;

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

        public string oldTime = "", newTime = "";
        public static bool IsStart = true;
        public string planID = "";

        private void FrmBarCode_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            Thread t = new Thread(new ThreadStart(TimeGo));
            t.Start();
            timer1.Interval = Program.interVal;
            //this.WindowState = FormWindowState.Maximized;
            //label2.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); ;
            label6.Text = Program.station;
            label8.Text = Program.OperatorName;
            //comboBox1.Text = "A班";
            initProduct();
            //textBox1.Text = DateTime.Now.ToString("yyMMdd");

            initBarCode();
            DateTime aa = GetDateTime();

            if (GetDateTime().Hour >= 8 && GetDateTime().Hour < 20)
            {
                Program.Shift = "A班";
                Program.ProductDate = DateTime.Now.ToString("yyyy-MM-dd");
                
            }
            else
            {
                Program.Shift = "B班";
                if (GetDateTime().Hour >= 0 && GetDateTime().Hour < 8)
                {
                    Program.ProductDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                }
                else
                {
                    Program.ProductDate = DateTime.Now.ToString("yyyy-MM-dd");
                }
            }
            comboBox1.Text = Program.Shift;

            textBox1.Text = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) +
                            Program.ProductDate.Substring(8, 2);
            if (IsStart==false)
            {
                timer1.Enabled = false;
                label12.Text = "开始打印";
                label12.BackColor = System.Drawing.Color.Gray;
            }

            else
            {
                timer1.Enabled = true;
                label12.Text = "暂停打印";
                label12.BackColor = System.Drawing.Color.DeepSkyBlue;
            }
        }

        private void initProduct()
        {
            comboBox2.Items.Clear();

            ProductBLL bll=new ProductBLL();

            DataTable dt = bll.SearchInfoByType("2000", Program.station);
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    comboBox2.Items.Add(dt.Rows[i]["ProductName"].ToString());
                }
            }
            dt.Dispose();
        }

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

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

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

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

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

        private void timer1_Tick(object sender, EventArgs e)
        {
            BarCodeBLL Barbll = new BarCodeBLL();
            BarCodeModel md = new BarCodeModel();
            timer1.Stop();
            Ping p1 = new Ping();
            bool status = false;
            string code = "",OneCode="";
            string newcode = "", newcode1 = "",NewOneCode = "", NewOneCode1 = "";
            string[] part=new string[3];
            GridppReport report = new GridppReport();
            long a = 0;
            

            ProductOfInjectionBLL pbll = new ProductOfInjectionBLL();
            ProductOfInjectionModel pmd = new ProductOfInjectionModel();
            InjectionPlanBLL bll = new InjectionPlanBLL();
            BarCodeBLL brbll = new BarCodeBLL();
            ProductBLL productBll =new ProductBLL();

            DataTable pdt3 = null;

            if (GetDateTime().Hour >= 8 && GetDateTime().Hour < 20)
            {
                Program.Shift = "A班";
                Program.ProductDate = DateTime.Now.ToString("yyyy-MM-dd");
            }
            else
            {
                Program.Shift = "B班";
                if (GetDateTime().Hour >= 0 && GetDateTime().Hour < 8)
                {
                    Program.ProductDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                }
                else
                {
                    Program.ProductDate = DateTime.Now.ToString("yyyy-MM-dd");
                }
            }

            comboBox1.Text = Program.Shift;
            textBox1.Text = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) +
                            Program.ProductDate.Substring(8, 2);
            LogHelper.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            try
            {
                PingReply reply = p1.Send(Program.IP); //发送主机名或Ip地址
                StringBuilder sbuilder;
                if (reply.Status == IPStatus.Success)
                {
                    //读取称重文件
                    status = Upload.DoConnComputer(Program.IP, Program.WeightFolder, Program.WeightUser, Program.WeightPsw);
                    if (status == true)
                    {
                        //DirectoryInfo theFolder = new DirectoryInfo(@"\\192.168.1.16\aa");
                        //DirectoryInfo theFolder = new DirectoryInfo(@"\\" + Program.IP + "\\UserData");
                        DirectoryInfo theFolder = new DirectoryInfo(@"\\" + Program.IP + "\\" + Program.WeightFolder);
                        //string filename = theFolder.ToString() + "\\ProdHisFile.csv";
                        string filename = theFolder.ToString() + "\\" + Program.WeightFile;

                        FileInfo fl = new FileInfo(filename);
                        

                        if (oldTime == "" || oldTime == "none")
                        {
                            oldTime = fl.LastWriteTime.ToString("yy-MM-dd HH:mm:ss fff");
                        }
                        else
                        {
                            newTime = fl.LastWriteTime.ToString("yy-MM-dd HH:mm:ss fff");
                            if (newTime != oldTime)
                            {
                               #region 生成打印条码  1、当前计划的存货代码2、barcode表根据存货代码查找今天的流水

                                DataTable dt = bll.SearchInfoByName(Program.station);
                                if (dt != null && dt.Rows.Count > 0)
                                {
                                    planID = dt.Rows[0]["InjectionPlanID"].ToString();
                                    DataTable dt2 = null;
                                    if (dt.Rows[0]["ProductName"].ToString().IndexOf("门槛") != -1)
                                    {
                                        //插入两条数据,一个左门槛,一个右门槛
                                        dt2 = brbll.SearchInfoByStock(dt.Rows[0]["StockNo"].ToString().Trim());
                                        if (dt2 != null && dt2.Rows.Count > 0)
                                        {
                                            code = dt2.Rows[0]["BarCode"].ToString().Trim();
                                            newcode = code.Substring(0, code.Length - 4) +
                                                      (Convert.ToInt32(code.Substring(code.Length - 4, 4)) + 1).ToString()
                                                      .PadLeft(4, '0');
                                            OneCode = dt2.Rows[0]["OneBarCode"].ToString().Trim();
                                            NewOneCode = OneCode.Substring(0, OneCode.Length - 4) + (Convert.ToInt32(OneCode.Substring(OneCode.Length - 4, 4)) + 1).ToString().PadLeft(4, '0');
                                        }
                                        else
                                        {
                                            //按照二维码的生成规则
                                            newcode = dt.Rows[0]["PartNo"].ToString().Trim() + "." + Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2) + "." + "0001";
                                            NewOneCode = dt.Rows[0]["StockNo"].ToString().Trim() + Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2) + "0001";
                                        }

                                        ProductBLL prbll = new ProductBLL();
                                        DataTable prdt = null;
                                        if (dt.Rows[0]["ProductName"].ToString().IndexOf("左门槛") != -1)
                                        {

                                            #region 计划为左门槛
                                            prdt = prbll.SearchInfoByProductName(
                                                                                    dt.Rows[0]["ProductName"].ToString().TrimEnd()
                                                                                        .Substring(0, dt.Rows[0]["ProductName"].ToString().TrimEnd().Length - 3) + "右门槛");
                                            if (prdt != null && prdt.Rows.Count > 0)
                                            {
                                                dt2 = brbll.SearchInfoByStock(prdt.Rows[0]["StockNo"].ToString().Trim());
                                                if (dt2 != null && dt2.Rows.Count > 0)
                                                {
                                                    code = dt2.Rows[0]["BarCode"].ToString().Trim();
                                                    newcode1 = code.Substring(0, code.Length - 4) +
                                                              (Convert.ToInt32(code.Substring(code.Length - 4, 4)) + 1).ToString()
                                                              .PadLeft(4, '0');
                                                    OneCode = dt2.Rows[0]["OneBarCode"].ToString().Trim();
                                                    NewOneCode1 = OneCode.Substring(0, OneCode.Length - 4) + (Convert.ToInt32(OneCode.Substring(OneCode.Length - 4, 4)) + 1).ToString().PadLeft(4, '0');
                                                }
                                                else
                                                {
                                                    //按照二维码的生成规则
                                                    newcode1 = prdt.Rows[0]["PartNo"].ToString().Trim() + "." + Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2) + "." + "0001";
                                                    NewOneCode1 = prdt.Rows[0]["StockNo"].ToString().Trim() + Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2) + "0001";
                                                }

                                                #region 如果顺序号不一致取最大的
                                                if (Convert.ToInt32(newcode.Substring(newcode.Length - 4, 4)) !=
                                                                                            Convert.ToInt32(newcode1.Substring(newcode1.Length - 4, 4)))
                                                {
                                                    if (Convert.ToInt32(newcode.Substring(newcode.Length - 4, 4)) > Convert.ToInt32(newcode1.Substring(newcode1.Length - 4, 4)))
                                                    {
                                                        newcode1 = newcode1.Substring(0, newcode1.Length - 4) +
                                                                   newcode.Substring(newcode.Length - 4, 4);
                                                        NewOneCode1 = NewOneCode1.Substring(0, NewOneCode1.Length - 4) + newcode.Substring(newcode.Length - 4, 4);
                                                    }
                                                    else
                                                    {
                                                        newcode = newcode.Substring(0, newcode.Length - 4) + newcode1.Substring(newcode1.Length - 4, 4);
                                                        NewOneCode = NewOneCode.Substring(0, NewOneCode.Length - 4) + newcode1.Substring(newcode1.Length - 4, 4);
                                                    }
                                                } 
                                                #endregion

                                                #region 插入tb_barcode表记录

                                                part = newcode.Split('.');
                                                md.ID = Guid.NewGuid().ToString();
                                                md.StationID = dt.Rows[0]["StationID"].ToString();
                                                md.OneBarCode = NewOneCode;
                                                md.BarCode = newcode;
                                                md.StockNo = dt.Rows[0]["StockNo"].ToString();
                                                md.PrintType = 0;
                                                md.PlanID = planID;

                                                DataTable pdt = productBll.SearchIsImportByStockNo(NewOneCode.Substring(0, 10));
                                                if (pdt != null && pdt.Rows.Count > 0)
                                                {
                                                    if (pdt.Rows[0]["isImport"].ToString() == "1")
                                                    {
                                                        md.Import = "国产料Kingfa";
                                                    }
                                                    else
                                                    {
                                                        md.Import = "";
                                                    }
                                                }

                                                Barbll.Add_Info(md);
                                                #endregion

                                                #region 打印条码

                                                report.Register("");
                                                report.LoadFromFile(@"D:\111 - 副本.grf");
                                                report.ConnectionString = ConfigurationManager.ConnectionStrings["report"].ToString();
                                                report.Initialize += new _IGridppReportEvents_InitializeEventHandler(ReportInitialize);
                                                report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
                                                //report.DesignPaperOrientation = GRPaperOrientation.grpoLandscape;
                                                //report.PrintPreview(true);
                                                report.Print(false);
                                                #endregion

                                                Barbll.Update_Info(md);


                                                #region 插入tb_barcode表记录

                                                part = newcode.Split('.');
                                                md.ID = Guid.NewGuid().ToString();
                                                md.StationID = dt.Rows[0]["StationID"].ToString();
                                                md.OneBarCode = NewOneCode1;
                                                md.BarCode = newcode1;
                                                md.StockNo = prdt.Rows[0]["StockNo"].ToString().Trim();
                                                md.PrintType = 0;
                                                md.PlanID = planID;

                                                DataTable pdt1 = productBll.SearchIsImportByStockNo(NewOneCode.Substring(0, 10));
                                                if (pdt1 != null && pdt1.Rows.Count > 0)
                                                {
                                                    if (pdt1.Rows[0]["isImport"].ToString() == "1")
                                                    {
                                                        md.Import = "国产料Kingfa";
                                                    }
                                                    else
                                                    {
                                                        md.Import = "";
                                                    }
                                                }

                                                Barbll.Add_Info(md);

                                                #endregion

                                                #region 打印条码

                                                report.Register("");
                                                report.LoadFromFile(@"D:\111 - 副本.grf");
                                                report.ConnectionString = ConfigurationManager.ConnectionStrings["report"].ToString();
                                                report.Initialize += new _IGridppReportEvents_InitializeEventHandler(ReportInitialize);
                                                report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
                                                //report.DesignPaperOrientation = GRPaperOrientation.grpoLandscape;
                                                //report.PrintPreview(true);
                                                report.Print(false);
                                                #endregion

                                                Barbll.Update_Info(md);
                                            } 
                                            #endregion
                                        }

                                        else
                                        {
                                            #region 计划为右门槛
                                            prdt = prbll.SearchInfoByProductName(
                                                                                    dt.Rows[0]["ProductName"].ToString().TrimEnd()
                                                                                        .Substring(0, dt.Rows[0]["ProductName"].ToString().TrimEnd().Length - 3) + "左门槛");
                                            if (prdt != null && prdt.Rows.Count > 0)
                                            {
                                                dt2 = brbll.SearchInfoByStock(prdt.Rows[0]["StockNo"].ToString().Trim());
                                                if (dt2 != null && dt2.Rows.Count > 0)
                                                {
                                                    code = dt2.Rows[0]["BarCode"].ToString().Trim();
                                                    newcode1 = code.Substring(0, code.Length - 4) +
                                                              (Convert.ToInt32(code.Substring(code.Length - 4, 4)) + 1).ToString()
                                                              .PadLeft(4, '0');
                                                    OneCode = dt2.Rows[0]["OneBarCode"].ToString().Trim();
                                                    NewOneCode1 = OneCode.Substring(0, OneCode.Length - 4) + (Convert.ToInt32(OneCode.Substring(OneCode.Length - 4, 4)) + 1).ToString().PadLeft(4, '0');
                                                }
                                                else
                                                {
                                                    //按照二维码的生成规则
                                                    newcode1 = prdt.Rows[0]["PartNo"].ToString().Trim() + "." + Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2) + "." + "0001";
                                                    NewOneCode1 = prdt.Rows[0]["StockNo"].ToString().Trim() + Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2) + "0001";
                                                }

                                                #region 如果顺序号不一致取最大的
                                                if (Convert.ToInt32(newcode.Substring(newcode.Length - 4, 4)) !=
                                                    Convert.ToInt32(newcode1.Substring(newcode1.Length - 4, 4)))
                                                {
                                                    if (Convert.ToInt32(newcode.Substring(newcode.Length - 4, 4)) > Convert.ToInt32(newcode1.Substring(newcode1.Length - 4, 4)))
                                                    {
                                                        newcode1 = newcode1.Substring(0, newcode1.Length - 4) +
                                                                   newcode.Substring(newcode.Length - 4, 4);
                                                        NewOneCode1 = NewOneCode1.Substring(0, NewOneCode1.Length - 4) + newcode.Substring(newcode.Length - 4, 4);
                                                    }
                                                    else
                                                    {
                                                        newcode = newcode.Substring(0, newcode.Length - 4) + newcode1.Substring(newcode1.Length - 4, 4);
                                                        NewOneCode = NewOneCode.Substring(0, NewOneCode.Length - 4) + newcode1.Substring(newcode1.Length - 4, 4);
                                                    }
                                                }
                                                #endregion

                                                #region 插入tb_barcode表记录

                                                part = newcode.Split('.');
                                                md.ID = Guid.NewGuid().ToString();
                                                md.StationID = dt.Rows[0]["StationID"].ToString();
                                                md.OneBarCode = NewOneCode;
                                                md.BarCode = newcode;
                                                md.StockNo = dt.Rows[0]["StockNo"].ToString();
                                                md.PrintType = 0;
                                                md.PlanID = planID;

                                                DataTable pdt = productBll.SearchIsImportByStockNo(NewOneCode.Substring(0, 10));
                                                if (pdt != null && pdt.Rows.Count > 0)
                                                {
                                                    if (pdt.Rows[0]["isImport"].ToString() == "1")
                                                    {
                                                        md.Import = "国产料Kingfa";
                                                    }
                                                    else
                                                    {
                                                        md.Import = "";
                                                    }
                                                }

                                                Barbll.Add_Info(md);
                                                #endregion

                                                #region 打印条码

                                                report.Register("");
                                                report.LoadFromFile(@"D:\111 - 副本.grf");
                                                report.ConnectionString = ConfigurationManager.ConnectionStrings["report"].ToString();
                                                report.Initialize += new _IGridppReportEvents_InitializeEventHandler(ReportInitialize);
                                                report.Print(false);
                                                #endregion

                                                Barbll.Update_Info(md);

                                                #region 插入tb_barcode表记录

                                                part = newcode.Split('.');
                                                md.ID = Guid.NewGuid().ToString();
                                                md.StationID = dt.Rows[0]["StationID"].ToString();
                                                md.OneBarCode = NewOneCode1;
                                                md.BarCode = newcode1;
                                                md.StockNo = prdt.Rows[0]["StockNo"].ToString();
                                                md.PrintType = 0;
                                                md.PlanID = planID;
                                                DataTable pdt2 = productBll.SearchIsImportByStockNo(NewOneCode.Substring(0, 10));
                                                if (pdt2 != null && pdt2.Rows.Count > 0)
                                                {
                                                    if (pdt2.Rows[0]["isImport"].ToString() == "1")
                                                    {
                                                        md.Import = "国产料Kingfa";
                                                    }
                                                    else
                                                    {
                                                        md.Import = "";
                                                    }
                                                }

                                                Barbll.Add_Info(md);

                                                #endregion
                                                
                                                #region 打印条码

                                                report.Register("");
                                                report.LoadFromFile(@"D:\111 - 副本.grf");
                                                report.ConnectionString = ConfigurationManager.ConnectionStrings["report"].ToString();
                                                report.Initialize += new _IGridppReportEvents_InitializeEventHandler(ReportInitialize);
                                                report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
                                                //report.DesignPaperOrientation = GRPaperOrientation.grpoLandscape;
                                                //report.PrintPreview(true);
                                                report.Print(false);
                                                #endregion

                                                Barbll.Update_Info(md);

                                            } 
                                            #endregion
                                        }
                                    }
                                    else
                                    {
                                        #region 不是门槛
                                        dt2 = brbll.SearchInfoByStock(dt.Rows[0]["StockNo"].ToString().Trim());
                                        if (dt2 != null && dt2.Rows.Count > 0)
                                        {
                                            code = dt2.Rows[0]["BarCode"].ToString().Trim();
                                            newcode = code.Substring(0, code.Length - 4) +
                                                      (Convert.ToInt32(code.Substring(code.Length - 4, 4)) + 1).ToString()
                                                      .PadLeft(4, '0');
                                            OneCode = dt2.Rows[0]["OneBarCode"].ToString().Trim();
                                            NewOneCode = OneCode.Substring(0, OneCode.Length - 4) + (Convert.ToInt32(OneCode.Substring(OneCode.Length - 4, 4)) + 1).ToString().PadLeft(4, '0');
                                        }
                                        else
                                        {
                                            //按照二维码的生成规则
                                            newcode = dt.Rows[0]["PartNo"].ToString().Trim() + "." + Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2) + "." + "0001";
                                            NewOneCode = dt.Rows[0]["StockNo"].ToString().Trim() + Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2) + "0001";
                                        }
                                        dt2.Dispose();
                                        //插入tb_barcode表记录

                                        part = newcode.Split('.');
                                        md.ID = Guid.NewGuid().ToString();
                                        md.StationID = dt.Rows[0]["StationID"].ToString();
                                        md.OneBarCode = NewOneCode;
                                        md.BarCode = newcode;
                                        md.StockNo = dt.Rows[0]["StockNo"].ToString();
                                        md.PrintType = 0;
                                        md.PlanID = planID;
                                        DataTable pdt = productBll.SearchIsImportByStockNo(NewOneCode.Substring(0, 10));
                                        if (pdt != null && pdt.Rows.Count > 0)
                                        {
                                            if (pdt.Rows[0]["isImport"].ToString() == "1")
                                            {
                                                md.Import = "国产料Kingfa";
                                            }
                                            else
                                            {
                                                md.Import = "";
                                            }
                                        }
                                        Barbll.Add_Info(md);
                                        dt.Dispose();


                                        #region 打印条码

                                        report.Register("");
                                        report.LoadFromFile(@"D:\111 - 副本.grf");
                                        report.ConnectionString = ConfigurationManager.ConnectionStrings["report"].ToString();
                                        report.Initialize += new _IGridppReportEvents_InitializeEventHandler(ReportInitialize);
                                        report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
                                        //report.DesignPaperOrientation = GRPaperOrientation.grpoLandscape;
                                        //report.PrintPreview(true);
                                        report.Print(false);
                                        #endregion

                                        Barbll.Update_Info(md); 
                                        #endregion
                                    }
                                }

                                #endregion
                                oldTime = newTime;
                            }
                        }

                        initBarCode();
                        
                    }
                    else
                    {
                        MessageBox.Show("连接称重仪失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    MessageBox.Show("连接称重仪失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }

            timer1.Interval =  Program.interVal; ;
            timer1.Start();
        }

        

        private void label12_Click(object sender, EventArgs e)
        {
            try
            {
                if (label12.Text == "暂停打印")
                {
                    DialogResult result = MessageBox.Show("确认暂停打印?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    if (result == DialogResult.OK)
                    {
                        timer1.Stop();
                        IsStart = false;
                        label12.Text = "开始打印";
                        label12.BackColor = System.Drawing.Color.Gray;
                    }
                    else
                    {
                        return;
                    }
                }

                else
                {
                    DialogResult result = MessageBox.Show("确认开始打印?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    if (result == DialogResult.OK)
                    {
                        IsStart = true;
                        timer1.Start();
                        label12.Text = "暂停打印";
                        label12.BackColor = System.Drawing.Color.DeepSkyBlue;
                    }
                    else
                    {
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        /// <summary>
        /// 手工打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label19_Click(object sender, EventArgs e)
        {
            string code = "",stationID="",OneCode="";
            string newcode = "",partNo="",stockNo="",NewOneCode="";

            try
            {
                #region 数据合法性判断

                if (comboBox2.Text.Trim() == "")
                {
                    MessageBox.Show("请选择产品!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (textBox1.Text.Trim() == "")
                {
                    MessageBox.Show("请输入批次!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (textBox1.Text.Trim().Length != 6)
                {
                    MessageBox.Show("批次格式不正确!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (textBox2.Text.Trim() == "")
                {
                    MessageBox.Show("请输入数量!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (!IsNumeric(textBox2.Text.Trim()))
                {
                    MessageBox.Show("数量格式不正确!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (Convert.ToInt32(textBox2.Text.Trim()) > 10)
                {
                    MessageBox.Show("数量不能大于10!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                #endregion

                #region 获取工位编号

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

                DialogResult result = MessageBox.Show("确定手工打印条码?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    #region 生成条码

                    ProductBLL pbll = new ProductBLL();

                    //查询零件号
                    DataTable pdt = pbll.SearchInfoByName(comboBox2.Text, "2000");
                    if (pdt != null && pdt.Rows.Count > 0)
                    {
                        partNo = pdt.Rows[0]["PartNo"].ToString().Trim();

                        stockNo = pdt.Rows[0]["StockNo"].ToString().Trim();

                    }

                    pdt.Dispose();

                    //根据零件号、批次号查找

                    BarCodeBLL bll = new BarCodeBLL();
                    BarCodeModel md = new BarCodeModel();

                    DataTable dt = bll.SearchSerialNoByBarCode(partNo + "." + textBox1.Text.Trim());
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        OneCode = dt.Rows[0]["OneBarCode"].ToString().Trim();
                        code = dt.Rows[0]["BarCode"].ToString().TrimEnd();
                        for (int i = 1; i <= Convert.ToInt32(textBox2.Text.Trim()); i++)
                        {
                            newcode = code.Substring(0, code.Length - 4) +
                                      (Convert.ToInt32(code.Substring(code.Length - 4, 4)) + i)
                                      .ToString()
                                      .PadLeft(4, '0');
                            NewOneCode = OneCode.Substring(0, OneCode.Length - 4) +
                                         (Convert.ToInt32(OneCode.Substring(OneCode.Length - 4, 4)) + i).ToString()
                                         .PadLeft(4, '0');
                            string[] part = newcode.Split('.');
                            //存入tb_BarCode表
                            md.ID = Guid.NewGuid().ToString();
                            md.StationID = stationID;
                            md.OneBarCode = NewOneCode;
                            md.BarCode = newcode;

                            md.StockNo = stockNo;
                            md.PrintType = 1;

                            DataTable pdt1 = pbll.SearchIsImportByStockNo(NewOneCode.Substring(0, 10));
                            if (pdt1 != null && pdt1.Rows.Count > 0)
                            {
                                if (pdt1.Rows[0]["isImport"].ToString() == "1")
                                {
                                    md.Import = "国产料Kingfa";
                                }
                                else
                                {
                                    md.Import = "";
                                }
                            }
                            //md.CreateTime = GetDateTime();
                            //if (NewOneCode.Substring(0, 10) == "2200000064" ||
                            //    NewOneCode.Substring(0, 10) == "2200000093" ||
                            //    NewOneCode.Substring(0, 10) == "2200000096" ||
                            //    NewOneCode.Substring(0, 10) == "2200000084" ||
                            //    NewOneCode.Substring(0, 10) == "2200000090" ||
                            //    NewOneCode.Substring(0, 10) == "2200000052")
                            //{
                            //    md.Import = "国产料Kingfa";
                            //}
                            //else
                            //{
                            //    md.Import = "";
                            //}

                            bll.Add_Info(md);


                            #region 打印条码

                            GridppReport report = new GridppReport();

                            report.Register("");
                            report.LoadFromFile(@"D:\111 - 副本.grf");
                            report.ConnectionString = ConfigurationManager.ConnectionStrings["report"].ToString();
                            report.Initialize += new _IGridppReportEvents_InitializeEventHandler(ReportInitialize);
                            report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
                            //report.DesignPaperSize = 256;
                            //report.DesignPaperWidth = 5;
                            //report.DesignPaperLength = 4;
                            //report.DesignPaperOrientation = GRPaperOrientation.grpoLandscape;
                            //report.Graphics.r
                            //report.PrintPreview(true);
                            report.Print(false);

                            #endregion

                            //md.PrintTime = GetDateTime();
                            bll.Update_Info(md);

                            #region 更新产量表、计划表

                            //ProductOfInjectionBLL InjectionBll = new ProductOfInjectionBLL();
                            //ProductOfInjectionModel pmd = new ProductOfInjectionModel();


                            //pmd.ID = Guid.NewGuid().ToString();
                            //pmd.StationID = md.StationID;
                            //pmd.ProductDate = Program.ProductDate;
                            //pmd.ClassName = Program.Shift;
                            //pmd.StockNo = md.StockNo;
                            //pmd.PartNo = part[0];
                            //pmd.ProductCount = 1;
                            //pmd.BadCount = 0;
                            //pmd.PlanID = planID;
                            //DataTable pdt1 = InjectionBll.SearchCountByInfo(md.StationID, Program.ProductDate, comboBox1.Text,
                            //    md.StockNo, part[0]);

                            //if (pdt1 != null && pdt1.Rows.Count > 0)
                            //{
                            //    //跟新
                            //    InjectionBll.Update_Info(pmd);
                            //}
                            //else
                            //{

                            //    //插入
                            //    InjectionBll.Add_Info(pmd);
                            //}
                            //pdt1.Dispose();

                            #region 注释掉

                            //InjectionPlanBLL ibll = new InjectionPlanBLL();
                            //InjectionPlanModel imd = new InjectionPlanModel();

                            //imd.CompleteCount = 1;
                            //imd.StationID = md.StationID;
                            //imd.StockNo = md.StockNo;
                            //ibll.UpdateCount(imd);

                            #endregion

                            #endregion
                        }
                    }
                    else
                    {
                        for (int i = 1; i <= Convert.ToInt32(textBox2.Text.Trim()); i++)
                        {
                            newcode = partNo + "." + textBox1.Text.Trim() + "." + i.ToString().PadLeft(4, '0');
                            NewOneCode = stockNo + textBox1.Text.Trim() + i.ToString().PadLeft(4, '0');
                            string[] part = newcode.Split('.');
                            //存入tb_BarCode表
                            md.ID = Guid.NewGuid().ToString();
                            md.StationID = stationID;
                            md.StockNo = stockNo;
                            md.OneBarCode = NewOneCode;
                            md.BarCode = newcode;
                            md.PrintType = 1;
                            bll.Add_Info(md);

                            #region 打印条码

                            GridppReport report = new GridppReport();

                            report.Register("");
                            report.LoadFromFile(@"D:\111 - 副本.grf");
                            report.ConnectionString = ConfigurationManager.ConnectionStrings["report"].ToString();
                            report.Initialize += new _IGridppReportEvents_InitializeEventHandler(ReportInitialize);
                            report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
                            //report.DesignPaperSize = 256;
                            //report.DesignPaperWidth = 5;
                            //report.DesignPaperLength = 4;
                            //report.DesignPaperOrientation = GRPaperOrientation.grpoLandscape;
                            //report.PrintPreview(true);
                            report.Print(false);

                            #endregion

                            #region 更新产量表、计划表

                            //ProductOfInjectionBLL InjectionBll = new ProductOfInjectionBLL();
                            //ProductOfInjectionModel pmd = new ProductOfInjectionModel();

                            //pmd.ID = Guid.NewGuid().ToString();
                            //pmd.StationID = md.StationID;
                            //pmd.ProductDate = Program.ProductDate;
                            //pmd.ClassName = Program.Shift;
                            //pmd.StockNo = md.StockNo;
                            //pmd.PartNo = part[0];
                            //pmd.ProductCount = 1;
                            //pmd.BadCount = 0;
                            //pmd.PlanID = planID;
                            //DataTable pdt1 = InjectionBll.SearchCountByInfo(md.StationID, Program.ProductDate, comboBox1.Text,
                            //    md.StockNo, part[0]);

                            //if (pdt1 != null && pdt1.Rows.Count > 0)
                            //{
                            //    //跟新
                            //    InjectionBll.Update_Info(pmd);
                            //}
                            //else
                            //{

                            //    //插入
                            //    InjectionBll.Add_Info(pmd);
                            //}
                            //pdt1.Dispose();

                            #region 注释掉

                            //InjectionPlanBLL ibll = new InjectionPlanBLL();
                            //InjectionPlanModel imd = new InjectionPlanModel();

                            //imd.CompleteCount = 1;
                            //imd.StationID = md.StationID;
                            //imd.StockNo = md.StockNo;
                            //ibll.UpdateCount(imd);

                            #endregion

                            #endregion

                            bll.Update_Info(md);
                        }
                    }

                    #endregion

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

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

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

                    DataTable dt = bll.SearchInfoByBarCode(code);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        md.ID = Guid.NewGuid().ToString();
                        md.BarCode = code;
                        md.StationID = dt.Rows[0]["StationID"].ToString();
                        md.StockNo = dt.Rows[0]["StockNo"].ToString();
                        md.OneBarCode = dt.Rows[0]["OneBarCode"].ToString();
                        md.PrintType = 2;
                        //md.CreateTime = GetDateTime();

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

                        //if (md.StockNo == "2200000064" || md.StockNo == "2200000093" || md.StockNo == "2200000096" ||
                        //    md.StockNo == "2200000052")
                        //{
                        //    md.Import = "国产料Kingfa";
                        //}
                        //else
                        //{
                        //    md.Import = "";
                        //}
                    }
                    dt.Dispose();
                    bll.Add_Info(md);
                    glacialList1.SelectedItems.Clear();
                    initBarCode();

                    #region 打印条码

                    GridppReport report = new GridppReport();

                    report.Register("");
                    report.LoadFromFile(@"D:\111 - 副本.grf");
                    report.ConnectionString = ConfigurationManager.ConnectionStrings["report"].ToString();
                    report.Initialize += new _IGridppReportEvents_InitializeEventHandler(ReportInitialize);
                    report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
                    //report.DesignPaperSize = 256;
                    //report.DesignPaperWidth = 5;
                    //report.DesignPaperLength = 4;
                    //report.DesignPaperOrientation = GRPaperOrientation.grpoLandscape;
                    //report.PrintPreview(true);
                    report.Print(false);
                    #endregion
                    //md.PrintTime = GetDateTime();
                    bll.Update_Info(md);
                    initBarCode();
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
            
        }


        public DateTime GetDateTime()
        {
            string sql = "";
            DateTime time;
            DataTable dt;
            try
            {
                sql = @"select  convert(char(23),getdate(),121) as time";

                dt = SqlHelper.ExecuteDataset(SqlHelper.GetConnSting(), CommandType.Text, sql, null).Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    //time = Convert.ToDateTime(dt.Rows[0]["time"].ToString());
                    time = DateTime.ParseExact(dt.Rows[0]["time"].ToString(), "yyyy-MM-dd HH:mm:ss.fff",
                        System.Globalization.CultureInfo.CurrentCulture);

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

        private void ReportInitialize()
        {

        }

        private void ReportFetchRecord()
        {

        }

        /// <summary>
        /// 切换一下计划
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label13_Click(object sender, EventArgs e)
        {
            string stationID = "",nextPlan="";
            InjectionPlanBLL bll = new InjectionPlanBLL();
            InjectionPlanModel md = new InjectionPlanModel();

            try
            {
                #region 获取下一计划

                DataTable dt = bll.NextSearchInfoByName(Program.station);
                if (dt != null && dt.Rows.Count > 1)
                {
                    nextPlan = dt.Rows[1]["ProductName"].ToString();
                }
                else
                {
                    nextPlan = "暂无下一计划,请联系计划员";
                }

                #endregion
                DialogResult result = MessageBox.Show("确定切换下一计划:"+nextPlan, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    #region 获取工位编号

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

                    #endregion

                    #region 更新计划完成

                    md.StationID = stationID;
                    bll.UpdateFinish(md);

                    #endregion
                    MessageBox.Show("操作成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("取消操作!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
            
            
        }

        /// <summary>
        /// 手动删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label20_Click(object sender, EventArgs e)
        {
            BarCodeBLL bll=new BarCodeBLL();
            BarCodeModel md=new BarCodeModel();

            try
            {
                if (glacialList1.SelectedItems.Count == 0)
                {
                    MessageBox.Show("请选择要补打的条码!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    GlacialComponents.Controls.GLItem gv;
                    gv = glacialList1.SelectedItems[0] as GlacialComponents.Controls.GLItem;
                    md.BarCode = gv.Text;

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

        private void label21_Click(object sender, EventArgs e)
        {
            Form fr=new FrmDown();
            fr.Show();
            //this.Hide();
        }

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

        private void textBox2_Click(object sender, EventArgs e)
        {
            //Process.Start(@"C:\windows\system32\osk.exe");
            ShowInputPanel();
        }

        private const Int32 WM_SYSCOMMAND = 274;

        private const UInt32 SC_CLOSE = 61536;

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]

        private static extern bool PostMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]

        private static extern bool PostMessage(IntPtr hWnd, int Msg, uint wParam, uint lParam);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]

        private static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]

        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]

        private static extern int RegisterWindowMessage(string lpString);



        //显示屏幕键盘

        public static int ShowInputPanel()
        {

            try
            {

                dynamic file = "C:\\Program Files\\Common Files\\microsoft shared\\ink\\TabTip.exe";

                if (!System.IO.File.Exists(file))

                    return -1;

                Process.Start(file);

                //return SetUnDock(); //不知SetUnDock()是什么,所以直接注释返回1

                return 1;

            }

            catch (Exception)
            {

                return 255;

            }

        }

        private void glacialList1_Click(object sender, EventArgs e)
        {

        }
    }
}