using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using grproLib;
using MESClassLibrary.BLL;
using MESClassLibrary.BLL.BasicInfo;
using MESClassLibrary.BLL.Injection;
using MESClassLibrary.BLL.Inspection;
using MESClassLibrary.BLL.Log;
using MESClassLibrary.BLL.TruckBox;
using MESClassLibrary.DAL;
using MESClassLibrary.EFModel;
using MESClassLibrary.Model;
using DataTable = System.Data.DataTable;

namespace InjectionSearch
{
    public partial class FrmBarCodeSearch2408 : Form
    {
        private UniqueBll _uniqueBll = new UniqueBll();
        private BasicBLL1 _basicBLL1 = new BasicBLL1();
        private InjectionBoxBLL _injectionBoxBLL = new InjectionBoxBLL();
        private BarCodeBLL _bll = new BarCodeBLL();
        private WmsBLL _wmsBll = new WmsBLL();
        private string _lastBoxNo = string.Empty;
        public FrmBarCodeSearch2408()
        {
            InitializeComponent();
        }

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

            ProductBLL bll = new ProductBLL();

            DataTable dt = bll.SearchInfoAllByType("2000");
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    comboBox1.Items.Add(dt.Rows[i]["StockNo"].ToString() +"--"+dt.Rows[i]["ProductName"].ToString());
                }
            }
            dt.Dispose();
        }

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

            glacialList1.Items.Clear();
            DataTable dt = bll.SearchBarCode();
            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.fff");
                    //glacialList1.Items[i].SubItems[4].Text = dt.Rows[i]["MaterialName"].ToString();
                    //glacialList1.Items[i].SubItems[5].Text = dt.Rows[i]["BatchNo"].ToString();
                    glacialList1.Items[i].SubItems[0].Tag = dt.Rows[i]["BoxNo"].ToString();
                    glacialList1.Items[i].SubItems[1].Tag = dt.Rows[i]["TableName"].ToString();
                }
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string stockNo = comboBox1.Text.Substring(0, 10);

            ProductBLL bll=new ProductBLL();
            BomBLL bombll=new BomBLL();

            DataTable dt = bll.SearchInfoByStock(stockNo);
            if (dt != null && dt.Rows.Count > 0)
            {
                textBox1.Text = dt.Rows[0]["PartNo"].ToString();
                dt.Dispose();
            }
            else
            {
                textBox1.Text = "";
            }

            DataTable dt1 = bombll.SearchBom(textBox1.Text);
            if (dt1 != null && dt1.Rows.Count > 0)
            {
                textBox2.Text = dt1.Rows[0]["PartNo2"].ToString();
                dt.Dispose();
            }
            else
            {
                textBox2.Text = "";
            }
        }

        private void FrmBarCodeSearch_Load(object sender, EventArgs e)
        {
            initProduct();
            initBarCode();
            comboBox2.Items.Clear();
            comboBox2.Items.Add("IM01");
            comboBox2.Items.Add("IM02");
            comboBox2.Items.Add("IM03");
            comboBox2.Items.Add("IM04");
            comboBox2.Items.Add("IM05");
            comboBox2.Items.Add("IM06");
            comboBox2.Items.Add("IM07");
            comboBox2.Items.Add("IM08");
            comboBox2.Items.Add("IM09");
            comboBox2.Items.Add("IM10");
            comboBox2.Items.Add("IM11");
            comboBox2.Items.Add("IM12");
            comboBox2.Items.Add("IM13");
            comboBox2.Items.Add("IM14");
            comboBox2.Items.Add("IM15");
            comboBox2.Items.Add("IM16");
            comboBox2.Items.Add("IM17");
            comboBox2.Items.Add("IM18");
            comboBox2.Items.Add("IM19");
            comboBox2.Items.Add("IM20");
            GetClass();
            textBox3.Text = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) +
                            Program.ProductDate.Substring(8, 2);     //批次

            comBoxSizeL.DataSource = _basicBLL1.GetPackageSize();
            comBoxSizeL.DisplayMember = "describe";
            comBoxSizeL.ValueMember = "Count";
        }

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

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

                }
                else
                {
                    Program.Shift = "B班";
                    if (GetDateTime().Hour >= 0 && GetDateTime().Hour < 8)
                    {
                        Program.ProductDate = aa.AddDays(-1).ToString("yyyy-MM-dd");
                    }
                    else
                    {
                        Program.ProductDate = aa.ToString("yyyy-MM-dd");
                    }
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        private void label18_Click(object sender, EventArgs e)
        {
            string code = "",name="";
            BarCodeModel md = new BarCodeModel();
            BarCodeBLL bll = new BarCodeBLL();
            ProductBLL pbll=new ProductBLL();
            string filename = "", partNo = "", OneCode="";

            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;

                    string[] aa = code.Split('.');
                    partNo = aa[0];

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

                        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 (bll.Add_Info_New(md, "tb_BarCode5") == false)
                    //{
                    //    return;
                    //}
                    if (SaveBarCode(md, "tb_BarCode5", false) == false)
                    {
                        return;
                    }
                    #region 打印条码
                    PlasticBLL plbll = new PlasticBLL();

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


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

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

                    rp.Report.Print(false);

                    #endregion

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

        public DateTime GetDateTime()
        {
            string sql = "";
            DateTime time;
            DataTable dt;
            try
            {
                sql = @"select getdate() 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());

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

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

        private void label19_Click(object sender, EventArgs e)
        {
            string code = "", stationID = "", OneCode = "",planID="";
            string newcode = "", partNo = "", stockNo = "", NewOneCode = "";
            string filename = "", printName = "", PartName = "", IsSupply="",QLevel="",ProductNature="",IsPrint="";

            ProductBLL pbll = new ProductBLL();
            BarCodeBLL bll = new BarCodeBLL();
            BarCodeModel md = new BarCodeModel();
            InjectionPlanBLL planbll = new InjectionPlanBLL();

            try
            {
               

                #region 数据合法性判断
                if (comboBox2.Text.Trim() == "")
                {
                    MessageBox.Show("请选择机台!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

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

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

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

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

                #endregion

                #region 获取工位编号

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

                #region 获取对应工位的当前计划信息

                
                DataTable plandt = planbll.SearchInfoByName(comboBox2.Text);
                if (plandt != null && plandt.Rows.Count > 0)
                {
                    planID = plandt.Rows[0]["InjectionPlanID"].ToString();
                    ProductNature = plandt.Rows[0]["ProductNature"].ToString();
                }

                #endregion
                int packageSize = 0;
                string msg = "确定手工打印条码?";
                if (cboxHandBox.Checked)
                {
                    if (comBoxSizeL.SelectedItem == null)
                    {
                        MessageBox.Show("选中打印箱码,请先选择箱码规格!");
                        return;
                    }
                    else 
                    {
                       string size = comBoxSizeL.SelectedValue.ToString();
                        int.TryParse(size, out packageSize);

                        int allCount = Convert.ToInt32(textBox4.Text.Trim());
                        int i = allCount % packageSize;

                        if(i > 0)
                        {
                            msg = $"最后一箱数量为[{i}],不能满箱打印,是否确定手工打印条码?";

                        }
                    }
                }
                DialogResult result = MessageBox.Show(msg, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    //查询零件号
                    stockNo = comboBox1.Text.Substring(0, 10);
                    partNo = textBox1.Text.Trim();
                    
                    #region 判断零件是否是直供件、是否打印标签

                    ProductBLL prbll = new ProductBLL();
                    DataTable prdt = prbll.SearchInfoByPartNo(partNo);
                    if (prdt != null && prdt.Rows.Count > 0)
                    {
                        IsSupply = prdt.Rows[0]["IsSupply"].ToString();
                        QLevel = prdt.Rows[0]["QLevel"].ToString();
                        IsPrint = prdt.Rows[0]["IsPrintOneTag"].ToString();
                    }

                    #endregion

                    #region 非直供件

                    if (IsSupply != "1")
                    {
                        for (int i = 1; i <= Convert.ToInt32(textBox4.Text.Trim()); i++)
                        {
                            DataTable pdt = pbll.SearchIsImportByStockNo(stockNo);
                            string packageCode = string.Empty;
                            if (cboxHandBox.Checked)
                            {
                                if( i% packageSize == 1)
                                {
                                    packageCode = SaveBoxInfo(pdt, partNo, textBox3.Text.Trim(), packageSize.ToString());

                                    if(string.IsNullOrEmpty(packageCode))
                                    {
                                        MessageBox.Show("箱单生成失败,请重新操作!");
                                        return;
                                    }
                                    else
                                    {
                                        packageCode = lbPackageCodeL.Text.Trim();
                                    }
                                    if (string.IsNullOrEmpty(packageCode))
                                    {
                                        MessageBox.Show("箱单生成失败,请重新操作!");
                                        return;
                                    }
                                }
                                else
                                {
                                    packageCode = lbPackageCodeL.Text.Trim();
                                }
                                if (string.IsNullOrEmpty(packageCode))
                                {
                                    MessageBox.Show("箱单生成失败,请重新操作!");
                                    return;
                                }
                            }

                            GetSjBarCode(stockNo, partNo,false, ref NewOneCode, ref newcode);
                            string[] part = newcode.Split('.');
                            //存入tb_BarCode表
                            md.ID = Guid.NewGuid().ToString();
                            md.StationID = Program.StationID;
                            md.StationID2 = stationID;
                            md.StockNo = stockNo;
                            md.OneBarCode = NewOneCode;
                            md.BarCode = newcode;
                            md.PrintType = 1;
                            md.PartNo = partNo;
                            md.PlanID = planID;
                            md.ProductNature = ProductNature;
                            md.BoxNo = packageCode;
                            
                            if (pdt != null && pdt.Rows.Count > 0)
                            {
                                PartName = pdt.Rows[0]["ProductName"].ToString();
                                if (pdt.Rows[0]["isImport"].ToString() == "1")
                                {
                                    md.Import = "国产料Kingfa";
                                }
                                else
                                {
                                    md.Import = "";
                                }
                            }

                            //if (bll.Add_Info_New(md, "tb_BarCode5") == false)
                            //{
                            //    return;
                            //}
                            if(SaveBarCode(md, "tb_BarCode5", i== Convert.ToInt32(textBox4.Text.Trim())) == false)
                            {
                                return;
                            }

                                #region 214TrunkBox存入质检表

                                if (partNo == "A2146106203kz")
                            {
                                tb_Inspection_tx imd = new tb_Inspection_tx();
                                InspectionBLL ibll = new InspectionBLL();

                                imd.BarCode = NewOneCode;
                                imd.IsOK = 1;
                                imd.Station = 1;

                                ibll.AddInfo(imd);
                            }

                            #endregion

                            if (IsPrint == "1")
                            {
                                #region 打印条码

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

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

                                rp.Report.Print(false);

                                #endregion
                            }
                        }

                        #region 原有打印代码
                        //DataTable dt = bll.SearchSerialNoByBarCodeNew(partNo + "." + textBox3.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(textBox4.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');

                        //        GetSjBarCode(stockNo, partNo, ref NewOneCode, ref newcode);
                        //        string[] part = newcode.Split('.');
                        //        //存入tb_BarCode表
                        //        md.ID = Guid.NewGuid().ToString();
                        //        md.StationID = Program.StationID;
                        //        md.StationID2 = stationID;
                        //        md.StockNo = stockNo;
                        //        md.OneBarCode = NewOneCode;
                        //        md.BarCode = newcode;
                        //        md.PrintType = 1;
                        //        md.PartNo = partNo;
                        //        md.PlanID = planID;
                        //        md.ProductNature = ProductNature;

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

                        //        if (bll.Add_Info_New(md, "tb_BarCode5") == false)
                        //        {
                        //            return;
                        //        }

                        //        #region 214TrunkBox存入质检表

                        //        if (partNo == "A2146106203kz")
                        //        {
                        //            tb_Inspection_tx imd = new tb_Inspection_tx();
                        //            InspectionBLL ibll = new InspectionBLL();

                        //            imd.BarCode = NewOneCode;
                        //            imd.IsOK =1;
                        //            imd.Station = 1;

                        //            ibll.AddInfo(imd);
                        //        }

                        //        #endregion

                        //        if (IsPrint == "1")
                        //        {
                        //            #region 打印条码

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

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

                        //            rp.Report.Print(false);

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

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

                        //        if (bll.Add_Info_New(md, "tb_BarCode5") == false)
                        //        {
                        //            return;
                        //        }

                        //        #region 214TrunkBox存入质检表

                        //        if (partNo == "A2146106203kz")
                        //        {
                        //            tb_Inspection_tx imd = new tb_Inspection_tx();
                        //            InspectionBLL ibll = new InspectionBLL();

                        //            imd.BarCode = NewOneCode;
                        //            imd.IsOK = 1;
                        //            imd.Station = 1;

                        //            ibll.AddInfo(imd);
                        //        }

                        //        #endregion

                        //        if (IsPrint == "1")
                        //        {
                        //            #region 打印条码

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

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

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

                        //            rp.Report.Print(false);

                        //            #endregion
                        //        }
                        //    }
                        //}
                        #endregion
                    }

                    #endregion

                    #region 直供件

                    if (IsSupply == "1")
                    {

                        for (int i = 1; i <= Convert.ToInt32(textBox4.Text.Trim()); i++)
                        {
                            //newcode = partNo + "#" + QLevel + "#" + textBox3.Text.Trim() + "#" +
                            //          i.ToString().PadLeft(3, '0') + "#";

                            DataTable pdt = pbll.SearchIsImportByStockNo(stockNo);
                            string packageCode = string.Empty;
                            if (cboxHandBox.Checked)
                            {
                                if (i % packageSize == 1)
                                {
                                    packageCode = SaveBoxInfo(pdt, partNo, textBox3.Text.Trim(), packageSize.ToString());

                                    if (string.IsNullOrEmpty(packageCode))
                                    {
                                        MessageBox.Show("箱单生成失败,请重新操作!");
                                        return;
                                    }
                                }
                                else
                                {
                                    packageCode = lbPackageCodeL.Text.Trim();
                                }
                                if(string.IsNullOrEmpty(packageCode))
                                {
                                    MessageBox.Show("箱单生成失败,请重新操作!");
                                    return;
                                }
                            }


                            NewOneCode = "";
                            //直供件不生成NewOneCode 此处也生成一个,可以不用
                            GetSjBarCode(stockNo, partNo, false, ref NewOneCode, ref newcode);

                            GetSupplyCode(partNo, QLevel,true, ref newcode);
                            
                            string[] part = newcode.Split('.');

                            #region 存入tb_BarCode表

                            md.ID = Guid.NewGuid().ToString();
                            md.StationID = Program.StationID;
                            md.StationID2 = stationID;
                            md.StockNo = stockNo;
                            md.OneBarCode = NewOneCode;
                            md.BarCode = newcode;
                            md.PrintType = 1;
                            md.PartNo = partNo;
                            md.PlanID = planID;
                            md.ProductNature = ProductNature;
                            md.BoxNo = packageCode;
                           // DataTable pdt = pbll.SearchIsImportByStockNo(stockNo);
                            if (pdt != null && pdt.Rows.Count > 0)
                            {
                                if (pdt.Rows[0]["isImport"].ToString() == "1")
                                {
                                    md.Import = "国产料Kingfa";
                                }
                                else
                                {
                                    md.Import = "";
                                }
                            }

                            //if (bll.Add_Info_New(md, "tb_BarCode5") == false)
                            //{
                            //    return;
                            //}
                            if (SaveBarCode(md, "tb_BarCode5", i == Convert.ToInt32(textBox4.Text.Trim())) == false)
                            {
                                return;
                            }
                            #endregion


                            if (IsPrint == "1")
                            {
                                #region 打印条码

                                filename = System.AppDomain.CurrentDomain.BaseDirectory +
                                           "单个条码1.grf";

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

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

                                rp.Report.Print(false);

                                #endregion
                            }
                        }

                        #region 原来打印代码
                        //DataTable dt = bll.SearchSerialNoByBarCodeNew1(partNo + "#" + QLevel + "#" + textBox3.Text.Trim() + "#");
                        //if (dt != null && dt.Rows.Count > 0)
                        //{
                        //    code = dt.Rows[0]["BarCode"].ToString().Trim();
                        //    for (int i = 1; i <= Convert.ToInt32(textBox2.Text.Trim()); i++)
                        //    {
                        //        newcode = code.Substring(0, code.Length - 4) +
                        //                  (Convert.ToInt32(code.Substring(23, 3)) +
                        //                   i).ToString()
                        //                  .PadLeft(3, '0') + "#";

                        //        #region 插入数据tb_barCode

                        //        md.ID = Guid.NewGuid().ToString();
                        //        md.StationID = Program.StationID;
                        //        md.StationID2 = stationID;
                        //        md.StockNo = stockNo;
                        //        md.OneBarCode = "";
                        //        md.BarCode = newcode;
                        //        md.PrintType = 1;
                        //        md.PartNo = partNo;

                        //        md.PlanID = planID;
                        //        md.ProductNature = ProductNature;

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

                        //        if (bll.Add_Info_New(md, "tb_BarCode5") == false)
                        //        {
                        //            return;
                        //        }

                        //        #endregion

                        //        if (IsPrint == "1")
                        //        {
                        //            #region 打印条码

                        //            filename = System.AppDomain.CurrentDomain.BaseDirectory +
                        //                       "单个条码1.grf";

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

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

                        //            rp.Report.Print(false);

                        //            #endregion
                        //        }
                        //    }
                        //}
                        //else
                        //{
                        //    for (int i = 1; i <= Convert.ToInt32(textBox4.Text.Trim()); i++)
                        //    {
                        //        newcode = partNo + "#" + QLevel + "#" + textBox3.Text.Trim() + "#" +
                        //                  i.ToString().PadLeft(3, '0') + "#";
                        //        NewOneCode = "";
                        //        string[] part = newcode.Split('.');

                        //        #region 存入tb_BarCode表

                        //        md.ID = Guid.NewGuid().ToString();
                        //        md.StationID = Program.StationID;
                        //        md.StationID2 = stationID;
                        //        md.StockNo = stockNo;
                        //        md.OneBarCode = NewOneCode;
                        //        md.BarCode = newcode;
                        //        md.PrintType = 1;
                        //        md.PartNo = partNo;
                        //        md.PlanID = planID;
                        //        md.ProductNature = ProductNature;

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

                        //        if (bll.Add_Info_New(md, "tb_BarCode5") == false)
                        //        {
                        //            return;
                        //        }

                        //        #endregion


                        //        if (IsPrint == "1")
                        //        {
                        //            #region 打印条码

                        //            filename = System.AppDomain.CurrentDomain.BaseDirectory +
                        //                       "单个条码1.grf";

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

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

                        //            rp.Report.Print(false);

                        //            #endregion
                        //        }
                        //    }
                        //}
                        #endregion
                    }

                    #endregion

                    initBarCode();
                }
                else
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }
        string SaveBoxInfo(DataTable pdt, string partNo, string batch,string packageSize)
        {
            string  packageCode = _uniqueBll.GetPackageCodeSerialNo(partNo, textBox3.Text.Trim(), packageSize.ToString());
            InjectionBoxModel boxmd = new InjectionBoxModel();
            boxmd.ID = Guid.NewGuid().ToString();
            boxmd.BoxNo = packageCode;
            boxmd.BoxCount = 0;
            boxmd.BoxType = 0;
            boxmd.IsFlag = 0;
            boxmd.StationNo = Program.station;
            if (pdt != null && pdt.Rows.Count > 0)
            {
                boxmd.PartName = pdt.Rows[0]["ProductName"].ToString();
            }


            boxmd.Mould = "2";
            boxmd.StandardQty = packageSize.ToString();
            if(_injectionBoxBLL.AddInfo(boxmd))
            {
                this.lbPackageCodeL.Text = packageCode;
                return packageCode;
            }
            return null;
        }
        bool SaveBarCode(BarCodeModel bcm, string tableName , bool printBox)
        {
            bool saveRst = false;
            if (cboxHandBox.Checked)
            {
                saveRst = _bll.Add_Info_New(bcm, "tb_BarCode5");
                if(saveRst == true)
                {
                    if (_injectionBoxBLL.UpdateBoxCount(bcm.BoxNo,1))
                    {
                        DataTable dt = _injectionBoxBLL.SearchBox(bcm.BoxNo);
                        if (dt.Rows.Count > 0)
                        {
                            string realCountStr = dt.Rows[0]["BoxCount"].ToString();

                            int realCount = 0;
                            int sizeCount = 0;
                            int.TryParse(realCountStr, out realCount);
                            int.TryParse(comBoxSizeL.SelectedValue?.ToString(), out sizeCount);
                            if ((realCount != 0 && realCount == sizeCount) || printBox ==true)
                            {
                                //检查上一个箱码是否给wms传成功了, 没成功重传一次.
                                //if (!string.IsNullOrEmpty(_lastBoxNo))
                                //{
                                //    if(_wmsBll.IsSendPackageCode(_lastBoxNo) == false)
                                //    {
                                //        DataTable dt2 = _injectionBoxBLL.SearchBox(_lastBoxNo);
                                //        if(dt2.Rows.Count >0)
                                //        {
                                //            _wmsBll.SaveInterface(dt2.Rows[0], MESClassLibrary.Enum.WmsInterfaceEnum.塑件箱码报工);
                                //        }
                                //    }
                                //    _lastBoxNo = "";

                                //}
                                ////wms接口传递
                                //_wmsBll.SaveInterface(dt.Rows[0], MESClassLibrary.Enum.WmsInterfaceEnum.塑件箱码报工);

                                _wmsBll.SaveInterface(dt.Rows[0]["BoxNo"].ToString(), _lastBoxNo, "", MESClassLibrary.Enum.WmsInterfaceEnum.塑件箱码报工);

                                //打印箱码
                                PrintBoxCode(dt.Rows[0], realCount,false);
                                _lastBoxNo = lbPackageCodeL.Text;
                                lbPackageCodeL.Text = "";
                            }
                        }
                    }
                }
            }
            else
            {
                saveRst = _bll.Add_Info_New(bcm, "tb_BarCode5");
            }
            return saveRst;
        }
        private void PrintBoxCode(DataRow boxRow, int realCount,bool isRePrint)
        {
            string filename = System.AppDomain.CurrentDomain.BaseDirectory + "装箱单.grf";
            DataTable headTable = new DataTable();
            headTable.Columns.Add("BoxNo");
            headTable.Columns.Add("PartName");
            headTable.Columns.Add("PartNo");
            headTable.Columns.Add("BatchNo");
            headTable.Columns.Add("PackCount");
            headTable.Columns.Add("Line");
            DataRow row = headTable.NewRow();
            string boxCode = boxRow["BoxNo"].ToString();
            string[] boxes = boxCode.Split('.');
            if (boxes.Length != 4)
            {
                //新生成一个箱码  应该都有
            }
            else
            {
                row["BoxNo"] = boxCode;
                row["PartNo"] = boxes[0].Trim();
                row["PartName"] = boxRow["PartName"].ToString();
                row["BatchNo"] = boxes[1].Trim();
                row["PackCount"] = realCount;
                row["Line"] = boxRow["StationNo"].ToString() + "注塑机";
            }
            //补打不修改数据状态
            if(isRePrint == false)
            {
                UpdateBoxRecordPrintState(boxCode);
            }

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

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

            rp.Report.Print(false);


        }
        private void UpdateBoxRecordPrintState(string UpdatePrinted)
        {
            _injectionBoxBLL.UpdatePrinted(UpdatePrinted);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            BarCodeBLL bll = new BarCodeBLL();
            DataTable dt = null;

            try
            {
                glacialList1.Items.Clear();
                if (textBox5.Text.Trim() == "")
                {
                    dt = bll.SearchBarCode();
                }
                else
                {
                    if (textBox5.Text.Trim().Length == 20)
                    {
                        dt = bll.SearchBarCodeByOne(textBox5.Text.Trim());
                    }
                    else
                    {
                        dt = bll.SearchBarCodeByTwo(textBox5.Text.Trim());
                    }
                }
                

                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]["PrintTime"].ToString() == "" ? "" : Convert.ToDateTime(dt.Rows[i]["PrintTime"].ToString()).ToString("yyyy-MM-dd HH:mm:ss.fff");
                        glacialList1.Items[i].SubItems[4].Text = dt.Rows[i]["MaterialName"].ToString();
                        glacialList1.Items[i].SubItems[5].Text = dt.Rows[i]["BatchNo"].ToString();

                        glacialList1.Items[i].SubItems[0].Tag = dt.Rows[i]["BoxNo"].ToString();
                        glacialList1.Items[i].SubItems[1].Tag = dt.Rows[i]["TableName"].ToString();
                    }
                }

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

        private void FrmBarCodeSearch_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        void GetSjBarCode(string stockNo, string partNo,bool autoPrint, ref string newOneCode, ref string newCode)
        {
            string batch = string.Empty;
            if (autoPrint)
            {
                 batch = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2);
            }
            else
            {
                 batch = textBox3.Text.Trim();
            }
           
           
             
            newOneCode = _uniqueBll.GetSjBarCodeSerialNo(stockNo, batch);
            newCode = partNo + "." + batch + "." + newOneCode.Substring(newOneCode.Length - 4, 4);
        }
        void GetSupplyCode(string partNo, string qLevel, bool autoPrint, ref string newCode)
        {
            string batch = string.Empty;
            if (autoPrint)
            {
                 batch = Program.ProductDate.Substring(2, 2) + Program.ProductDate.Substring(5, 2) + Program.ProductDate.Substring(8, 2);
            }
            else
            {
                 batch = textBox3.Text.Trim();
            }
            newCode = _uniqueBll.GetSupplySerialNo(partNo, qLevel, batch);
        }

        private void btnPackage_Click(object sender, EventArgs e)
        {
            string boxCode = string.Empty;
            string tableName = string.Empty;
            if (glacialList1.SelectedItems.Count > 0)
            {
                GlacialComponents.Controls.GLItem gv;
                gv = glacialList1.SelectedItems[0] as GlacialComponents.Controls.GLItem;
                
                boxCode = gv.SubItems[0].Tag?.ToString();
                tableName = gv.SubItems[1].Tag?.ToString();
            }
            FrmPackageDetail detail = new FrmPackageDetail(boxCode);
            detail.ShowDialog();
        }

        private void btnBoxRePrint_Click(object sender, EventArgs e)
        {
            if(pnBoxReprint.Visible == true)
            {
                pnBoxReprint.Visible = false;
            }
            else
            {
                pnBoxReprint.Visible = true;
            }

            if (glacialList1.SelectedItems.Count > 0)
            {
                GlacialComponents.Controls.GLItem gv;
                gv = glacialList1.SelectedItems[0] as GlacialComponents.Controls.GLItem;

                txtRePrintBoxCode.Text = gv.SubItems[0].Tag?.ToString();
                txtRePrintBoxCode.SelectAll();
            }
        }

        private void btnRePrint_Click(object sender, EventArgs e)
        {
            string boxCode = txtRePrintBoxCode.Text?.Trim();
            if (string.IsNullOrEmpty(boxCode))
            {
                MessageBox.Show("请输入箱码");
                return;
            }
            DataTable dt = _injectionBoxBLL.SearchBox(boxCode);
            if(dt.Rows.Count == 0)
            {
                MessageBox.Show($"箱码[{boxCode}]在系统中不存在!");
                return;
            }
            PrintBoxCode(dt.Rows[0], int.Parse(dt.Rows[0]["StandardQty"].ToString()), true);

        }

        private void btnPrintCancel_Click(object sender, EventArgs e)
        {
            pnBoxReprint.Visible = false;
        }
    }
}