using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using LabelManager2;
using UAS_LabelMachine.PublicMethod;
using UAS_LabelMachine.Entity;
using UAS_LabelMachine.PublicForm;
using System.Threading;
using System.IO;
using System.Globalization;
using System.Reflection;
using Seagull.BarTender.Print;

namespace UAS_LabelMachine
{
    public partial class UAS_出货标签打印 : Form
    {
        //自适应屏幕
        AutoSizeFormClass asc = new AutoSizeFormClass();

        DataHelper dh;

        SqliteDBHelper sdh;

        DataTable dt;

        StringBuilder sql = new StringBuilder();
        /// <summary>
        /// CodeSoft新建打印机引擎
        /// </summary>
        ApplicationClass lbl;
        /// <summary>
        /// CodeSoft单盘打印文件
        /// </summary>
        Document SingleDoc;
        /// <summary>
        /// CodeSoft中盒打印文件
        /// </summary>
        Document MidDoc;
        /// <summary>
        /// CodeSoft外箱打印文件
        /// </summary>
        Document OutBoxDoc;
        /// <summary>
        /// Loading窗口
        /// </summary>
        SetLoadingWindow stw;
        /// <summary>
        /// 弹窗线程
        /// </summary>
        Thread thread;
        /// <summary>
        /// 当前品牌
        /// </summary>
        string Brand;
        string PI_ID;
        /// <summary>
        /// 当前扫描的项目
        /// </summary>
        int CurrentItemIndex = 0;
        /// <summary>
        /// 当前扫描的所在行
        /// </summary>
        int CurrentRowIndex = 0;
        /// <summary>
        /// 最大的出入口单号
        /// </summary>
        int MaxOutBoxCode = 1;
        /// <summary>
        /// 正则表达式用于项目匹配
        /// </summary>
        Regex reg;
        /*标识供应商物料编号采集是否通过*/
        bool CollectVeProdCodePass = true;

        bool CollectQTYPass = true;

        bool logout = false;

        //每个不同序号存在的
        object[] ItemData;

        DataTable SingleLabelParam;
        DataTable MidLabelParam;
        DataTable OutLabelParam;
        /// <summary>
        /// BarTender引擎
        /// </summary>
        Engine engine;
        LabelFormatDocument EmptySingleFormat;

        LabelFormatDocument EmptyOutFormat;
        /// <summary>
        /// BarTender单盘
        /// </summary>
        LabelFormatDocument SingleFormat;
        /// <summary>
        /// BarTender中盒
        /// </summary>
        LabelFormatDocument MidFormat;
        /// <summary>
        /// BarTender外箱 
        /// </summary>
        LabelFormatDocument OutFormat;

        Dictionary<string, string> CollectData;
        //缓存单盘数据数据的DataTable
        /// <summary>
        /// 存放单盘的ID
        /// </summary>
        List<string> SingleID = new List<string>();
        /// <summary>
        /// 单盘的打印参数
        /// </summary>
        List<string> SingleBoxArgument = new List<string>();
        /// <summary>
        /// 中盒缓存数据
        /// </summary>
        /// <summary>
        /// 存放中盒的ID和盒号
        /// </summary>
        Dictionary<string, string> MidIDAndOutboxcode = new Dictionary<string, string>();
        /// <summary>
        /// 中盒的打印参数
        /// </summary>
        List<string> MidBoxArgument = new List<string>();
        /// <summary>
        /// 全部采集
        /// </summary>
        bool AllCollect = false;
        /// <summary>
        /// 是否获取过箱号
        /// </summary>
        bool GetPackingCode = false;
        /*用于存放采集项目的Grid信息*/
        Dictionary<string, Dictionary<string, string>> SiItem;
        int CloumnCount = 0;
        //使用二维数组进行排序
        ArrayList<ArrayList<string>> ScanData;
        ArrayList<string> GetData;
        /// <summary>
        /// 是否通过选择Combox来改变打开的文件
        /// </summary>
        bool ComBoxClickChangeLabelDoc = false;

        List<string> MidParam = new List<string>();

        List<string> OutParam = new List<string>();

        public static DataTable Attach;

        public string PrintMethod = "";
        /// <summary>
        /// 用于记录外箱号和当前的箱号进行比对,判断当前行和上一行是否是同一个箱号,从而判断是否要打印空白页
        /// </summary>
        public string Last_OutboxCode = "";

        public UAS_出货标签打印(string Master)
        {
            //设置窗体的双缓冲
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint, true);
            this.UpdateStyles();
            InitializeComponent();
            //利用反射设置DataGridView的双缓冲
            Type dgvType = this.LabelInf.GetType();
            PropertyInfo pi = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
            pi.SetValue(this.LabelInf, true, null);
            Text = Text + "-" + Master;
        }

        protected override void WndProc(ref System.Windows.Forms.Message m)
        {
            //拦截双击标题栏、移动窗体的系统消息
            if (m.Msg != 0xA3)
            {
                base.WndProc(ref m);
            }
        }

        private void 贴标机条码打印_Load(object sender, EventArgs e)
        {
            ShowMenu.TopLevel = false;
            ShowMenu.Parent = this;
            //杀死之前全部未关闭的进程
            Process[] processes = System.Diagnostics.Process.GetProcessesByName("lppa");
            Process[] processes1 = System.Diagnostics.Process.GetProcessesByName("bartend");
            for (int i = 0; i < processes1.Length; i++)
            {
                processes1[i].Kill();
            }
            for (int i = 0; i < processes.Length; i++)
            {
                processes[i].Kill();
            }
            //用计时器重置数据库链接
            LogManager.DoLog("程序启动,登陆人员【" + User.UserName + "】");
            dh = SystemInf.dh;
            sdh = SystemInf.sdh;
            sdh.ExecuteZip();
            CheckForIllegalCrossThreadCalls = false;
            CloumnCount = LabelInf.Columns.Count;

            pi_inoutno.TableName = "prodinout";
            pi_inoutno.Field = "pi_inoutno";
            pi_inoutno.ValueField = "pi_inoutno";
            pi_inoutno.Condition = "pi_class in('出货单','拨出单','其它出库单')";
            pi_inoutno.Focus();
            //将本地读取的打印机设置进Combox,并选中默认打印机
            sg_code.FormName = Name;
            sg_code.SetValueField = new string[] { "sg_code" };
            sg_code.SelectField = "sg_code # 策略编号 ,sg_name # 策略名称,sg_brand # 品牌,sg_separator # 分隔符";
            sg_code.TableName = "scangroup";
            sg_code.DbChange += Sg_code_DbChange;
            pr_code.FormName = Name;
            pr_code.SetValueField = new string[] { "pr_code" };
            pr_code.TableName = "prodiodetail left join product on pd_prodcode=pr_code";
            pr_code.SelectField = "pd_pdno # 行号,pr_code # 物料编号,pr_detail # 名称 ,pr_spec # 规格";

            cu_code.FormName = Name;
            cu_code.SetValueField = new string[] { "cu_code" };
            cu_code.TableName = "customer";
            cu_code.SelectField = "cu_code # 客户编号,cu_name # 客户名称";

            CollectionUnit.Text = "盘";
            Point pt = new Point();

            //禁止所有列的排序
            foreach (DataGridViewColumn dgv in LabelInf.Columns)
            {
                dgv.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            int ScreenWidth = Screen.GetWorkingArea(pt).Width;
            //设置获取当前屏幕大小自动全屏但是保留任务栏
            Rectangle ScreenArea = Screen.GetWorkingArea(this);
            Top = 0;
            Left = 0;
            Width = ScreenArea.Width;
            Height = ScreenArea.Height;
            MidBoxCapacity.Value = Properties.Settings.Default.MidBoxCapacity;
            OutboxCapacity.Value = Properties.Settings.Default.OutboxCapacity;
            SingleLabelPrinter.Text = Properties.Settings.Default.SinglePrinter;
            MidLabelPrinter.Text = Properties.Settings.Default.MidPrinter;
            OutBoxPrinter.Text = Properties.Settings.Default.OutPrinter;

            asc.controllInitializeSize(this);
            asc.controlAutoSize(this);
            string Code = dh.GetConfig("PrintMethod", "CodeOrBar").ToString();
            SystemInf.CheckDcAndLotNo = dh.GetConfig("PrintCheck", "CheckDcAndLotNo").ToString() == "" ? false : true;
            if (dh.GetConfig("isSpeac", "LabelSpace").ToString() == "" ? false : true)
            {
                LabelSpace.Visible = true;
                LabelSpace.Checked = true;
            }
            if (Code != "")
            {
                try
                {
                    engine = new Engine(true);
                    PrintMethod = "BarTender";
                }
                catch (Exception ex)
                {
                    MessageLog.AppendText(ex.Message + ex.StackTrace);
                    //MessageBox.Show(ex.Message + ex.StackTrace);
                }
                //try
                //{
                //    lbl = new ApplicationClass();
                //}
                //catch (Exception)
                //{
                //    MessageBox.Show("未安装CodeSoft软件或者版本不正确");
                //}
            }
            else
            {
                try
                {
                    engine = new Engine(true);
                    PrintMethod = "BarTender";
                }
                catch (Exception ex)
                {
                    MessageLog.AppendText(ex.Message + ex.StackTrace);
                    //MessageBox.Show(ex.Message + ex.StackTrace);
                }

            }
            pi_inoutno.BringToFront();
            LogicHandler.CustInit("0");
        }


        private void Sg_code_DbChange(object sender, EventArgs e)
        {
            Form f = Form.ActiveForm;
          
            DataTable dt = sg_code.ReturnData;
            BaseUtil.SetFormValue(this.Controls, dt);
        }

        //只执行一次窗体自适应
        bool AutoSized = false;
        private void 贴标机条码打印_SizeChanged(object sender, EventArgs e)
        {
            if (!AutoSized)
            {
                asc.controlAutoSize(this);
                AutoSized = true;
            }
        }

        private void GenerateBarCode_Click(object sender, EventArgs e)
        {
            生成条码 form = new 生成条码(pi_inoutno.Text, Order_Prod.Checked ? "Prod" : "Detno");
            form.FormClosed += LoadGridData;
            BaseUtil.SetFormCenter(form);
            form.ShowDialog();
        }

        private void LabelFormClose(object sender, EventArgs e)
        {
            Activate();
            if (GetGridOnly.Checked)
                GetInOutInfAndLabelFile();
            else
            {
                GetInOutInfAndLabelFile();
            }
        }

        /// <summary>
        /// 保存明细
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveGrid_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)sdh.ExecuteSql("select pib_id,pib_outboxcode1,pib_outboxcode2,pib_custmidboxcode,pib_custoutboxcode,pib_lotno,pib_datecode,pib_ifupload,pib_ifpick,pib_ifprint from prodiobarcode where pib_inoutno='" + pi_inoutno.Text + "' and pib_ifpick=-1   ", "select");
            if (dt.Rows.Count > 0)
            {
                dh.CallProcedure("sp_uploadbarcode", dt);
                MessageBox.Show("保存成功!");
            }
        }

        //放大镜选择后出发的事件
        private void sg_code_UserControlTextChanged(object sender, EventArgs e)
        {
            //取已启用的的按照采集次序排序
            dt = (DataTable)dh.ExecuteSql("select si_item,si_detno,sg_separator,si_kind,si_expression,si_expressionitem,si_index,si_indexstring,si_length from scanitem left join scangroup on si_sgid=sg_id where sg_code='" + sg_code.Text + "' and si_enable<>0 order by si_detno,si_innerdetno", "select");
            BaseUtil.FillDgvWithDataTable(Si_ItemDGV, dt);
            if (dt.Rows.Count > 0)
            {
                sg_separator.Text = dt.Rows[0]["sg_separator"].ToString();
            }
            //按DetNo排列之后的采集项
            ScanData = new ArrayList<ArrayList<string>>();
            //每个采集项目的子项
            GetData = new ArrayList<string>();
            //将数据添加进一个List的二维数组中
            for (int i = 0; i < Si_ItemDGV.RowCount; i++)
            {
                //如果不包含这个则添加进数组
                if (!GetData.Contains(Si_ItemDGV.Rows[i].Cells["si_item"].Value.ToString()))
                {
                    GetData.Add(Si_ItemDGV.Rows[i].Cells["si_item"].Value.ToString());
                }
                //如果和后一个的采集次序相同
                if (((i + 1) < Si_ItemDGV.RowCount) && Si_ItemDGV.Rows[i].Cells["si_detno"].Value.ToString() == Si_ItemDGV.Rows[i + 1].Cells["si_detno"].Value.ToString())
                {
                    GetData.Add(Si_ItemDGV.Rows[i + 1].Cells["si_item"].Value.ToString());
                }
                else
                {
                    ScanData.Add(GetData);
                    //添加完一次数据需要一个新的List
                    GetData = new ArrayList<string>();
                }
            }
            RemindUser();
            if (ScanData.ToArray().Length > 0)
            {
                object[] arr = (ScanData.ToArray()[0] as ArrayList<string>).ToArray();
                if (arr.Contains("MPN"))
                {
                    AutoMatch.CheckState = CheckState.Checked;
                    AutoMatch.Enabled = true;
                }
                else
                {
                    AutoMatch.CheckState = CheckState.Unchecked;
                    AutoMatch.Enabled = false;
                }
            }
        }

        //输入框Enter事件
        private void Input_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (Input.Text == "")
                {
                    MessageBox.Show("采集的数据不能为空");
                    return;
                }
                if (Si_ItemDGV.Rows.Count == 0)
                {
                    MessageBox.Show("未维护采集策略");
                    return;
                }
                CollectInputData();
            }
        }

        /// <summary>
        /// 设置自动匹配的数据的行号
        /// </summary>
        /// <returns></returns>
        private void SetAutoMatchRow()
        {
            //采集策略的第一组数据
            string[] arr = new string[ItemData.Length];
            if (sg_separator.Text == "")
            {
                for (int i = 0; i < arr.Length; i++)
                {
                    arr[i] = Input.Text;
                }
            }
            else
            {
                arr = Input.Text.Split(sg_separator.Text.ToCharArray()).ToArray();
            }
            bool FindAutoMatch = false;
            for (int i = 0; i < LabelInf.RowCount; i++)
            {
                for (int j = 0; j < arr.Length; j++)
                {
                    if (LabelInf.Rows[i].Cells["pr_vendprodcode"].Value.ToString() == MatchStr(arr[j].ToString(), "MPN") && LabelInf.Rows[i].Cells["pib_ifpick"].FormattedValue.ToString() != "True")
                    {
                        CurrentRowIndex = i;
                        FindAutoMatch = true;
                        break;
                    }
                }
                if (FindAutoMatch)
                    break;
            }
        }

        /// <summary>
        /// 采集数据
        /// </summary>
        private void CollectInputData()
        {
            LogManager.DoLog("采集数据【" + Input.Text + "】,使用采集策略编号【" + sg_code.Text + "】");
            //按DetNo排列之后的采集项
            ScanData = new ArrayList<ArrayList<string>>();
            //每个采集项目的子项
            GetData = new ArrayList<string>();
            //用于保存采集策略的具体信息
            SiItem = new Dictionary<string, Dictionary<string, string>>();
            for (int i = 0; i < Si_ItemDGV.RowCount; i++)
            {
                //如果不包含这个则添加进数组
                if (!GetData.Contains(Si_ItemDGV.Rows[i].Cells["si_item"].Value.ToString()))
                    GetData.Add(Si_ItemDGV.Rows[i].Cells["si_item"].Value.ToString());
                //如果和后一个的采集次序相同
                if (((i + 1) < Si_ItemDGV.RowCount) && Si_ItemDGV.Rows[i].Cells["si_detno"].Value.ToString() == Si_ItemDGV.Rows[i + 1].Cells["si_detno"].Value.ToString())
                    GetData.Add(Si_ItemDGV.Rows[i + 1].Cells["si_item"].Value.ToString());
                else
                {
                    ScanData.Add(GetData);
                    //添加完一次数据需要一个新的List
                    GetData = new ArrayList<string>();
                }
                Dictionary<string, string> item = new Dictionary<string, string>();
                for (int j = 0; j < Si_ItemDGV.ColumnCount; j++)
                {
                    item.Add(Si_ItemDGV.Columns[j].DataPropertyName, Si_ItemDGV.Rows[i].Cells[j].Value.ToString());
                }
                SiItem.Add(Si_ItemDGV.Rows[i].Cells["si_item"].Value.ToString().ToUpper(), item);
            }
            //采集项目的数组
            ItemData = (ScanData.ToArray()[CurrentItemIndex] as ArrayList<string>).ToArray();
            //分隔符不为空的时候  //采集的项和Grid的数目不等
            //用户采集的数据的分割数组
            CollectData = new Dictionary<string, string>();
            if (sg_separator.Text == "")
            {
                for (int i = 0; i < ItemData.Length; i++)
                    CollectData.Add(ItemData[i].ToString().ToUpper(), Input.Text);
            }
            else
            {
                int DataCount = Input.Text.Split(sg_separator.Text.ToCharArray()).Length;
                if (DataCount > ItemData.Length)
                {
                    MessageBox.Show("采集数据大于采集项次");
                    return;
                }
                else if (DataCount < ItemData.Length)
                {
                    MessageBox.Show("采集数据小于采集项次");
                    return;
                }
                for (int i = 0; i < DataCount; i++)
                    CollectData.Add(ItemData[i].ToString().ToUpper(), Input.Text.Split(sg_separator.Text.ToCharArray())[i]);
            }
            //首先判断当前采集的个数,如果采集的个数为1则不对数据进行分隔符验证
            if (ItemData.Length > 0)
            {
                //CollectData.Clear();
                //for (int i = 0; i < ItemData.Length; i++)
                //{
                //    CollectData.Add(ItemData[i].ToString().ToUpper(), Input.Text);
                //}
                //勾选了自动匹配调用该函数
                if (AutoMatch.Checked)
                    SetAutoMatchRow();
                //将筛选之后的值赋给Cell 
                SetDataToCell(ref CollectData);
            }
            else
            {
                MessageBox.Show("所采集的数据个数和采集项目不符");
                return;
            }
            //采集项目的索引+1
            CurrentItemIndex = CurrentItemIndex + 1;
            //如果已经采集完了最后一个
            if (CurrentItemIndex == ScanData.ToArray().Length)
            {
                //数据校验均已通过则勾选上已采集
                if (CollectVeProdCodePass && CollectQTYPass)
                {
                    //如果按盒号采集,所有的此盒的均更新为
                    DataTable dt = (DataTable)LabelInf.DataSource;
                    StringBuilder pibid1 = new StringBuilder();
                    string year = "0";
                    string month = "0";
                    string day = "0";
                    string date = "";
                    string lotno = LabelInf.Rows[CurrentRowIndex].Cells["pib_lotno"].Value.ToString();
                    string datecode = LabelInf.Rows[CurrentRowIndex].Cells["pib_datecode"].Value.ToString();
                    string pr_brand = LabelInf.Rows[CurrentRowIndex].Cells["pib_brand"].Value.ToString();
                    LogicHandler.GetTimeFromDatecode(datecode, pr_brand, out year, out month, out day, out date);
                    if (CollectionUnit.Text == "盒")
                    {
                        for (int i = 0; i < LabelInf.RowCount; i++)
                        {
                            if (LabelInf.Rows[i].Cells["pib_outboxcode1"].Value.ToString() == LabelInf.Rows[CurrentRowIndex].Cells["pib_outboxcode1"].Value.ToString())
                            {
                                string pibid = LabelInf.Rows[i].Cells["pib_id1"].Value.ToString();
                                string outboxcode = LabelInf.Rows[i].Cells["pib_outboxcode2"].Value.ToString();
                                dt.Rows[i]["pib_lotno"] = lotno;
                                dt.Rows[i]["pib_datecode"] = datecode;
                                dt.Rows[i]["pib_year"] = year;
                                dt.Rows[i]["pib_month"] = month;
                                dt.Rows[i]["pib_day"] = day;
                                LabelInf.Rows[i].Cells["pib_ifpick"].Value = true;
                                LabelInf.Rows[i].Cells["Choose"].Value = true;
                                pibid1.Append(pibid + ",");
                                LabelInf.Invalidate();
                                //当前行的索引随循环增长
                                CurrentRowIndex = i;
                                if (SingleLabelAutoPrint.Checked)
                                {
                                    AutoPrintSingleLabel(pibid, outboxcode);
                                }
                                if (MidLabelAutoPrint.Checked)
                                    AutoPrintMidLabel();
                                SetOutBoxCode2(true);
                            }
                        }
                        pibid1.Append("1");
                        sdh.ExecuteSql("update prodiobarcode set pib_ifpick=-1,pib_lotno='" + lotno + "',pib_datecode='" + datecode + "',pib_year='" + year + "',pib_month='" + month + "',pib_day='" + day + "' where pib_id in (" + pibid1 + ")", "update");
                        Last_OutboxCode = "";
                    }
                    else if (CollectionUnit.Text == "全部")
                    {
                        for (int i = 0; i < LabelInf.RowCount; i++)
                        {
                            string pibid = LabelInf.Rows[i].Cells["pib_id1"].Value.ToString();
                            dt.Rows[i]["pib_lotno"] = lotno;
                            dt.Rows[i]["pib_datecode"] = datecode;
                            dt.Rows[i]["pib_year"] = year;
                            dt.Rows[i]["pib_month"] = month;
                            dt.Rows[i]["pib_day"] = day;
                            CurrentRowIndex = i;
                            LabelInf.Refresh();
                            LabelInf.Rows[i].Cells["pib_ifpick"].Value = true;
                            LabelInf.Rows[i].Cells["Choose"].Value = true;
                            pibid1.Append(pibid + ",");
                            LabelInf.Invalidate();
                            SetOutBoxCode2(true);
                        }
                        pibid1.Append("1");
                        sdh.ExecuteSql("update prodiobarcode set pib_ifpick=-1,pib_lotno='" + lotno + "',pib_datecode='" + datecode + "',pib_year='" + year + "',pib_month='" + month + "',pib_day='" + day + "' where pib_id in (" + pibid1 + ")", "update");
                    }
                    else
                    {
                        LabelInf.Rows[CurrentRowIndex].Cells["pib_ifpick"].Value = true;
                        LabelInf.Rows[CurrentRowIndex].Cells["Choose"].Value = true;
                        LabelInf.Rows[CurrentRowIndex].Cells["pib_year"].Value = year;
                        LabelInf.Rows[CurrentRowIndex].Cells["pib_month"].Value = month;
                        LabelInf.Rows[CurrentRowIndex].Cells["pib_day"].Value = day;
                        sdh.ExecuteSql("update prodiobarcode set pib_ifpick=-1,pib_lotno='" + lotno + "',pib_datecode='" + datecode + "',pib_year='" + year + "',pib_month='" + month + "',pib_day='" + day + "' where pib_id in (" + pibid1 + ")", "update");
                        LabelInf.Invalidate();
                        //勾选了单盘自动打印
                        if (SingleLabelAutoPrint.Checked)
                        {
                            if (SingleLabelCombox.SelectedValue != null)
                            {
                                AutoPrintSingleLabel(LabelInf.Rows[CurrentRowIndex].Cells["pib_id1"].Value.ToString(), LabelInf.Rows[CurrentRowIndex].Cells["pib_outboxcode2"].Value.ToString());
                                Last_OutboxCode = "";
                            }
                            else
                            {
                                MessageBox.Show("未维护单盘标签");
                                return;
                            }
                        }
                        //勾选了中盒自动打印
                        if (MidLabelAutoPrint.Checked)
                            AutoPrintMidLabel();
                    }
                }
                //采集未通过的时候
                else
                {
                    //如果自动采集采集未成功需要移动到下一行
                    if (!AutoMatch.Checked)
                        SetRowIndexToCollectRow();
                }
                //当前项目已采集完成,重置采集项目
                CurrentItemIndex = 0;
                //未勾选自动匹配,设置到下一个未采集的行
                if (!AutoMatch.Checked)
                    SetRowIndexToCollectRow();
            }
            //提醒用户需要采集的数据
            RemindUser();
            RefreshProcessData();
            MessageLog.AppendText(">>扫描到数据" + Input.Text + "\n", Color.Blue);
            //如果所采集的行的物料不一样的话,重新计算箱内容量
            if (CurrentRowIndex - 1 > 0)
            {
                string LastRowProd = LabelInf.Rows[CurrentRowIndex - 1].Cells["pib_prodcode"].Value.ToString();
                string CurrentRowProd = LabelInf.Rows[CurrentRowIndex].Cells["pib_prodcode"].Value.ToString();
                //如果两行的物料资料不相等的话
                if (LastRowProd != CurrentRowProd)
                    SetOutBoxCapacity(CurrentRowProd);
            }
            if (CleanInputAfterCollect.Checked)
                Input.Text = "";
        }

        /// <summary>
        /// 根据物料资料的参数设置外箱容量
        /// </summary>
        /// <param name="pr_code"></param>
        private void SetOutBoxCapacity(string pr_code)
        {
            DataTable temp = (DataTable)dh.ExecuteSql("select pr_qtyperplace,pr_zxbzs from product where pr_code='" + pr_code + "'", "select");
            if (temp.Rows.Count > 0)
            {
                //try { OutboxCapacity.Value = (decimal)temp.Rows[0]["pr_qtyperplace"] / (decimal)temp.Rows[0]["pr_zxbzs"]; }
                //catch (Exception) { }
            }
        }

        //设置行的索引到当前需要采集的行
        private void SetRowIndexToCollectRow()
        {
            //获取当前需要采集的行
            for (int i = CurrentRowIndex; i < LabelInf.RowCount; i++)
            {
                if (LabelInf.Rows[i].Cells["pib_ifpick"].FormattedValue.ToString() != "True")
                {
                    griddetno.Text = LabelInf.Rows[i].Cells["pib_pdno"].FormattedValue.ToString();
                    pr_code.Text = LabelInf.Rows[i].Cells["pib_prodcode"].FormattedValue.ToString();
                    CurrentRowIndex = LabelInf.Rows[i].Cells["pib_prodcode"].RowIndex;
                    break;
                }
            }
        }

        private void AutoPrintSingleLabel(string pib_id, string outboxcode)
        {
            bool PrintBlankLabel = false;
            if (PrintMethod == "CodeSoft")
                Print.CodeSoft.SinglePrint(SingleDoc, SingleLabelParam, pib_id);
            else
            {
                //第一箱不打印空标签
                if (outboxcode != "" && Last_OutboxCode == "")
                {
                    PrintBlankLabel = false;
                }
                //如果外箱不相等
                else if (outboxcode != "" && Last_OutboxCode != "" && outboxcode != Last_OutboxCode)
                {
                    PrintBlankLabel = true;
                }
                Last_OutboxCode = outboxcode;
                //打印一张空白标签
                if (LabelSpace.Checked && PrintBlankLabel)
                {
                    Print.BarTender.SinglePrint(EmptySingleFormat, SingleLabelParam, "-1");
                }
                Print.BarTender.SinglePrint(SingleFormat, SingleLabelParam, pib_id);
            }
            LabelInf.Rows[CurrentRowIndex].Cells["pib_ifprint"].Value = true;
            sdh.ExecuteSql("update prodiobarcode set pib_ifprint=-1 where pib_id='" + pib_id + "'", "update");
        }

        /// <summary>
        /// 提醒用户当前采集的项目
        /// </summary>
        private void RemindUser()
        {
            SetRowIndexToCollectRow();
            if (ScanData.ToArray().Length > 0)
            {
                object[] arr = (ScanData.ToArray()[CurrentItemIndex] as ArrayList<string>).ToArray();
                string Inf = "";
                for (int i = 0; i < arr.Length; i++)
                {
                    Inf += arr[i] + "  ";
                }
                MessageLog.AppendText(">>当前采集行" + (CurrentRowIndex + 1) + ",请采集" + Inf + "\n", Color.Green);
            }
        }

        /// <summary>
        /// 自定义函数 将匹配之后的值设置到Cell中,传递引用,每次赋值之后从List中移除已使用过的
        /// </summary>
        /// <param name="data"></param>
        /// <param name="kind"></param>
        private void SetDataToCell(ref Dictionary<string, string> setdata)
        {
            int length = setdata.Count;
            string pib_id = LabelInf.Rows[CurrentRowIndex].Cells["pib_id1"].Value.ToString();
            string LotNo = "";
            string DateCode = "";
            foreach (var item in setdata)
            {
                string[] data = new string[setdata.Count];
                for (int i = 0; i < length; i++)
                {
                    data[i] = setdata[item.Key];
                }
                DataGridViewCell cell = null;
                string Matchstr = "";
                switch (item.Key)
                {
                    case "DATECODE":
                        cell = LabelInf.Rows[CurrentRowIndex].Cells["pib_datecode"];
                        Matchstr = MatchStr(item.Value, "DATECODE");
                        DateCode = Matchstr;
                        length--;
                        break;
                    case "LOTNO":
                        cell = LabelInf.Rows[CurrentRowIndex].Cells["pib_lotno"];
                        Matchstr = MatchStr(item.Value, "LOTNO");
                        LotNo = Matchstr;
                        length--;
                        break;
                    case "MPN":
                        cell = LabelInf.Rows[CurrentRowIndex].Cells["pr_vendprodcode"];
                        Matchstr = MatchStr(item.Value, "MPN");
                        //采集的供应商号不匹配的话
                        if (cell.Value.ToString() != Matchstr)
                        {
                            CollectVeProdCodePass = false;
                            //添加需要重绘的Cell
                            LabelInf.Refresh();
                            MessageLog.AppendText(">>供应商物料编号不匹配\n", Color.Red);
                        }
                        else
                        {
                            LabelInf.Refresh();
                            CollectVeProdCodePass = true;
                        }
                        length--;
                        break;
                    case "QTY":
                        cell = LabelInf.Rows[CurrentRowIndex].Cells["pib_qty"];
                        Matchstr = MatchStr(item.Value, "QTY");
                        //如果采集的数量不相等的话
                        if (cell.Value.ToString() != Matchstr)
                        {
                            CollectQTYPass = false;
                            LabelInf.Refresh();
                            MessageLog.AppendText(">>数量不匹配\n", Color.Red);
                        }
                        else
                        {
                            LabelInf.Refresh();
                            CollectQTYPass = true;
                        }
                        length--;
                        break;
                    case "品牌":
                        cell = LabelInf.Rows[CurrentRowIndex].Cells["pib_brand"];
                        Matchstr = MatchStr(item.Value, "品牌");
                        //如果采集的数量不相等的话
                        if (cell.Value.ToString() != Matchstr)
                        {
                            CollectQTYPass = false;
                            LabelInf.Refresh();
                            MessageLog.AppendText(">>品牌不匹配\n", Color.Red);
                        }
                        else
                        {
                            LabelInf.Refresh();
                            CollectQTYPass = true;
                        }
                        length--;
                        break;
                    default:
                        break;
                }
                //如果数据为空或者数据不为空的时候但是和需要采集的数据不相等的情况下进行采集
                //MPN和QTY只做比较不需要赋值
                if (cell.Value.ToString() == "" || cell.Value.ToString() != Matchstr)
                {
                    string MatchResult = "";
                    if (item.Key != "MPN" && item.Key != "QTY" && item.Key != "品牌")
                    {
                        DataTable dt = (DataTable)LabelInf.DataSource;
                        cell.Value = Matchstr;
                        MatchResult = "成功";
                    }
                    else
                        MatchResult = "失败";
                    switch (SiItem[item.Key]["si_kind"])
                    {
                        case "索引字符":
                            LogManager.DoLog("采集项" + item.Key + ",匹配结果:【" + MatchResult + "】,匹配方式:" + SiItem[item.Key]["si_kind"] + ",使用字符" + SiItem[item.Key]["si_indexstring"] + ",匹配后字符串" + Matchstr);
                            break;
                        case "起始位置":
                            LogManager.DoLog("采集项" + item.Key + ",匹配结果:【" + MatchResult + "】,匹配方式:" + SiItem[item.Key]["si_kind"] + ",从第" + SiItem[item.Key]["si_index"] + "位开始匹配,匹配后字符串" + Matchstr);
                            break;
                        case "二次解析":
                            LogManager.DoLog("采集项" + item.Key + ",匹配结果:【" + MatchResult + "】,匹配方式:" + SiItem[item.Key]["si_kind"] + ",匹配后字符串" + Matchstr);
                            break;
                        case "全部":
                            LogManager.DoLog("采集项" + item.Key + ",匹配结果:【" + MatchResult + "】,匹配方式:" + SiItem[item.Key]["si_kind"] + ",匹配后字符串" + Matchstr);
                            break;
                        default:
                            break;
                    }
                }
                else
                    LogManager.DoLog("采集项" + item.Key + ",匹配结果:【成功】,匹配方式:" + SiItem[item.Key]["si_kind"] + ",,匹配后字符串" + Matchstr);
            }
            sql.Clear();
            sql.Append("update prodiobarcode set pib_ifpick=-1");
            if (LotNo != "")
            {
                sql.Append(",pib_lotno='" + LotNo + "'");
            }
            if (DateCode != "")
            {
                string year = "";
                string month = "";
                string day = "";
                string date = "";
                string pr_brand = LabelInf.Rows[CurrentRowIndex].Cells["pib_brand"].Value.ToString();
                LogicHandler.GetTimeFromDatecode(DateCode, pr_brand, out year, out month, out day, out date);
                sql.Append(",pib_datecode='" + DateCode + "',pib_year='" + year + "',pib_month='" + month + "',pib_day='" + day + "' ");
            }
            sql.Append("where pib_id='" + pib_id + "'");
            sdh.ExecuteSql(sql.ToString(), "update");
            //添加外箱号,如果外箱号的箱内容量不为0并且已经采集完成
            SetOutBoxCode2(false);
        }

        //
        /// <summary>
        /// 设置外箱号
        /// </summary>
        /// <param name="BatchCollect">是否批量采集</param>
        private void SetOutBoxCode2(bool BatchCollect)
        {
            if (OutboxCapacity.Value != 0)
            {
                //获取当前出入口单最大的外箱号
                for (int i = 0; i < LabelInf.RowCount; i++)
                {
                    string outboxcode = LabelInf.Rows[i].Cells["pib_outboxcode2"].Value.ToString();
                    if (outboxcode.Contains("-"))
                    {
                        if (int.Parse(outboxcode.Split('-')[0] == "" ? "1" : outboxcode.Split('-')[0]) > MaxOutBoxCode)
                            MaxOutBoxCode = int.Parse(outboxcode.Split('-')[0]);
                    }
                    else
                    {
                        if (int.Parse(outboxcode == "" ? "0" : outboxcode) > MaxOutBoxCode)
                            MaxOutBoxCode = int.Parse(outboxcode);
                    }
                }
                //统计最大的箱号存在多少
                int MaxOutBoxCodeCount = 0;
                for (int i = 0; i < LabelInf.RowCount; i++)
                {
                    if (LabelInf.Rows[i].Cells["pib_outboxcode2"].Value.ToString() == MaxOutBoxCode.ToString())
                        MaxOutBoxCodeCount = MaxOutBoxCodeCount + 1;
                }
                //如果是获取过包装单的话则不再继续追加箱号
                if (!GetPackingCode)
                {
                    //如果箱内的盒数量小于容量,继续使用此箱号赋值,否则箱号+1
                    if (BatchCollect)
                    {
                        if (MaxOutBoxCodeCount < OutboxCapacity.Value)
                            LabelInf.Rows[CurrentRowIndex].Cells["pib_outboxcode2"].Value = MaxOutBoxCode;
                        else
                        {
                            MaxOutBoxCode = MaxOutBoxCode + 1;
                            LabelInf.Rows[CurrentRowIndex].Cells["pib_outboxcode2"].Value = MaxOutBoxCode;
                        }
                    }
                    else
                    {
                        if (MaxOutBoxCodeCount <= OutboxCapacity.Value)
                            LabelInf.Rows[CurrentRowIndex].Cells["pib_outboxcode2"].Value = MaxOutBoxCode;
                        else
                        {
                            MaxOutBoxCode = MaxOutBoxCode + 1;
                            LabelInf.Rows[CurrentRowIndex].Cells["pib_outboxcode2"].Value = MaxOutBoxCode;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 自定义函数 根据匹配规则
        /// si_item的二维数组,str是需要赋值的字符串,item表示DateCode,LotNo等
        /// </summary>
        /// <param name="SiItem"></param>
        /// <param name="str"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        private string MatchStr(string str, string item)
        {
            string kind = SiItem[item]["si_kind"];
            //起始字符不为空的时候
            switch (kind)
            {
                case "起始位置":
                    if (SiItem[item]["si_index"] != "")
                    {
                        try
                        {
                            //长度不为空的时候按照指定的长度去取数据
                            if (SiItem[item]["si_length"] != "")
                                str = str.Substring(int.Parse(SiItem[item]["si_index"]), int.Parse(SiItem[item]["si_length"]));
                            //长度为空的时候取index之后的全部数据
                            else
                                str = str.Substring(int.Parse(SiItem[item]["si_index"]));
                        }
                        catch (Exception e) { LogManager.DoLog(e.StackTrace); }
                    }
                    break;
                case "索引字符":
                    try
                    {
                        if (SiItem[item]["si_indexstring"] != "")
                        {
                            //长度不为空的时候按照指定的长度去取数据
                            if (SiItem[item]["si_length"] != "")
                                str = str.Substring(str.IndexOf(SiItem[item]["si_indexstring"]) + 1, int.Parse(SiItem[item]["si_length"]));
                            //长度为空的时候取index之后的全部数据
                            else
                                str = str.Substring(str.IndexOf(SiItem[item]["si_indexstring"]) + 1);
                        }
                    }
                    catch (Exception e) { LogManager.DoLog(e.StackTrace); }
                    break;
                case "全部":
                    break;
                default:
                    break;
            }
            if (SiItem[item]["si_expression"] != "")
            {
                string log = "使用正则表达式" + SiItem[item]["si_expression"] + "匹配数据" + str;
                reg = new Regex(SiItem[item]["si_expression"]);
                try
                {
                    str = reg.Matches(str)[int.Parse(SiItem[item]["si_expressionitem"].ToString()) - 1].Value;
                }
                catch (Exception)
                {

                }
                log += ",匹配后数据" + str;
                LogManager.DoLog(log);
            }
            return str;
        }

        //关闭窗口前提示用户确认
        private void 贴标机条码打印_FormClosing(object sender, FormClosingEventArgs e)
        {
            //如果不是注销的话
            if (!logout)
            {
                string close = MessageBox.Show(this.ParentForm, "是否关闭", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
                if (close.ToString() != "Yes")
                    e.Cancel = true;
                else
                {
                    if (lbl != null)
                        lbl.Quit();
                    if (engine != null)
                        engine.Dispose();
                    LogManager.DoLog("关闭程序");
                }
            }
        }

        /// <summary>
        /// 获取打印标签
        /// </summary>
        private void GetInOutInfAndLabelFile()
        {
            ComBoxClickChangeLabelDoc = false;
            Attach = (DataTable)dh.ExecuteSql("select lap_param lp_name,lap_value lp_sql  from LabelAttachPARAMETER where lap_custcode='" + cu_code.Text + "'", "select");
            sql.Clear();
            sql.Append("select to_char(nvl(cl_date,sysdate),'YYYY-MM-DD HH24:Mi:SS') cl_date,cl_labelname,cl_isdefault,la_id||'#'||cl_labelurl||'#'||to_char(cl_date,'YYYY-MM-DD HH24:Mi:SS') ");
            sql.Append(" la_id,cl_custcode from customerlabel left join customer on cu_code=cl_custcode left join label on la_code=CL_LABELCODE where (cl_custcode='" + cu_code.Text + "' ");
            sql.Append(" or cl_custcode is null) and cl_labeltype='单盘' order by cl_custcode");
            dt = (DataTable)dh.ExecuteSql(sql.ToString(), "select");
            SingleLabelCombox.DisplayMember = "cl_labelname";
            SingleLabelCombox.ValueMember = "la_id";
            SingleLabelCombox.DataSource = dt;
            if (SingleDoc != null)
                SingleDoc.Close();
            if (!GetGridOnly.Checked)
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string LabelUrl = dt.Rows[i]["la_id"].ToString().Split('#')[1];
                    string LabelName = dt.Rows[i]["cl_labelname"].ToString();
                    System.DateTime time = Convert.ToDateTime(dt.Rows[i]["cl_date"].ToString());
                    FileInfo file = new FileInfo(ftpOperater.DownLoadTo + LabelName);
                    if (time.ToString() != file.LastWriteTime.ToString())
                        BaseUtil.GetLabelUrl(LabelUrl, LabelName, time);
                }
            if (SingleLabelCombox.Text != "")
            {
                if (PrintMethod == "CodeSoft")
                {
                    SingleDoc = lbl.Documents.Open(ftpOperater.DownLoadTo + SingleLabelCombox.Text);
                    SingleDoc.Printer.SwitchTo(SingleLabelPrinter.Text);
                }
                else
                {
                    if (SingleFormat != null)
                    {
                        SingleFormat.Close(SaveOptions.DoNotSaveChanges);
                    }
                    SingleFormat = engine.Documents.Open(ftpOperater.DownLoadTo + SingleLabelCombox.Text);
                    SingleFormat.PrintSetup.PrinterName = SingleLabelPrinter.Text;
                }
                SingleLabelParam = (DataTable)dh.ExecuteSql("select lp_name,lp_sql,lp_valuetype from label left join LABELPARAMETER on la_id= lp_laid where la_id=" + SingleLabelCombox.SelectedValue.ToString().Split('#')[0], "select");
            }
            sql.Clear();
            sql.Append("select to_char(nvl(cl_date,sysdate),'YYYY-MM-DD HH24:Mi:SS') cl_date,cl_labelname,cl_isdefault,la_id||'#'||cl_labelurl||'#'||to_char(cl_date,'YYYY-MM-DD HH24:Mi:SS') ");
            sql.Append(" la_id,cl_custcode from customerlabel left join customer on cu_code=cl_custcode left join label on la_code=CL_LABELCODE where (cl_custcode='" + cu_code.Text + "' ");
            sql.Append(" or cl_custcode is null) and cl_labeltype='中盒' order by cl_labelname");
            dt = (DataTable)dh.ExecuteSql(sql.ToString(), "select");
            MidLabelCombox.DisplayMember = "cl_labelname";
            MidLabelCombox.ValueMember = "la_id";
            MidLabelCombox.DataSource = dt;
            if (MidDoc != null)
                MidDoc.Close();
            if (!GetGridOnly.Checked)
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string LabelUrl = dt.Rows[i]["la_id"].ToString().Split('#')[1];
                    string LabelName = dt.Rows[i]["cl_labelname"].ToString();
                    System.DateTime time = Convert.ToDateTime(dt.Rows[i]["cl_date"].ToString());
                    FileInfo file = new FileInfo(ftpOperater.DownLoadTo + LabelName);
                    if (time.ToString() != file.LastWriteTime.ToString())
                        BaseUtil.GetLabelUrl(LabelUrl, LabelName, time);
                }

            if (MidLabelCombox.Text != "")
            {
                if (PrintMethod == "CodeSoft")
                {
                    MidDoc = lbl.Documents.Open(ftpOperater.DownLoadTo + MidLabelCombox.Text);
                    MidDoc.Printer.SwitchTo(MidLabelPrinter.Text);
                }
                else
                {
                    if (MidFormat != null)
                    {
                        MidFormat.Close(SaveOptions.DoNotSaveChanges);
                    }
                    MidFormat = engine.Documents.Open(ftpOperater.DownLoadTo + MidLabelCombox.Text);
                    MidFormat.PrintSetup.PrinterName = MidLabelPrinter.Text;
                }
                MidLabelParam = (DataTable)dh.ExecuteSql("select lp_name,lp_sql,lp_valuetype from label left join LABELPARAMETER on la_id= lp_laid where la_id=" + MidLabelCombox.SelectedValue.ToString().Split('#')[0], "select");
            }
            //缓存中盒参数
            sql.Clear();
            sql.Append("select to_char(nvl(cl_date,sysdate),'YYYY-MM-DD HH24:Mi:SS') cl_date,cl_labelname,cl_isdefault,la_id||'#'||cl_labelurl||'#'||to_char(cl_date,'YYYY-MM-DD HH24:Mi:SS') ");
            sql.Append(" la_id,cl_custcode from customerlabel left join customer on cu_code=cl_custcode left join label on la_code=CL_LABELCODE where (cl_custcode='" + cu_code.Text + "' ");
            sql.Append(" or cl_custcode is null) and cl_labeltype='外箱' order by cl_custcode");
            dt = (DataTable)dh.ExecuteSql(sql.ToString(), "select");
            OutBoxCombox.DisplayMember = "cl_labelname";
            OutBoxCombox.ValueMember = "la_id";
            OutBoxCombox.DataSource = dt;
            if (OutBoxDoc != null)
                OutBoxDoc.Close();
            if (!GetGridOnly.Checked)
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string LabelUrl = dt.Rows[i]["la_id"].ToString().Split('#')[1];
                    string LabelName = dt.Rows[i]["cl_labelname"].ToString();
                    System.DateTime time = Convert.ToDateTime(dt.Rows[i]["cl_date"].ToString());
                    FileInfo file = new FileInfo(ftpOperater.DownLoadTo + LabelName);
                    if (time.ToString() != file.LastWriteTime.ToString())
                        BaseUtil.GetLabelUrl(LabelUrl, LabelName, time);
                }
            if (OutBoxCombox.Text != "")
            {
                if (PrintMethod == "CodeSoft")
                {
                    OutBoxDoc = lbl.Documents.Open(ftpOperater.DownLoadTo + OutBoxCombox.Text);
                    OutBoxDoc.Printer.SwitchTo(OutBoxPrinter.Text);
                }
                else
                {
                    if (OutFormat != null)
                    {
                        OutFormat.Close(SaveOptions.DoNotSaveChanges);
                    }
                    OutFormat = engine.Documents.Open(ftpOperater.DownLoadTo + OutBoxCombox.Text);
                    OutFormat.PrintSetup.PrinterName = OutBoxPrinter.Text;
                }
                OutLabelParam = (DataTable)dh.ExecuteSql("select lp_name,lp_sql,lp_valuetype from label left join LABELPARAMETER on la_id= lp_laid where la_id=" + OutBoxCombox.SelectedValue.ToString().Split('#')[0], "select");
            }
            try
            {
                //打开空标签文件
                if (EmptySingleFormat == null)
                {
                    EmptySingleFormat = engine.Documents.Open(System.Windows.Forms.Application.StartupPath + @"\Empty.btw");
                    EmptySingleFormat.PrintSetup.PrinterName = SingleLabelPrinter.Text;
                }
                if (EmptyOutFormat == null)
                {
                    EmptyOutFormat = engine.Documents.Open(System.Windows.Forms.Application.StartupPath + @"\Empty1.btw");
                    EmptyOutFormat.PrintSetup.PrinterName = OutBoxPrinter.Text;
                }
            }
            catch (Exception)
            {

            }
            //缓存外箱参数
            ComBoxClickChangeLabelDoc = true;
        }
        bool InitGetLabel = true;
        /// <summary>
        /// 出入库单录入框的回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pi_inoutno_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                sql.Clear();
                sql.Append("select pi_id,pi_cardcode,pi_class,to_char(pi_date,'yyyymmdd')pi_date from prodinout where pi_inoutno='" + pi_inoutno.Text + "'");
                dt = (DataTable)dh.ExecuteSql(sql.ToString(), "select");
                if (dt.Rows.Count > 0)
                {
                    InitGetLabel = true;
                    cu_code.Text = dt.Rows[0]["pi_cardcode"].ToString();
                    InitGetLabel = false;
                    pi_date.Text = dt.Rows[0]["pi_date"].ToString();
                    pi_class.Text = dt.Rows[0]["pi_class"].ToString();
                    PI_ID = dt.Rows[0]["pi_id"].ToString();

                    if (dh.GetConfig("AutoBarcode", "ProdInOut!Sale").ToString() != "")
                    {
                        string[] param = new string[] { PI_ID, ""};
                        dh.CallProcedure("GetCustBarcode", ref param);
                    }
                    if (dh.GetConfig("PassOrNeg", "FTPModel").ToString() != "Y")
                    {
                        FTPModel.Checked = false;
                        SystemInf.FTPModel = false;
                    }
                    else
                    {
                        FTPModel.Checked = true;
                        SystemInf.FTPModel = true;
                    }
                    CurrentItemIndex = 0;
                    CurrentRowIndex = 0;
                    LoadGridData(sender, e);
                    //重新输入单号后清除缓存
                    MidBoxArgument.Clear();
                    SingleBoxArgument.Clear();
                    MidIDAndOutboxcode.Clear();
                    SingleID.Clear();
                    //刷新采集进度
                    RefreshProcessData();
                    //设置当前的最大箱号
                    for (int i = 0; i < LabelInf.RowCount; i++)
                    {
                        string outboxcode = LabelInf.Rows[i].Cells["pib_outboxcode2"].Value.ToString();
                        //如果包含有-,则需要解析
                        if (outboxcode.Contains("-"))
                            if (int.Parse(outboxcode.Split('-')[0] == "" ? "1" : outboxcode.Split('-')[0]) > MaxOutBoxCode)
                                MaxOutBoxCode = int.Parse(outboxcode.Split('-')[0]);
                        //else
                        //if (int.Parse(outboxcode == "" ? "1" : outboxcode) > MaxOutBoxCode)
                        //    MaxOutBoxCode = int.Parse(outboxcode);
                    }
                    thread = new Thread(GetInOutInfAndLabelFile);
                    stw = new SetLoadingWindow(thread, "正在获取打印标签");
                    BaseUtil.SetFormCenter(stw);
                    stw.ShowDialog();
                    LogicHandler.CustInit(PI_ID);
                    //重置采集项次
                    LogManager.DoLog("输入单号【" + pi_inoutno.Text + "】");
                }
                else
                    MessageBox.Show("当前出入库单号不存在!");
            }
        }

        private void SingleBoxPrint()
        {
            if (SingleLabelParam.Rows.Count > 0 && LabelInf.Rows.Count > 0)
            {
                //每次打印清除之前缓存的行号和ID,后面会判断需要打印的数据重新加载
                MidIDAndOutboxcode.Clear();
                SingleID.Clear();
                //获取全部的中盒号
                Dictionary<string, bool> outboxcode1 = new Dictionary<string, bool>();
                //判断所有盒号为该盒的是否勾选已采集
                outboxcode1.Add(LabelInf.Rows[0].Cells["pib_outboxcode1"].Value.ToString(), true);
                for (int i = 0; i < LabelInf.Rows.Count; i++)
                {
                    if (!SingleID.Contains(LabelInf.Rows[i].Cells["pib_id1"].Value.ToString()))
                        SingleID.Add(LabelInf.Rows[i].Cells["pib_id1"].Value.ToString());
                    if (LabelInf.Rows[i].Cells["Choose"].FormattedValue.ToString() == "True" && LabelInf.Rows[i].Cells["pib_ifpick"].FormattedValue.ToString() == "True" && LabelInf.Rows[i].Cells["pib_ifprint"].FormattedValue.ToString() != "True")
                    {
                        //如果不存在中盒号则进行添加
                        if (!MidIDAndOutboxcode.ContainsValue(LabelInf.Rows[i].Cells["pib_outboxcode1"].Value.ToString()))
                        {
                            MidIDAndOutboxcode.Add(LabelInf.Rows[i].Cells["pib_id1"].Value.ToString(), LabelInf.Rows[i].Cells["pib_outboxcode1"].Value.ToString());
                        }
                    }
                }
                if (SingleID.ToArray().Length == 0)
                {
                    MessageBox.Show("选择的行未勾选采集或者已打印");
                    return;
                }
                for (int i = 0; i < LabelInf.RowCount; i++)
                {
                    if (i + 1 < LabelInf.RowCount)
                    {
                        //如果本行的中盒号和下一行不相等的话
                        if (LabelInf.Rows[i].Cells["pib_outboxcode1"].Value.ToString() != LabelInf.Rows[i + 1].Cells["pib_outboxcode1"].Value.ToString())
                        {
                            if (!outboxcode1.ContainsKey(LabelInf.Rows[i + 1].Cells["pib_outboxcode1"].Value.ToString()))
                                outboxcode1.Add(LabelInf.Rows[i + 1].Cells["pib_outboxcode1"].Value.ToString(), true);
                        }
                    }
                    //只要有一行没有采集满就不打印
                    if (LabelInf.Rows[i].Cells["pib_outboxcode1"].Value.ToString() == LabelInf.Rows[CurrentRowIndex].Cells["pib_outboxcode1"].Value.ToString())
                    {
                        if (LabelInf.Rows[i].Cells["pib_ifpick"].FormattedValue.ToString() != "True")
                            outboxcode1[LabelInf.Rows[i].Cells["pib_outboxcode1"].Value.ToString()] = false;
                    }
                }
                //用于判断用户是否勾选了行
                int CheckedRowCount = 0;
                string[] arg = SingleBoxArgument.ToArray();
                for (int i = 0; i < LabelInf.RowCount; i++)
                {
                    //勾选了并且未打印
                    if (LabelInf.Rows[i].Cells["Choose"].FormattedValue.ToString() == "True" && LabelInf.Rows[i].Cells["pib_ifpick"].FormattedValue.ToString() == "True" && LabelInf.Rows[i].Cells["pib_ifprint"].FormattedValue.ToString() != "True")
                    {
                        CheckedRowCount = CheckedRowCount + 1;
                        CurrentRowIndex = i;
                        //以标签模板的参数为基准,循环取数
                        try
                        {
                            string pib_id = LabelInf.Rows[i].Cells["pib_id1"].Value.ToString();
                            string outboxcode = LabelInf.Rows[i].Cells["pib_outboxcode2"].Value.ToString();
                            AutoPrintSingleLabel(pib_id, outboxcode);
                            if (MidLabelAutoPrint.Checked)
                            {
                                //判断当前行的盒号和下一行不相等或者已经是最后一行了
                                if (i + 1 == LabelInf.RowCount || LabelInf.Rows[i].Cells["pib_outboxcode1"].Value.ToString() != LabelInf.Rows[i + 1 == LabelInf.RowCount ? i : i + 1].Cells["pib_outboxcode1"].Value.ToString())
                                {
                                    if (outboxcode1[LabelInf.Rows[i].Cells["pib_outboxcode1"].Value.ToString()])
                                    {
                                        if (MidLabelCombox.SelectedValue != null)
                                        {
                                            MidBoxCodePrint(CurrentRowIndex);
                                        }
                                    }
                                }
                            }
                            //勾选为已打印
                            LabelInf.Rows[i].Cells["pib_ifprint"].Value = true;
                            sdh.ExecuteSql("update prodiobarcode set pib_ifprint=-1 where pib_id='" + pib_id + "'", "update");
                        }
                        catch (Exception ex) { LogManager.DoLog(ex.Message); }
                    }
                }
                Last_OutboxCode = "";
                dh.BatchInsert("update prodiobarcode set pib_printdate=sysdate where pib_id=:pib_id", new string[] { "pib_id" }, SingleID.ToArray());
                if (CheckedRowCount == 0)
                    MessageBox.Show("未勾选打印明细!");
                else if (CurrentRowIndex + 1 < LabelInf.Rows.Count)
                    CurrentRowIndex = CurrentRowIndex + 1;
                outboxcode1.Clear();
            }
            else
            {
                MessageBox.Show("此模板尚未维护参数或不存在打印明细");
                return;
            }
        }

        private void SingleLabelPrint_Click(object sender, EventArgs e)
        {
            if (SingleLabelCombox.Text != "")
            {
                if (SingleBoxBegin.Text != "" || SingleBoxEnd.Text != "")
                {
                    try
                    {
                        int begin = int.Parse(SingleBoxBegin.Text == "" ? "1" : SingleBoxBegin.Text);
                        int end = int.Parse(SingleBoxEnd.Text == "" ? LabelInf.Rows.Count.ToString() : SingleBoxEnd.Text);
                        if (begin > 0 && end <= LabelInf.Rows.Count && begin <= end)
                        {
                            for (int i = begin - 1; i < end; i++)
                            {
                                LabelInf.Rows[i].Cells["Choose"].Value = true;
                                LabelInf.Rows[i].Cells["pib_ifpick"].Value = true;
                                LabelInf.Rows[i].Cells["pib_ifprint"].Value = false;
                            }
                        }
                        else
                        {
                            MessageBox.Show("单盘打印范围错误");
                            return;
                        }
                        LabelInf.Invalidate();
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("单盘打印范围错误");
                        return;
                    }
                }
                thread = new Thread(SingleBoxPrint);
                stw = new SetLoadingWindow(thread, "正在打印单盘");
                BaseUtil.SetFormCenter(stw);
                stw.ShowDialog();
            }
            else
                MessageBox.Show("未维护单盘标签");
        }

        private void MidBoxLabelPrint()
        {
            if (MidLabelNum.Text == "")
            {
                int begin = 0;
                int end = 0;
                if (MidBoxBegin.Text != "" || MidBoxEnd.Text != "")
                {
                    try
                    {
                        begin = int.Parse(MidBoxBegin.Text == "" ? "1" : MidBoxBegin.Text);
                        end = int.Parse(MidBoxEnd.Text == "" ? LabelInf.Rows[LabelInf.Rows.Count - 1].Cells["pib_outboxcode1"].Value.ToString() : MidBoxEnd.Text);
                        int minmidbox = int.Parse(LabelInf.Rows[0].Cells["pib_outboxcode1"].Value.ToString());
                        int maxmidbox = int.Parse(LabelInf.Rows[LabelInf.Rows.Count - 1].Cells["pib_outboxcode1"].Value.ToString());
                        if (begin >= minmidbox && end <= maxmidbox && begin <= end)
                        {
                            //设置中盒打印范围的行号
                            for (int i = 0; i < LabelInf.Rows.Count; i++)
                            {
                                string outboxcode1 = LabelInf.Rows[i].Cells["pib_outboxcode1"].Value.ToString();
                                if (outboxcode1 != "")
                                {
                                    if (int.Parse(outboxcode1) == begin)
                                    {
                                        begin = i;
                                    }
                                    if (int.Parse(outboxcode1) == end)
                                    {
                                        end = i;
                                    }
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show("中盒打印范围错误");
                            return;
                        }
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("中盒打印范围错误");
                        return;
                    }
                }
                else
                {
                    end = LabelInf.Rows.Count - 1;
                }
                MidBoxArgument.Clear();
                List<int> MidOutBoxCode = new List<int>();
                List<int> MidOutBoxCodeIndex = new List<int>();
                for (int i = (begin == 0 ? 0 : begin); i <= (end); i++)
                {
                    string outboxcode1 = LabelInf.Rows[i].Cells["pib_outboxcode1"].Value.ToString();
                    if (outboxcode1 != "")
                    {
                        if (!MidIDAndOutboxcode.ContainsValue(outboxcode1))
                            MidIDAndOutboxcode.Add(LabelInf.Rows[i].Cells["pib_id1"].Value.ToString(), outboxcode1);
                        if (!MidOutBoxCode.Contains(int.Parse(outboxcode1)))
                        {
                            MidOutBoxCode.Add(int.Parse(outboxcode1));
                            MidOutBoxCodeIndex.Add(i);
                        }
                    }
                }
                for (int i = 0; i < MidOutBoxCodeIndex.Count; i++)
                {
                    MidBoxCodePrint(MidOutBoxCodeIndex[i]);
                }
                MidBoxArgument.Clear();
                return;
            }
            bool FindMidLabel = false;
            if (MidLabelCombox.SelectedValue != null)
            {
                //中盒号所在的行
                int MidLabelRowIndex = 0;
                //查找是否存在该中盒号
                List<int> MidRowIndex = new List<int>();
                //缓存中盒数据
                for (int i = 0; i < LabelInf.RowCount; i++)
                {
                    if (MidLabelNum.Text == LabelInf.Rows[i].Cells["pib_outboxcode1"].Value.ToString())
                    {
                        //找到了输入的中盒号停止循环
                        FindMidLabel = true;
                        MidLabelRowIndex = i;
                        MidRowIndex.Add(i);
                    }
                }
                //找到了指定的盒号
                if (FindMidLabel)
                    MidBoxCodePrint(MidLabelRowIndex);
                else
                    MessageBox.Show("该出入库单未找到该中盒号!");
            }
            else
                MessageBox.Show("未维护中盒模板");
        }

        private void MidLabelPrint_Click(object sender, EventArgs e)
        {
            if (MidLabelCombox.Text != "")
            {
                thread = new Thread(MidBoxLabelPrint);
                stw = new SetLoadingWindow(thread, "正在打印中盒");
                BaseUtil.SetFormCenter(stw);
                stw.ShowDialog();
            }
            else
                MessageBox.Show("未维护中盒标签");
        }

        private void OutBoxPrint()
        {
            List<string> Outboxcode = new List<string>();
            //如果未勾选箱号则对勾选的数据的箱号进行整合
            if (OutBoxNum.Text == "")
            {
                for (int i = 0; i < LabelInf.RowCount; i++)
                {
                    if (LabelInf.Rows[i].Cells["Choose"].FormattedValue.ToString() == "True")
                    {
                        string outboxcode2 = LabelInf.Rows[i].Cells["pib_outboxcode2"].Value.ToString();
                        //富为使用包装单的逻辑
                        //如果不包含该箱号则进行添加
                        if (!Outboxcode.Contains(outboxcode2))
                            Outboxcode.Add(outboxcode2);
                    }
                }
                //按获取到的箱号列表进行打印
                if (Outboxcode.ToArray().Length > 0)
                {
                    try
                    {
                        // 循环打印外箱号
                        for (int i = 0; i < Outboxcode.ToArray().Length; i++)
                        {
                            for (int h = 0; h < LabelInf.RowCount; h++)
                            {
                                if (LabelInf.Rows[h].Cells["pib_outboxcode2"].Value.ToString() == Outboxcode.ToArray()[i])
                                {
                                    OutBoxCodePrint(h);
                                    break;
                                }
                            }
                        }
                    }
                    catch { }
                }
                else
                {
                    MessageBox.Show("请勾选需要打印的外箱");
                }
            }
            else
            {
                bool FindMidLabel = false;
                try
                {
                    int OutBoxLabelRowIndex = 0;
                    //查找是否存在该中盒号
                    for (int i = 0; i < LabelInf.RowCount; i++)
                    {
                        if (OutBoxNum.Text == LabelInf.Rows[i].Cells["pib_outboxcode2"].Value.ToString())
                        {
                            //找到了输入的中盒号停止循环
                            FindMidLabel = true;
                            OutBoxLabelRowIndex = i;
                            break;
                        }
                    }
                    //找到了指定的盒号
                    if (FindMidLabel)
                        OutBoxCodePrint(OutBoxLabelRowIndex);
                    else
                        MessageBox.Show("该出入库单未找到该外箱号!");
                }
                catch (Exception) { }
            }
            Outboxcode.Clear();
        }

        private void MidBoxCodePrint(int rowindex)
        {
            //获取对应行的pib_id
            string pib_id = LabelInf.Rows[rowindex].Cells["pib_id1"].Value.ToString();
            string pib_outboxcode1 = LabelInf.Rows[rowindex].Cells["pib_outboxcode1"].Value.ToString();
            if (PrintMethod == "CodeSoft")
            {
                Print.CodeSoft.MidPrint(MidDoc, MidLabelParam, pi_inoutno.Text, pib_id, pib_outboxcode1);
            }
            else
            {
                Print.BarTender.MidPrint(MidFormat, MidLabelParam, pi_inoutno.Text, pib_id, pib_outboxcode1);
                MidFormat.PrintSetup.PrinterName = MidLabelPrinter.Text;
            }
        }

        private void OutBoxCodePrint(int rowindex)
        {
            //获取对应行的pib_id
            string pib_id = LabelInf.Rows[rowindex].Cells["pib_id1"].Value.ToString();
            string pib_outboxcode2 = LabelInf.Rows[rowindex].Cells["pib_outboxcode2"].Value.ToString();
            if (PrintMethod == "CodeSoft")
                Print.CodeSoft.OutPrint(OutBoxDoc, OutLabelParam, pi_inoutno.Text, pib_id, pib_outboxcode2, cu_print_outprod.Checked, cu_print_outpo.Checked, cu_print_outdc.Checked, cu_print_outlotno.Checked, cu_print_ordercode.Checked);
            else
            {

                if (DiffCustOutBoxCode.Checked)
                {
                    //执行本地SQL,获取需要更新的DataCode
                    DataTable dt = (DataTable)sdh.ExecuteSql(BaseUtil.GetOutBoxSQL(OutFormat, OutLabelParam, pi_inoutno.Text, pib_id, pib_outboxcode2, cu_print_outprod.Checked, cu_print_outpo.Checked, cu_print_outdc.Checked, cu_print_outlotno.Checked, cu_print_ordercode.Checked), "select");
                    //大于1行表示有需要分组的数据
                    if (dt.Rows.Count > 1)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            GetCustRule();
                            string custoutboxcode = LogicHandler.BarcodeMethod1(Prefix, Suffix, SerialNumIndex, SerialNumLength, Radix);
                            string updateCondition = "";
                            //勾选了这些参数并且打印的时候需要才进行更新
                            if (cu_print_outprod.Checked && dt.Columns.Contains("pd_custprodcode"))
                            {
                                updateCondition += " and pd_custprodcode='" + dt.Rows[i]["pd_custprodcode"].ToString() + "'";
                            }
                            if (cu_print_outpo.Checked && dt.Columns.Contains("pd_pocode"))
                            {
                                updateCondition += " and pd_pocode='" + dt.Rows[i]["pd_pocode"].ToString() + "'";
                            }
                            if (cu_print_ordercode.Checked && dt.Columns.Contains("pd_ordercode"))
                            {
                                updateCondition += " and pd_ordercode='" + dt.Rows[i]["pd_ordercode"].ToString() + "'";
                            }
                            if (cu_print_outdc.Checked && dt.Columns.Contains("pib_datecode"))
                            {
                                updateCondition += " and pib_datecode='" + dt.Rows[i]["pib_datecode"].ToString() + "'";
                            }
                            if (cu_print_outlotno.Checked && dt.Columns.Contains("pib_lotno"))
                            {
                                updateCondition += " and pib_lotno='" + dt.Rows[i]["pib_lotno"].ToString() + "'";
                            }
                            try
                            {
                                dh.ExecuteSql("update prodiobarcode set pib_custoutboxcode='" + custoutboxcode + "' where pib_id in(select pib_id from prodiobarcode left join prodinout on pib_inoutno=pi_inoutno left join prodiodetail on pd_piid=pi_id and pib_prodcode=pd_prodcode where pib_inoutno='" + pi_inoutno.Text + "' and pib_outboxcode2='" + pib_outboxcode2 + "' " + updateCondition + " )", "update");
                                LogicHandler.SP_OUTCUSTBARCODE(pi_inoutno.Text, "and pib_outboxcode2='" + pib_outboxcode2 + "' " + updateCondition + " ");
                                dh.UpdateByCondition("RuleMaxNum", "rmn_maxnumber='" + custserialnum + "'", "rmn_nrcode='" + NrCode + "' and rmn_prefix='" + Prefix + "'");

                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message + ex.StackTrace);
                                throw;
                            }
                        }
                    }
                }
                LoadGridData(true);
                Print.BarTender.OutPrint(OutFormat, OutLabelParam, pi_inoutno.Text, pib_id, pib_outboxcode2, cu_print_outprod.Checked, cu_print_outpo.Checked, cu_print_outdc.Checked, cu_print_outlotno.Checked, cu_print_ordercode.Checked);
                if (LabelSpace.Checked)
                {
                    Print.BarTender.OutPrint(EmptyOutFormat, OutLabelParam, pi_inoutno.Text, pib_id, "-1", cu_print_outprod.Checked, cu_print_outpo.Checked, cu_print_outdc.Checked, cu_print_outlotno.Checked, cu_print_ordercode.Checked);
                }
            }
        }

        private void CleanDetail_Click(object sender, EventArgs e)
        {
            ArrayList<string> DeleteID = new ArrayList<string>();
            StringBuilder pibid = new StringBuilder();
            for (int i = 0; i < LabelInf.RowCount; i++)
            {
                if (LabelInf.Rows[i].Cells["Choose"].FormattedValue.ToString() == "True")
                {
                    DeleteID.Add(LabelInf.Rows[i].Cells["pib_id1"].Value.ToString());
                    pibid.Append(LabelInf.Rows[i].Cells["pib_id1"].Value.ToString() + ",");
                }
            }
            //勾选了删除的明细之后
            if (DeleteID.ToArray().Length > 0)
            {
                string close = MessageBox.Show(this.ParentForm, "删除后不可恢复,是否确认删除", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
                if (close.ToString() == "Yes")
                {
                    pibid.Append("1");
                    sdh.ExecuteSql("delete from prodiobarcode where pib_id in(" + pibid + ")", "delete");
                    dh.BatchInsert("delete from prodiobarcode where pib_id=:pib_id", new string[] { "pib_id" }, DeleteID.ToArray());
                    MessageBox.Show("删除成功");
                    LoadGridData(sender, e);
                    RefreshProcessData();
                }
            }
            else
                MessageBox.Show("尚未勾选需要删除的明细");
        }

        private void OutBoxLabelPrint_Click(object sender, EventArgs e)
        {
            if (OutBoxCombox.Text != "")
            {
                thread = new Thread(OutBoxPrint);
                stw = new SetLoadingWindow(thread, "正在打印外箱");
                BaseUtil.SetFormCenter(stw);
                stw.ShowDialog();
            }
            else
                MessageBox.Show("未维护外箱标签");
        }

        /// <summary>
        /// 刷新采集进度
        /// </summary>
        private void RefreshProcessData()
        {
            if (LabelInf.Rows.Count > 0)
            {
                //设置初始化的采集进度
                int Count = 0;
                int CurrentMidBoxCollectedCount = 0;
                //当前盒号的总盘数
                int CurrentMidBoxTotalCount = 0;
                //未超出当前范围的时候
                for (int i = 0; i < LabelInf.RowCount; i++)
                {
                    if (LabelInf.Rows[i].Cells["pib_ifpick"].FormattedValue.ToString() == "True")
                        Count++;
                    //和当前编辑箱号相等行
                    if (LabelInf.Rows[i].Cells["pib_ifpick"].FormattedValue.ToString() == "True" && LabelInf.Rows[CurrentRowIndex].Cells["pib_outboxcode1"].Value.ToString() == LabelInf.Rows[i].Cells["pib_outboxcode1"].Value.ToString())
                        CurrentMidBoxCollectedCount++;
                    //当前盒号一共有几盘
                    if (LabelInf.Rows[CurrentRowIndex].Cells["pib_outboxcode1"].Value.ToString() == LabelInf.Rows[i].Cells["pib_outboxcode1"].Value.ToString())
                        CurrentMidBoxTotalCount++;
                }
                Capacity.Text = "可装" + CurrentMidBoxTotalCount + "盘";
                Installed.Text = "已装" + CurrentMidBoxCollectedCount + "盘";
                //设置当前的箱号和盒号
                Process_outboxcode.Text = LabelInf.Rows[CurrentRowIndex].Cells["pib_outboxcode2"].Value.ToString();
                Process_midboxcode.Text = LabelInf.Rows[CurrentRowIndex].Cells["pib_outboxcode1"].Value.ToString();
                //设置当前总数和已采集数量
                TotalCount.Text = LabelInf.RowCount.ToString();
                CollectedCount.Text = Count.ToString();
            }
        }

        private void LoadGridData(bool AllCollect)
        {
            LoadGridData(AllCollect, new EventArgs());
        }
        DataTable LabelInfDataTable;
        /// <summary>
        /// 自定义函数  加载明细行的数据,多处使用添加进函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadGridData(object sender, EventArgs e)
        {
            AllCollect = sender.Equals(true);
            //查询Oracle数据库
            sql.Clear();
            sql.Append("select t.*,rownum from prodiobarcode_view t where pib_inoutno='" + pi_inoutno.Text + "' ");
            LabelInfDataTable = (DataTable)dh.ExecuteSql(sql.ToString(), "select");
            //查询本地数据库
            sql.Clear();
            sql.Append("select count(1) from prodiobarcode where pib_inoutno='" + pi_inoutno.Text + "'");
            DataTable dt = (DataTable)sdh.ExecuteSql(sql.ToString(), "select");
            int rowcount = int.Parse(dt.Rows[0][0].ToString());
            //如果本地没有缓存过
            if (rowcount == 0 || rowcount != LabelInfDataTable.Rows.Count)
            {
                if (rowcount != LabelInfDataTable.Rows.Count && rowcount != 0)
                {
                    string close = MessageBox.Show(this.ParentForm, "本地条码和服务器条码数量不一致,覆盖本地条码", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
                    if (close == "Yes")
                    {
                        sdh.ExecuteSql("delete from prodiobarcode where pib_inoutno='" + pi_inoutno.Text + "'", "delete");
                        //检验查询的字段和本地数据库字段是否匹配
                        sdh.AddColumFromDataTable(LabelInfDataTable, "prodiobarcode");
                        //将数据保存在本地数据库
                        sdh.SaveDataTable(LabelInfDataTable, "prodiobarcode");
                    }
                }
                else
                {
                    //检验查询的字段和本地数据库字段是否匹配
                    sdh.AddColumFromDataTable(LabelInfDataTable, "prodiobarcode");
                    //将数据保存在本地数据库
                    sdh.SaveDataTable(LabelInfDataTable, "prodiobarcode");
                }
            }
            else if (LabelInfDataTable.Columns.Count != dt.Columns.Count)
            {
                //检验查询的字段和本地数据库字段是否匹配
                sdh.AddColumFromDataTable(LabelInfDataTable, "prodiobarcode");
                sdh.ExecuteSql("delete from prodiobarcode where pib_inoutno='" + pi_inoutno.Text + "'", "delete");
                sdh.SaveDataTable(LabelInfDataTable, "prodiobarcode");
                //sdh.BatchInsert("prodiobarcode", LabelInfDataTable);
            }
            sql.Clear();
            sql.Append("select * from prodiobarcode where pib_inoutno='" + pi_inoutno.Text + "' order by cast(pib_outboxcode1 as int)");
            LabelInfDataTable = (DataTable)sdh.ExecuteSql(sql.ToString(), "select");
            bindingsource(LabelInf, LabelInfDataTable);
            //有数据的话默认取第一条的品牌去取采集策略
            TotalCount.Text = LabelInf.RowCount.ToString();
            if (LabelInf.RowCount > 0)
            {
                Brand = LabelInf.Rows[0].Cells["pib_brand"].FormattedValue.ToString();
                if (Brand != "")
                    sg_code.Text = dh.getFieldDataByCondition("scangroup", "sg_code", "sg_brand='" + Brand + "'").ToString();
                SetOutBoxCapacity(LabelInf.Rows[0].Cells["pib_prodcode"].Value.ToString());
            }
            //绑定数据之后往下找到未采集的数据显示在当前采集的栏目
            for (int i = 0; i < LabelInf.RowCount; i++)
            {
                if (LabelInf.Rows[i].Cells["pib_ifpick"].FormattedValue.ToString() != "True")
                {
                    griddetno.Text = LabelInf.Rows[i].Cells["pib_pdno"].FormattedValue.ToString();
                    pr_code.Text = LabelInf.Rows[i].Cells["pib_prodcode"].FormattedValue.ToString();
                    pib_id.Text = LabelInf.Rows[i].Cells["pib_id1"].FormattedValue.ToString();
                    CurrentRowIndex = LabelInf.Rows[i].Cells["pib_prodcode"].RowIndex;
                    break;
                }
            }
        }

        delegate void BindDataSource(DataGridView dgv, DataTable dt);//定义委托

        void bindingsource(DataGridView dgv, DataTable dt)
        {
            if (dgv.InvokeRequired)
            {
                dgv.Invoke(new BindDataSource(bindingsource), new object[] { dgv, dt });
            }
            else
            {
                dgv.AutoGenerateColumns = false;
                dgv.DataSource = dt;
            }
        }

        /// <summary>
        /// 重绘Cell的颜色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LabelInf_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            bool mouseOver = e.CellBounds.Contains(this.PointToClient(Cursor.Position));
            if (e.ColumnIndex > 0)
            {
                if (LabelInf.Columns[e.ColumnIndex].Name == "pib_madein" || LabelInf.Columns[e.ColumnIndex].Name == "pib_lotno" || LabelInf.Columns[e.ColumnIndex].Name == "pib_datecode" || LabelInf.Columns[e.ColumnIndex].Name == "pib_outboxcode1" || LabelInf.Columns[e.ColumnIndex].Name == "pib_outboxcode2" || LabelInf.Columns[e.ColumnIndex].Name == "pr_brand")
                {
                    SolidBrush solidBrush = new SolidBrush(Color.FromArgb(51, 153, 255));
                    e.Graphics.FillRectangle(mouseOver ? solidBrush : Brushes.LightSeaGreen, e.CellBounds);
                    Rectangle border = e.CellBounds;
                    border.Width -= 1;
                    e.Graphics.DrawRectangle(Pens.White, border);
                    e.PaintContent(e.CellBounds);
                    e.Handled = true;
                }
                if (e.RowIndex >= 0)
                {
                    if (LabelInf.Rows[e.RowIndex].Cells["pib_ifpick"].FormattedValue.ToString() == "True")
                    {
                        if (LabelInf.Columns[e.ColumnIndex].Name == "pib_lotno" || LabelInf.Columns[e.ColumnIndex].Name == "pib_datecode")
                        {
                            SolidBrush solidBrush = new SolidBrush(Color.FromArgb(51, 153, 255));
                            e.Graphics.FillRectangle(Brushes.ForestGreen, e.CellBounds);
                            Rectangle border = e.CellBounds;
                            border.Width -= 1;
                            e.Graphics.DrawRectangle(Pens.Black, border);
                            e.PaintContent(e.CellBounds);
                            e.Handled = true;
                        }
                    }
                }
            }
        }

        private void pr_code_SearchIconClick(object sender, EventArgs e)
        {
            pr_code.Condition = "  pd_inoutno='" + pi_inoutno.Text + "'";
        }

        private void pr_code_UserControlTextChanged(object sender, EventArgs e)
        {
            //用户在重新勾选后重置采集项目的索引
            CurrentItemIndex = 0;
            for (int i = 0; i < LabelInf.RowCount; i++)
            {
                if (pr_code.Text == LabelInf.Rows[i].Cells["pib_prodcode"].Value.ToString() && LabelInf.Rows[i].Cells["pib_ifpick"].FormattedValue.ToString() != "True")
                {
                    CurrentRowIndex = i;
                    break;
                }
            }
        }

        private void Refresh_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            KeyEventArgs e2 = new KeyEventArgs(Keys.Enter);
            pi_inoutno_KeyDown(sender, e2);
        }

        /// <summary>
        /// 采集明细切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void griddetno_KeyDown(object sender, KeyEventArgs e)
        {
            if (Keys.Enter == e.KeyData)
            {
                bool FindDetno = false;
                for (int i = 0; i < LabelInf.RowCount; i++)
                {
                    if (LabelInf.Rows[i].Cells["pib_pdno"].Value.ToString() == griddetno.Text && LabelInf.Rows[i].Cells["pib_ifpick"].FormattedValue.ToString() != "True")
                    {
                        FindDetno = true;
                        CurrentItemIndex = 0;
                        CurrentRowIndex = i;
                        RemindUser();
                        break;
                    }
                }
                if (!FindDetno)
                {
                    MessageBox.Show("不存在未采集的明细序号" + griddetno.Text);
                    return;
                }
            }
        }

        private void AutoPrintMidLabel()
        {
            bool FullBox = true;
            //判断所有盒号未该盒的是否勾选已采集
            for (int i = 0; i < LabelInf.RowCount; i++)
            {
                if (LabelInf.Rows[i].Cells["pib_outboxcode1"].Value.ToString() == LabelInf.Rows[CurrentRowIndex].Cells["pib_outboxcode1"].Value.ToString())
                {
                    if (LabelInf.Rows[i].Cells["pib_ifpick"].FormattedValue.ToString() != "True")
                        FullBox = false;
                }
            }
            //如果当前箱号已经装满了
            if (FullBox)
            {
                if (MidLabelCombox.SelectedValue != null)
                {
                    MidBoxCodePrint(CurrentRowIndex);
                }
                else
                    MessageBox.Show("未维护中盒模板");
            }
        }

        /// <summary>
        /// 勾选的时候自动打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LabelInf_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (LabelInf.Columns[e.ColumnIndex].Name == "pib_datecode")
            {
                string datecode = LabelInf.Rows[e.RowIndex].Cells["pib_datecode"].Value.ToString();
                try
                {
                    System.DateTime dt = System.DateTime.ParseExact(datecode, "yyyyMMdd", CultureInfo.CurrentCulture);
                    GregorianCalendar gc = new GregorianCalendar();
                    int weekOfYear = gc.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
                    if (weekOfYear < 10)
                        LabelInf.Rows[e.RowIndex].Cells["pib_datecode1"].Value = dt.Year.ToString().Substring(2, 2) + "0" + weekOfYear;
                    else
                        LabelInf.Rows[e.RowIndex].Cells["pib_datecode1"].Value = dt.Year.ToString().Substring(2, 2) + weekOfYear;
                }
                catch (Exception) { }
            }
        }

        private void AllCollected_Click(object sender, EventArgs e)
        {
            if (AllCollect == false)
            {
                foreach (DataGridViewRow dr in LabelInf.Rows)
                    dr.Cells[1].Value = true;
                AllCollect = true;
            }
            else
            {
                foreach (DataGridViewRow dr in LabelInf.Rows)
                    dr.Cells[1].Value = false;
                AllCollect = false;
            }
        }

        private void GetOutBoxCode_Click(object sender, EventArgs e)
        {
            if (dh.GetConfig("UsingPacking", "ProdInOut!Sale").ToString() != "")
            {
                int Current = 0;
                sql.Clear();
                sql.Append("select pr_qtyperplace,pd_qty,packingdetail.pd_cartonno,pr_zxbzs,packingdetail.pd_cartons from packingdetail left join packing on pd_piid=pi_id left join prodinout on ");
                sql.Append("pi_packingcode=packing.pi_code left join product on pd_prodcode=pr_code where pi_inoutno='" + pi_inoutno.Text + "' order by pr_code,pd_detno");
                dt = (DataTable)dh.ExecuteSql(sql.ToString(), "select");
                if (dt.Rows.Count > 0)
                {
                    try { OutboxCapacity.Value = (decimal)dt.Rows[0]["pr_qtyperplace"] / (decimal)dt.Rows[0]["pr_zxbzs"]; }
                    catch (Exception) { }
                }
                try
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        int pd_qty = int.Parse(dt.Rows[i]["pd_qty"].ToString());
                        int pr_zxbzs = int.Parse(dt.Rows[i]["pr_zxbzs"].ToString());
                        int pd_cartons = int.Parse(dt.Rows[i]["pd_cartons"].ToString());
                        for (int j = 0; j < pd_qty * pd_cartons / pr_zxbzs; j++)
                        {
                            LabelInf.Rows[Current].Cells["pib_outboxcode2"].Value = dt.Rows[i]["pd_cartonno"].ToString();
                            Current++;
                        }
                    }
                    GetPackingCode = true;
                }
                catch (Exception)
                {
                }
            }
            else
            {
                int BoxCode = 1;
                for (int i = 0; i < LabelInf.Rows.Count; i++)
                {
                    LabelInf.Rows[i].Cells["pib_outboxcode2"].Value = BoxCode;
                    if (i + 1 < LabelInf.Rows.Count)
                    {
                        if (int.Parse(LabelInf.Rows[i].Cells["pib_outboxcode1"].Value.ToString()) % OutboxCapacity.Value == 0 && (LabelInf.Rows[i].Cells["pib_outboxcode1"].Value.ToString() != LabelInf.Rows[i + 1].Cells["pib_outboxcode1"].Value.ToString()))
                        {
                            BoxCode = BoxCode + 1;
                        }
                        else if (cu_print_outdc.Checked)
                        {
                            if (LabelInf.Rows[i].Cells["pib_datecode"].Value.ToString() != LabelInf.Rows[i + 1].Cells["pib_datecode"].Value.ToString())
                            {
                                BoxCode = BoxCode + 1;
                            }
                        }
                        else if (cu_print_outlotno.Checked)
                        {
                            if (LabelInf.Rows[i].Cells["pib_lotno"].Value.ToString() != LabelInf.Rows[i + 1].Cells["pib_lotno"].Value.ToString())
                            {
                                BoxCode = BoxCode + 1;
                            }
                        }
                        else if (cu_print_outpo.Checked)
                        {
                            if (LabelInf.Rows[i].Cells["pd_pocode"].Value.ToString() != LabelInf.Rows[i + 1].Cells["pd_pocode"].Value.ToString())
                            {
                                BoxCode = BoxCode + 1;
                            }
                        }
                        else if (cu_print_outprod.Checked)
                        {
                            if (LabelInf.Rows[i].Cells["pd_custprodcode"].Value.ToString() != LabelInf.Rows[i + 1].Cells["pd_custprodcode"].Value.ToString())
                            {
                                BoxCode = BoxCode + 1;
                            }
                        }
                    }
                }
                sdh.BatchInsert("prodiobarcode", LabelInf.DataSource as DataTable);
            }
            DataTable dt1 = (DataTable)sdh.ExecuteSql("select pib_id,pib_outboxcode1,pib_outboxcode2,pib_custmidboxcode,pib_custoutboxcode,pib_lotno,pib_datecode,pib_ifupload,pib_ifpick,pib_ifprint from prodiobarcode where pib_inoutno='" + pi_inoutno.Text + "' ", "select");
            if (dt1.Rows.Count > 0)
            {
                dh.CallProcedure("sp_uploadbarcode", dt1);
            }
        }

        private void LogingOut_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ChangeMaster ch = new ChangeMaster();
            BaseUtil.SetFormCenter(ch);
            ch.FormClosed += Ch_FormClosed;
            ch.ShowDialog();
        }

        private void Ch_FormClosed(object sender, FormClosedEventArgs e)
        {
            dh = SystemInf.dh;
            sdh = SystemInf.sdh;
            Text = "UAS-出货标签打印-" + SystemInf.MasterName;
        }

        private void LabelInf_DataError(object sender, DataGridViewDataErrorEventArgs e) { }

        /// <summary>
        /// 切换打开的单盘文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SingleLabelCombox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ComBoxClickChangeLabelDoc)
                {
                    if (SingleDoc != null)
                        SingleDoc.Close();
                    if (SingleFormat != null)
                        SingleFormat.Close(SaveOptions.DoNotSaveChanges);
                    System.DateTime time = Convert.ToDateTime(SingleLabelCombox.SelectedValue.ToString().Split('#')[2]);
                    if (SingleLabelCombox.Text != "" && SingleLabelCombox.SelectedValue != null && !GetGridOnly.Checked)
                    {
                        if (PrintMethod == "CodeSoft")
                        {
                            SingleDoc = lbl.Documents.Open(BaseUtil.GetLabelUrl(SingleLabelCombox.SelectedValue.ToString().Split('#')[1], SingleLabelCombox.Text, time));
                            SingleDoc.Printer.Name = SingleLabelPrinter.Text;
                        }
                        else
                        {
                            SingleFormat = engine.Documents.Open(BaseUtil.GetLabelUrl(SingleLabelCombox.SelectedValue.ToString().Split('#')[1], SingleLabelCombox.Text, time));
                            SingleFormat.PrintSetup.PrinterName = SingleLabelPrinter.Text;
                            EmptySingleFormat.PrintSetup.PrinterName = SingleLabelPrinter.Text;
                        }
                    }
                }
            }
            catch (Exception) { }
        }

        /// <summary>
        /// 切换打开的中盒文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MidLabelCombox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ComBoxClickChangeLabelDoc)
                {
                    if (MidDoc != null)
                        MidDoc.Close();
                    if (MidFormat != null)
                        MidFormat.Close(SaveOptions.DoNotSaveChanges);
                    MidFormat = engine.Documents.Open(ftpOperater.DownLoadTo + MidLabelCombox.Text);
                }
            }
            catch (Exception) { }
        }

        /// <summary>
        /// 切换打开的外箱文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OutBoxCombox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ComBoxClickChangeLabelDoc)
                {
                    if (OutBoxDoc != null)
                        OutBoxDoc.Close();
                    if (OutFormat != null)
                        OutFormat.Close(SaveOptions.DoNotSaveChanges);
                    System.DateTime time = Convert.ToDateTime(OutBoxCombox.SelectedValue.ToString().Split('#')[2]);
                    if (OutBoxCombox.Text != "" && OutBoxCombox.SelectedValue != null && !GetGridOnly.Checked)
                    {
                        if (PrintMethod == "CodeSoft")
                        {
                            OutBoxDoc = lbl.Documents.Open(BaseUtil.GetLabelUrl(OutBoxCombox.SelectedValue.ToString().Split('#')[1], OutBoxCombox.Text, time));
                            OutBoxDoc.Printer.Name = OutBoxPrinter.Text;
                        }
                        else
                        {
                            OutFormat = engine.Documents.Open(BaseUtil.GetLabelUrl(OutBoxCombox.SelectedValue.ToString().Split('#')[1], OutBoxCombox.Text, time));
                            OutFormat.PrintSetup.PrinterName = OutBoxPrinter.Text;
                            EmptyOutFormat.PrintSetup.PrinterName = OutBoxPrinter.Text;
                        }
                    }
                }
            }
            catch (Exception) { }
        }

        private void ChooseAll_Click(object sender, EventArgs e)
        {
            if (LabelInf.Rows.Count > 0)
            {
                if (LabelInf.Rows.Count > 0)
                {
                    if (LabelInf.Rows[0].Cells["Choose"].FormattedValue.ToString() == "True")
                    {
                        foreach (DataGridViewRow dr in LabelInf.Rows)
                            dr.Cells[0].Value = false;
                    }
                    else
                    {
                        foreach (DataGridViewRow dr in LabelInf.Rows)
                            dr.Cells[0].Value = true;
                    }
                }
            }
        }

        private void LabelInf_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > 0)
            {
                if (LabelInf.Columns[e.ColumnIndex].Name == "pin_madein")
                {
                    StringBuilder pibid = new StringBuilder();
                    string madein = LabelInf.Rows[e.RowIndex].Cells["pib_madein"].Value.ToString();
                    if (LabelInf.Columns[e.ColumnIndex].Name == "pib_madein" && CollectionUnit.Text == "盒")
                    {
                        string midbox = LabelInf.Rows[e.RowIndex].Cells["pib_outboxcode1"].Value.ToString();
                        for (int i = 0; i < LabelInf.Rows.Count; i++)
                        {
                            if (midbox == LabelInf.Rows[i].Cells["pib_outboxcode1"].Value.ToString())
                            {
                                LabelInf.Rows[i].Cells["pib_madein"].Value = madein;
                                pibid.Append(LabelInf.Rows[i].Cells["pib_id1"].Value + ",");
                            }
                        }
                    }
                    if (LabelInf.Columns[e.ColumnIndex].Name == "pib_madein" && CollectionUnit.Text == "全部")
                    {
                        for (int i = 0; i < LabelInf.Rows.Count; i++)
                        {
                            LabelInf.Rows[i].Cells["pib_madein"].Value = madein;
                            pibid.Append(LabelInf.Rows[i].Cells["pib_id1"].Value + ",");
                        }
                    }
                    pibid.Append("1");
                    sdh.ExecuteSql("update prodiobarcode set pib_madein='" + madein + "' where pib_id in (" + pibid + ")", "update");
                }
            }
        }

        private void ExportData_Click(object sender, EventArgs e)
        {

        }

        private void MidBoxCapacity_Leave(object sender, EventArgs e)
        {
            NumericUpDown nup = (NumericUpDown)sender;
            switch (nup.Name)
            {
                case "MidBoxCapacity":
                    Properties.Settings.Default.MidBoxCapacity = nup.Value;
                    Properties.Settings.Default.Save();
                    break;
                case "OutboxCapacity":
                    Properties.Settings.Default.OutboxCapacity = nup.Value;
                    Properties.Settings.Default.Save();
                    break;
                default:
                    break;
            }
        }

        private void CleanBarCode_Click(object sender, EventArgs e)
        {
            string close = MessageBox.Show(this.ParentForm, "是否清除该出货单条码", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
            if (close.ToString() == "Yes")
            {
                sdh.ExecuteSql("delete from prodiobarcode where pib_inoutno='" + pi_inoutno.Text + "'", "delete");
                dh.ExecuteSql("delete from prodiobarcode where pib_inoutno='" + pi_inoutno.Text + "'", "delete");
                LoadGridData(sender, e);
            }
        }

        private void LabelPrinter_UserOnSelectIndexChange(object sender, EventArgs e)
        {
            switch ((sender as Control).Parent.Name)
            {
                case "SingleLabelPrinter":
                    if (PrintMethod == "CodeSoft")
                    {
                        if (SingleDoc != null)
                            SingleDoc.Printer.SwitchTo(SingleLabelPrinter.Text);
                    }
                    else
                    {
                        if (SingleFormat != null)
                            SingleFormat.PrintSetup.PrinterName = SingleLabelPrinter.Text;
                    }
                    Properties.Settings.Default.SinglePrinter = SingleLabelPrinter.Text;
                    break;
                case "MidLabelPrinter":
                    if (PrintMethod == "CodeSoft")
                    {
                        if (MidDoc != null)
                            MidDoc.Printer.SwitchTo(MidLabelPrinter.Text);
                    }
                    else
                    {
                        if (MidFormat != null)
                            MidFormat.PrintSetup.PrinterName = MidLabelPrinter.Text;
                    }
                    Properties.Settings.Default.MidPrinter = MidLabelPrinter.Text;
                    break;
                case "OutBoxPrinter":
                    if (PrintMethod == "CodeSoft")
                    {
                        if (OutBoxDoc != null)
                            OutBoxDoc.Printer.SwitchTo(OutBoxPrinter.Text);
                    }
                    else
                    {
                        if (OutFormat != null)
                            OutFormat.PrintSetup.PrinterName = OutBoxPrinter.Text;
                    }
                    Properties.Settings.Default.OutPrinter = OutBoxPrinter.Text;
                    break;
                default:
                    break;
            }
            Properties.Settings.Default.Save();
        }

        private void DocRefresh_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            switch ((sender as Control).Name)
            {
                case "SingleDocRefresh":
                    if (SingleDoc != null)
                        SingleDoc.Close();
                    if (SingleLabelCombox.Text != "" && SingleLabelCombox.SelectedValue != null && !GetGridOnly.Checked)
                    {
                        System.DateTime time = Convert.ToDateTime(SingleLabelCombox.SelectedValue.ToString().Split('#')[2]);
                        SingleDoc = lbl.Documents.Open(BaseUtil.GetLabelUrl(SingleLabelCombox.SelectedValue.ToString().Split('#')[1], SingleLabelCombox.Text, time));
                    }
                    break;
                case "MidDocRefresh":
                    if (MidDoc != null)
                        MidDoc.Close();
                    if (MidLabelCombox.Text != "" && MidLabelCombox.SelectedValue != null && !GetGridOnly.Checked)
                    {
                        System.DateTime time = Convert.ToDateTime(MidLabelCombox.SelectedValue.ToString().Split('#')[2]);
                        MidDoc = lbl.Documents.Open(BaseUtil.GetLabelUrl(MidLabelCombox.SelectedValue.ToString().Split('#')[1], MidLabelCombox.Text, time));
                    }
                    break;
                case "OutDocRefresh":
                    if (OutBoxDoc != null)
                        OutBoxDoc.Close();
                    if (OutBoxCombox.Text != "" && OutBoxCombox.SelectedValue != null && !GetGridOnly.Checked)
                    {
                        System.DateTime time = Convert.ToDateTime(OutBoxCombox.SelectedValue.ToString().Split('#')[2]);
                        OutBoxDoc = lbl.Documents.Open(BaseUtil.GetLabelUrl(OutBoxCombox.SelectedValue.ToString().Split('#')[1], OutBoxCombox.Text, time));
                    }
                    break;
                default:
                    break;
            }
        }

        private void cu_code_UserControlTextChanged(object sender, EventArgs e)
        {
            if (!InitGetLabel)
                GetInOutInfAndLabelFile();
        }

        private void MenuSetting_Click(object sender, EventArgs e)
        {
            ShowMenu.Show(new Point(MenuSetting.Location.X, MenuSetting.Location.Y + 20));
        }

        private void Menu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            ShowMenu.Close();
            DataTable dt;
            DialogResult result;
            switch (e.ClickedItem.Text)
            {
                case "采集策略设置":
                    采集策略 form = new 采集策略(sg_code.Text);
                    form.FormClosed += sg_code_UserControlTextChanged;
                    BaseUtil.SetFormCenter(form);
                    form.ShowDialog();
                    break;
                case "附加信息设置":
                    if (cu_code.Text != "")
                    {
                        附件内容打印 att = new 附件内容打印(cu_code.Text);
                        att.FormClosed += Att_FormClosed;
                        att.ShowDialog();
                    }
                    else MessageBox.Show("请先获取出库单信息");
                    break;
                case "标签维护":
                    客户标签维护 form1 = new 客户标签维护();
                    BaseUtil.SetFormCenter(form1);
                    if (SingleDoc != null)
                        SingleDoc.Close();
                    if (MidDoc != null)
                        MidDoc.Close();
                    if (OutBoxDoc != null)
                        OutBoxDoc.Close();
                    //if (SingleFormat != null)
                    //    SingleFormat.Close(SaveOptions.DoNotSaveChanges);
                    //if (MidFormat != null)
                    //    MidFormat.Close(SaveOptions.DoNotSaveChanges);
                    //if (OutFormat != null)
                    //    OutFormat.Close(SaveOptions.DoNotSaveChanges);
                    form1.FormClosed += LabelFormClose;
                    form1.ShowDialog();
                    break;
                case "导出数据":
                    ExportExcel ex = new ExportExcel(pi_inoutno.Text);
                    ex.FormClosed += Ex_FormClosed;
                    switch (SystemInf.Master)
                    {
                        case "SZSI_TEST":
                            ex.StartPosition = FormStartPosition.CenterScreen;
                            ex.ShowDialog();
                            break;
                        case "SZSI_P":
                            ex.StartPosition = FormStartPosition.CenterScreen;
                            ex.ShowDialog();
                            break;
                        default:
                            ExportFileDialog.Description = "选择导出的路径";
                            result = ExportFileDialog.ShowDialog();
                            if (result == DialogResult.OK)
                            {
                                ExcelHandler eh = new ExcelHandler();
                                dt = ((DataTable)LabelInf.DataSource).Copy();
                                for (int i = dt.Columns.Count - 1; i >= 0; i--)
                                {
                                    for (int j = 0; j < LabelInf.Columns.Count; j++)
                                    {
                                        //去除ID列
                                        if (dt.Columns[i].ColumnName.ToLower().Contains("id") || dt.Columns[i].ColumnName.ToLower() == "pib_barcode" || dt.Columns[i].ColumnName.ToLower() == "pib_pdno" || dt.Columns[i].ColumnName.ToLower() == "pib_ifpick" || dt.Columns[i].ColumnName.ToLower() == "pib_ifprint" || dt.Columns[i].ColumnName.ToLower() == "pib_datecode1" || dt.Columns[i].ColumnName.ToLower() == "pr_vendprodcode")
                                        {
                                            dt.Columns.RemoveAt(i);
                                            break;
                                        }
                                        switch (dt.Columns[i].ColumnName.ToLower())
                                        {
                                            case "pib_lotno":
                                                dt.Columns[i].ColumnName = "批次号";
                                                break;
                                            case "pib_datecode":
                                                dt.Columns[i].ColumnName = "生产日期";
                                                break;
                                            case "pib_custbarcode":
                                                dt.Columns[i].ColumnName = "最小产品包装条码";
                                                break;
                                            default:
                                                break;
                                        }
                                        if (dt.Columns[i].ColumnName.ToLower() == LabelInf.Columns[j].DataPropertyName.ToLower())
                                        {
                                            dt.Columns[i].ColumnName = LabelInf.Columns[j].HeaderText;
                                            break;
                                        }
                                    }
                                }
                                eh.ExportExcel(dt, ExportFileDialog.SelectedPath, pi_date.Text + "-" + pi_inoutno.Text);
                                string close = MessageBox.Show(this.ParentForm, "导出成功,是否打开文件", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
                                if (close.ToString() == "Yes")
                                    System.Diagnostics.Process.Start(ExportFileDialog.SelectedPath + "\\" + pi_date.Text + "-" + pi_inoutno.Text + ".xls");
                            }
                            break;
                    }
                    break;
                case "权限设置":
                    PowerSetting pw = new PowerSetting();
                    BaseUtil.SetFormCenter(pw);
                    pw.ShowDialog();
                    break;
                case "条码导入生成":
                    ImportExcel.Filter = "(*.xls)|*.xlsx;*.xls";
                    result = ImportExcel.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        thread = new Thread(ImportBarcode);
                        stw = new SetLoadingWindow(thread, "正在生成条码");
                        BaseUtil.SetFormCenter(stw);
                        stw.ShowDialog();
                    }
                    break;
                case "下载模板":
                    ExportFileDialog.Description = "选择导出的路径";
                    result = ExportFileDialog.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        File.Copy(System.Windows.Forms.Application.StartupPath + "\\导入模板.xls", ExportFileDialog.SelectedPath + "\\导入模板.xls", true);
                        System.Diagnostics.Process.Start(ExportFileDialog.SelectedPath + "\\导入模板.xls");
                    }
                    break;
                case "客户合并规则":
                    CustomerRule cust = new CustomerRule();
                    BaseUtil.SetFormCenter(cust);
                    cust.ShowDialog();
                    break;
                case "流水调整":
                    if (cu_code.Text != "")
                    {
                        ReSetMaxNum reset = new ReSetMaxNum(cu_code.Text, pi_inoutno.Text);
                        BaseUtil.SetFormCenter(reset);
                        reset.ShowDialog();
                    }
                    else
                    {
                        MessageBox.Show("请先输入出货单号");
                    }
                    break;
                default:
                    break;
            }
        }

        private void Ex_FormClosed(object sender, FormClosedEventArgs e)
        {
            LoadGridData(false);
        }

        private void Att_FormClosed(object sender, FormClosedEventArgs e)
        {
            Attach = (DataTable)dh.ExecuteSql("select lap_param lp_name,lap_value lp_sql from LabelAttachPARAMETER where lap_custcode='" + cu_code.Text + "'", "select");
        }

        //生成客户条码
        public string BarcodeMethod1(string Prefix, string Suffix, int Index, int Length, int radix)
        {
            string str = Prefix;
            //如果是流水则需要在前面加0
            string serialcode = BaseUtil.DToAny(custserialnum, radix);
            for (int j = serialcode.ToString().Length; j < Length; j++)
            {
                serialcode = "0" + serialcode;
            }
            str += serialcode;
            str += Suffix;
            custserialnum = custserialnum + 1;
            return str;
        }

        //前缀
        public static string Prefix = "";
        //后缀
        public static string Suffix = "";
        //编码规则编号
        public static string NrCode = "";

        public static string PrefixFixed = "";
        //流水号的索引
        public static int SerialNumIndex = 0;
        //流水长度
        public static int SerialNumLength = 0;
        //存放键值对
        public static int Radix = 10;
        //客户的流水号
        public static int custserialnum = 0;

        public void GetCustRule()
        {
            //前缀
            Prefix = "";
            //后缀
            Suffix = "";
            //编码规则编号
            NrCode = "";

            PrefixFixed = "";
            //流水号的索引
            SerialNumIndex = 0;
            //流水长度
            SerialNumLength = 0;
            //存放键值对
            Radix = 10;
            DataTable Nr = (DataTable)dh.ExecuteSql("select nrd_detno,nrd_name,nrd_type,nrd_radix,nrd_sql,nrd_length,nr_code,nvl(nrd_iscombine,-1)nrd_iscombine from NoRuleDetail left join norule on nrd_nrid=nr_id where nr_custcode='" + cu_code.Text + "' order by nrd_detno", "select");
            //如果没有则取公共规则
            if (Nr.Rows.Count == 0)
                Nr = (DataTable)dh.ExecuteSql("select nrd_detno,nrd_name,nrd_radix,nrd_type,nrd_sql,nrd_length,nr_code,nvl(nrd_iscombine,-1)nrd_iscombine from NoRuleDetail left join norule on nrd_nrid=nr_id where nr_custcode is null and nr_isdefault <> 0 order by nrd_detno", "select");
            //用于过滤参数的正则表达式
            if (Nr.Rows.Count > 0)
            {
                NrCode = Nr.Rows[0]["nr_code"].ToString();
            }
            Regex match = new Regex("{\\w+}");
            //用于存放每一项的明细的数据
            string[] NrData = new string[Nr.Rows.Count];

            for (int m = 0; m < Nr.Rows.Count; m++)
            {
                switch (Nr.Rows[m]["nrd_type"].ToString())
                {
                    //常量直接进行拼接
                    case "常量":
                        NrData[m] = Nr.Rows[m]["nrd_sql"].ToString();
                        Prefix += NrData[m];
                        Suffix += NrData[m];
                        break;
                    case "SQL":
                        string SQL = Nr.Rows[m]["nrd_sql"].ToString();
                        DataTable Temp;
                        //如果不包含参数替换
                        if (SQL.IndexOf("{") == 0)
                        {
                            Temp = (DataTable)dh.ExecuteSql(SQL, "select");
                        }
                        else
                        {
                            //替换参数后重新执行SQL
                            foreach (Match mch in match.Matches(SQL))
                            {
                                SQL = SQL.Replace(mch.Value.Trim(), "'" + pi_inoutno.Text + "'");
                            }
                            Temp = (DataTable)dh.ExecuteSql(SQL, "select");
                        }
                        if (Temp.Rows.Count > 0)
                        {
                            NrData[m] = Temp.Rows[0][0].ToString();
                            Prefix += NrData[m];
                            Suffix += NrData[m];
                        }
                        else
                        {
                            NrData[m] = "";
                            Prefix += NrData[m];
                            Suffix += NrData[m];
                        }
                        break;
                    //流水需要通过MaxNumber去取
                    case "流水":
                        NrData[m] = dh.getFieldDataByCondition("RuleMaxNum", "rmn_maxnumber", "rmn_nrcode='" + NrCode + "'").ToString();
                        Suffix = "";
                        PrefixFixed = Prefix;
                        //设置当前流水
                        custserialnum = int.Parse(NrData[m] == "" ? "0" : NrData[m]);
                        SerialNumIndex = m;
                        SerialNumLength = int.Parse(Nr.Rows[m]["nrd_length"].ToString());
                        Radix = int.Parse(Nr.Rows[m]["nrd_radix"].ToString());
                        break;
                    default:
                        break;
                }
            }
            string maxnum = dh.getFieldDataByCondition("RuleMaxNum", "rmn_maxnumber", "rmn_nrcode='" + NrCode + "' and rmn_prefix='" + Prefix + "'").ToString();
            if (maxnum == "")
            {

                dh.ExecuteSql("insert into RuleMaxNum(rmn_id,rmn_nrcode,rmn_prefix,rmn_maxnumber) values(RuleMaxNum_seq.nextval,'" + NrCode + "','" + Prefix + "','1')", "insert");
                maxnum = dh.getFieldDataByCondition("RuleMaxNum", "rmn_maxnumber", "rmn_nrcode='" + NrCode + "' and rmn_prefix='" + Prefix + "'").ToString();
                if (maxnum == "")
                {
                    maxnum = "0";
                }
                custserialnum = int.Parse(maxnum);
            }//如果流水号不为空则取当前流水
            else
            {
                custserialnum = int.Parse(maxnum);
            }
        }

        public void ImportBarcode()
        {
            try
            {
                GetCustRule();
                LogicHandler.ImportExcel(SystemInf.Master, ImportExcel.FileName, PI_ID, pi_inoutno.Text, cu_code.Text);
                LoadGridData(false);
            }
            catch (Exception ex)
            {
                LogManager.DoLog(ex.StackTrace);
                MessageBox.Show(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }

        int rowindex = 0;

        private void LabelInf_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                rowindex = e.RowIndex;
                DateCodeSetAndPrint date = new DateCodeSetAndPrint();
                date.Controls["SetValue"].Click += SetValue_ButtonClick;
                //date.Controls["SetValueAndPrint"].Click += SetValueAndPrint_ButtonClick;
                date.ShowDialog();
            }
        }

        private void SetValue_ButtonClick(object sender, EventArgs e)
        {
            Button setvalue = sender as Button;
            string pdno = LabelInf.Rows[rowindex].Cells["pib_pdno"].Value.ToString();
            string pr_brand = LabelInf.Rows[rowindex].Cells["pib_brand"].Value.ToString();

            string datecode = setvalue.FindForm().Controls["datecode"].Text;
            string lotno = setvalue.FindForm().Controls["lotno"].Text;
            string BeginRow = setvalue.FindForm().Controls["Begin"].Text;
            string EndRow = setvalue.FindForm().Controls["End"].Text;
            //string year = "0";
            //string month = "0";
            //string day = "0";
            //string date = "";
            //string sql = "update prodiobarcode set pib_autoset=-1,pib_ifrecheck=-1,pib_ifpick=-1,pib_ifmodify=-1,pib_lotno='" + lotno + "',pib_datecode='" + datecode + "',pib_year='" + year + "',pib_month='" + month + "',pib_day='" + day + "' where pib_id in (select pib_id from prodiobarcode where  pib_inoutno='" + pi_inoutno.Text + "'";
            //if (datecode != "")
            //{
            //    //LogicHandler.GetTimeFromDatecode(datecode, pr_brand, out year, out month, out day, out date);
            //    sql += "  and (pib_datecode='' or pib_datecode is null) ";
            //}
            //if (lotno != "")
            //{
            //    sql += " and (pib_lotno='' or pib_lotno is null) ";
            //}
            List<string> pib_id = new List<string>();
            if (BeginRow != "" || EndRow != "")
            {
                try
                {
                    int begin = int.Parse(BeginRow == "" ? "1" : BeginRow);
                    int end = int.Parse(EndRow == "" ? LabelInf.Rows.Count.ToString() : EndRow);
                    if (begin > 0 && end <= LabelInf.Rows.Count && begin <= end)
                    {
                        for (int i = begin - 1; i < end; i++)
                        {
                            pib_id.Add(LabelInf.Rows[i].Cells["pib_id1"].Value.ToString());
                        }
                    }
                    else
                    {
                        MessageBox.Show("范围设置错误");
                        return;
                    }
                    LabelInf.Invalidate();
                }
                catch (Exception)
                {
                    MessageBox.Show("范围设置错误");
                    return;
                }
            }
            dh.BatchInsert("update prodiobarcode set pib_lotno='" + lotno + "',pib_datecode='" + datecode + "' where pib_id=:pib_id", new string[] { "pib_id" }, pib_id.ToArray());
            //同步数据到本地
            sdh.ExecuteSql("delete from prodiobarcode where pib_inoutno='" + pi_inoutno.Text + "'", "delete");
            LoadGridData(false);
            setvalue.FindForm().Close();
        }

        private void SetValueAndPrint_ButtonClick(object sender, EventArgs e)
        {
            Button setvalueandprint = sender as Button;
            string pdno = LabelInf.Rows[rowindex].Cells["pib_pdno"].Value.ToString();
            string pr_brand = LabelInf.Rows[rowindex].Cells["pib_brand"].Value.ToString();
            string datecode = setvalueandprint.FindForm().Controls["datecode"].Text;
            string lotno = setvalueandprint.FindForm().Controls["lotno"].Text;
            string nums = setvalueandprint.FindForm().Controls["Nums"].Text;
            string year = "0";
            string month = "0";
            string day = "0";
            //string date = "";
            string sql = "update prodiobarcode set pib_autoset=-1,pib_ifrecheck=-1,pib_ifpick=-1,pib_ifmodify=-1,pib_ifprint=-1,pib_lotno='" + lotno + "',pib_datecode='" + datecode + "',pib_year='" + year + "',pib_month='" + month + "',pib_day='" + day + "' where pib_id in (select pib_id from prodiobarcode where  pib_inoutno='" + pi_inoutno.Text + "'";
            string PrintSQL = "select pib_id from prodiobarcode where pib_inoutno='" + pi_inoutno.Text + "' and pib_pdno=" + pdno;
            if (datecode != "")
            {
                //LogicHandler.GetTimeFromDatecode(datecode, pr_brand, out year, out month, out day, out date);
                sql += " and (pib_datecode='' or pib_datecode is null) ";
                PrintSQL += " and (pib_datecode='' or pib_datecode is null) ";
            }
            if (lotno != "")
            {
                sql += " and (pib_lotno='' or pib_lotno is null) ";
                PrintSQL += " and (pib_lotno='' or pib_lotno is null) ";
            }
            if (nums == "")
            {
                sql += ")";
            }
            else
            {
                sql += " limit 0," + nums + ")";
                PrintSQL += " limit 0," + nums;
            }
            DataTable pibid_dt = (DataTable)sdh.ExecuteSql(PrintSQL, "select");
            sdh.ExecuteSql(sql, "update");
            for (int i = 0; i < pibid_dt.Rows.Count; i++)
            {
                if (PrintMethod == "CodeSoft")
                    Print.CodeSoft.SinglePrint(SingleDoc, SingleLabelParam, pibid_dt.Rows[i]["pib_id"].ToString());
                else
                    Print.BarTender.SinglePrint(SingleFormat, SingleLabelParam, pibid_dt.Rows[i]["pib_id"].ToString());
            }
            setvalueandprint.FindForm().Close();
        }

        /// <summary>
        /// 特殊业务逻辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CustBarCode_Click(object sender, EventArgs e)
        {
            string SQL = "";
            LogicHandler.CustBarCode(pi_inoutno.Text, out SQL);
            sdh.ExecuteSql(SQL, "update");
            LoadGridData(false);
        }

        private void GetMidBoxCode_Click(object sender, EventArgs e)
        {
            int BoxCode = 1;
            int innerboxcount = 1;
            for (int i = 0; i < LabelInf.Rows.Count; i++)
            {
                string midcapa = LabelInf.Rows[i].Cells["pr_midboxcapacity_user"].Value.ToString();
                if (!(midcapa == "" || midcapa == "0"))
                {
                    //如果出现值为空或者0默认界面上填写的值
                    MidBoxCapacity.Value = decimal.Parse((midcapa == "" || midcapa == "0") ? MidBoxCapacity.Value.ToString() : midcapa);
                    LabelInf.Rows[i].Cells["pib_outboxcode1"].Value = BoxCode;
                    if (i + 1 < LabelInf.Rows.Count)
                    {
                        if (innerboxcount == MidBoxCapacity.Value)
                        {
                            BoxCode = BoxCode + 1;
                            innerboxcount = 1;
                        }
                        else if (LabelInf.Rows[i].Cells["pib_prodcode"].Value.ToString() != LabelInf.Rows[i + 1].Cells["pib_prodcode"].Value.ToString() || LabelInf.Rows[i].Cells["pib_outboxcode2"].Value.ToString() != LabelInf.Rows[i + 1].Cells["pib_outboxcode2"].Value.ToString())
                        {
                            BoxCode = BoxCode + 1;
                            innerboxcount = 1;
                        }
                        else
                        {
                            innerboxcount = innerboxcount + 1;
                        }
                    }
                }
            }
            sdh.BatchInsert("prodiobarcode", LabelInf.DataSource as DataTable);
            DataTable dt1 = (DataTable)sdh.ExecuteSql("select pib_id,pib_outboxcode1,pib_outboxcode2,pib_custmidboxcode,pib_custoutboxcode,pib_lotno,pib_datecode,pib_ifupload,pib_ifpick,pib_ifprint from prodiobarcode where pib_inoutno='" + pi_inoutno.Text + "' ", "select");
            if (dt1.Rows.Count > 0)
            {
                dh.CallProcedure("sp_uploadbarcode", dt1);
            }
        }

        private void MidLabelPreView_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            MidFormat = engine.Documents.Open(ftpOperater.DownLoadTo + MidLabelCombox.Text);
            Resolution re = new Resolution(ImageResolution.Printer);
            if (File.Exists(@"C:\打印标签\" + MidLabelCombox.Text + ".jpg"))
            {
                File.Delete(@"C:\打印标签\" + MidLabelCombox.Text + ".jpg");
            }
            MidFormat.ExportImageToFile(@"C:\打印标签\" + MidLabelCombox.Text + ".jpg", ImageType.JPEG, Seagull.BarTender.Print.ColorDepth.Mono, re, OverwriteOptions.DoNotOverwrite);
            PreViewWindow pre = new PreViewWindow(MidLabelCombox.Text);
            pre.StartPosition = FormStartPosition.CenterScreen;
            pre.ShowDialog();
        }

        private void FTPModel_CheckedChanged(object sender, EventArgs e)
        {
            if (FTPModel.Checked)
            {
                if (!dh.CheckExist("configs", "caller='FTPModel' and code='PassOrNeg'"))
                {
                    dh.ExecuteSql("insert into configs(id,caller,code,data)values(configs_seq.nextval,'FTPModel','PassOrNeg','Y')", "insert");
                }
                else
                {
                    dh.ExecuteSql("update configs set data='Y' where caller='FTPModel' and code ='PassOrNeg'", "insert");
                }
                SystemInf.FTPModel = true;
            }
            else
            {
                dh.ExecuteSql("update configs set data='N' where caller='FTPModel' and code ='PassOrNeg'", "insert");
                SystemInf.FTPModel = false;
            }
        }
    }
}