using LabelManager2;
using System;
using System.Data;
using System.Text;
using System.Windows.Forms;
using UAS_MES.DataOperate;
using UAS_MES.Entity;
using UAS_MES.PublicMethod;
using System.Drawing;
using System.Threading;
using UAS_MES.PublicForm;
using System.IO.Ports;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;

namespace UAS_MES.Make
{
    public partial class Make_SpecialCartonPack : Form
    {
        DataHelper dh;
        DataTable dt;
        LogStringBuilder sql = new LogStringBuilder();
        AutoSizeFormClass asc = new AutoSizeFormClass();
        ApplicationClass lbl;
        Thread thread;
        string ErrorMessage = "";
        string oMakeCode = "";
        string oMsID = "";
        string ActWeigh;
        string oMsStatus = "";

        Regex re = new Regex("\\d+.\\d+\\w+");

        //称量的标准重量
        double Weight;
        //最大重量
        double MaxWeight;
        //最小重量
        double MinWeight;

        decimal StandardQTY = 0;
        string LastSncode;
        string oOutBoxCode = "";

        //创建串口实例
        SerialPort serialPort1 = new SerialPort();

        //true的时候表示从串口读取数据
        bool GetData = true;

        public Make_SpecialCartonPack()
        {
            InitializeComponent();
        }

        //创建打印进程
        private void NewPrint()
        {
            try
            {
                lbl = new ApplicationClass();
                BaseUtil.WriteLbl();
            }
            catch (Exception)
            {
                OperateResult.AppendText("未正确安装CodeSoft软件\n", Color.Red);
            }
        }

        private void 包装采集_Load(object sender, EventArgs e)
        {
            ComList.Text = BaseUtil.GetCacheData("PortName").ToString();
            Baurate.Text = BaseUtil.GetCacheData("BaudRate").ToString();
            //设置DbFind的必须的数据
            PrintNum.Text = "1";
            asc.controllInitializeSize(this);
            thread = new Thread(NewPrint);
            SetLoadingWindow stw = new SetLoadingWindow(thread, "初始化打印程序");
            BaseUtil.SetFormCenter(stw);
            stw.ShowDialog();
            dh = SystemInf.dh;
            thread = new Thread(getSerialData);
            try
            {
                GetData = true;
                serialPort1.PortName = ComList.Text;
                serialPort1.BaudRate = int.Parse(Baurate.Text);
                serialPort1.Open();
                thread.Start();
            }
            catch (Exception mes)
            {
                if (Baurate.Text == "" || ComList.Text == "")
                    OperateResult.AppendText(">>请先在电子秤调试界面维护波特率和串口\n", Color.Red);
                else
                    OperateResult.AppendText(">>" + mes.Message + "\n", Color.Red);
            }
            StepCount.StepCode = User.CurrentStepCode;
            StepCount.Source = User.UserSourceCode;
            StepCount.LineCode = User.UserLineCode;
            StepCount.Dh = dh;
            StepCount.Start();
        }


        private void getSerialData()
        {
            if (serialPort1.IsOpen)
            {
                if (!SystemInf.OpenPort.Contains(serialPort1.PortName))
                {
                    SystemInf.OpenPort.Add(serialPort1.PortName);
                    try
                    {
                        while (GetData)
                        {
                            try
                            {
                                weight.Text = re.Match(serialPort1.ReadLine().Trim()).Groups[0].Value;
                                ActWeigh = weight.Text.Replace("kg", "").Trim();
                            }
                            catch (Exception)
                            {
                                GetData = false;
                            }
                        }
                    }
                    catch (IOException ex) { MessageBox.Show(ex.Message); }
                }
                else OperateResult.AppendText(">>端口已被占用,请关闭其他窗口\n", Color.Red);
            }
        }

        private void 包装采集_SizeChanged(object sender, EventArgs e)
        {
            asc.controlAutoSize(this);
        }

        private void 包装采集_Activated(object sender, EventArgs e)
        {
            pa_outboxcode.Focus();
        }

        //刷新表单的数据的数据
        private void LoadData()
        {
            //加载表单数据
            sql.Clear();
            sql.Append("select pa_prodcode,pr_cartonmaxw,pa_salecode,nvl(pr_sendchecktype,'LineCode')pr_sendchecktype,pa_makecode,pr_cartonunit,pr_code,pr_cartonminw,pr_cartongw,pa_outboxcode,pa_sccode,nvl(pa_downstatus,0) pa_downstatus,pa_checkno,");
            sql.Append("pa_status,pr_packrule,pr_detail,pa_packageqty,nvl(pa_standardqty,0)pa_standardqty,nvl(pr_outboxinnerqty,0)pr_outboxinnerqty,nvl(PR_CHECKCARTONW,'0') PR_CHECKCARTONW,pa_currentqty from package left join ");
            sql.Append("product on pa_prodcode=pr_code where pa_outboxcode='" + pa_outboxcode.Text + "'");
            DataTable dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
            if (dt.Rows.Count > 0)
            {
                //重量的临时变量
                string _weight = dt.Rows[0]["pr_cartongw"].ToString();
                string _maxweight = dt.Rows[0]["pr_cartonmaxw"].ToString();
                string _minweight = dt.Rows[0]["pr_cartonminw"].ToString();
                Weight = double.Parse(_weight == "" ? "0" : _weight);
                MaxWeight = double.Parse(_maxweight == "" ? "0" : _maxweight);
                MinWeight = double.Parse(_minweight == "" ? "0" : _minweight);
                //记录该数据保证在修改不被允许的前提下能偶回复之前的值
                StandardQTY = decimal.Parse(dt.Rows[0]["pr_outboxinnerqty"].ToString());
                BaseUtil.SetFormValue(this.Controls, dt);
                ms_salecode.Text = dt.Rows[0]["pa_salecode"].ToString();
                if (pa_standardqty.Text != "0")
                    pr_outboxinnerqty.Text = pa_standardqty.Text;
                if (Weight - MinWeight == MaxWeight - Weight)
                    pr_cartonboxgw.Text = Weight + "±" + (MaxWeight - Weight) + dt.Rows[0]["pr_cartonunit"].ToString();
                else
                    pr_cartonboxgw.Text = MinWeight + "-" + MaxWeight + dt.Rows[0]["pr_cartonunit"].ToString();
            }
            else sn_code.Focus();
            LoadCheckQTY();
        }

        private void LoadGridData()
        {
            //加载Grid数据
            dt = (DataTable)dh.ExecuteSql("select pa_outboxcode,pa_prodcode,pd_barcode,pd_innerqty,pa_indate from packageDetail left join package on pa_id=pd_paid where pa_outboxcode='" + pa_outboxcode.Text + "'", "select");
            BaseUtil.FillDgvWithDataTable(PackageDetail, dt);
        }

        private void Print_Click(object sender, EventArgs e)
        {
            if (PrintLabel.Items.Count != 0)
            {
                if (dh.getFieldDataByCondition("package", "pa_status", "pa_outboxcode='" + pa_outboxcode.Text + "'").ToString() == "1")
                {
                    dh.ExecuteSql("update package set pa_printcount=pa_printcount+1 where pa_outboxcode='" + pa_outboxcode.Text + "'", "update");
                    OperateResult.AppendText(">>开始打印箱号" + pa_outboxcode.Text + "\n", Color.Black);
                    //doc = lbl.Documents.Open(PrintLabel.Text);
                    if (!Print.CodeSoft(Tag.ToString(), ref lbl, PrintLabel.Text, PrintLabel.SelectedValue.ToString(), PrintList.Text, pa_outboxcode.Text, int.Parse(PrintNum.Text), ms_makecode.Text, pr_code.Text, "卡通箱标", "0", out ErrorMessage))
                    {
                        OperateResult.AppendText(ErrorMessage + "\n", Color.Red);
                    }
                    pa_outboxcode.Focus();
                    pa_outboxcode.SelectAll();
                }
                else OperateResult.AppendText(">>箱号" + pa_outboxcode.Text + "尚未封箱,请封箱后执行打印\n", Color.Red);
            }
            else OperateResult.AppendText(">>产品" + pr_code.Text + "未维护打印标签\n", Color.Red);
        }

        //加载工单信息和装箱明细信息
        private void pa_code_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                LoadData();
                LoadGridData();
            }
        }

        //输入序列号的回车事件
        private void barcode_KeyDown(object sender, KeyEventArgs e)
        {
            //当用户输入回车键的时候
            if (e.KeyCode == Keys.Enter)
            {
                if (LogicHandler.CheckStepAttribute(Tag.ToString(), User.UserSourceCode, out ErrorMessage))
                {
                    dt = (DataTable)dh.ExecuteSql("select ms_id,ms_status,ms_makecode from makeserial where ms_sncode ='" + sn_code.Text + "' and ms_status=2 order by ms_id desc", "select");
                    if (LogicHandler.CheckStepSNAndMacode("", User.UserSourceCode, sn_code.Text, User.UserCode, out oMakeCode, out oMsID, out ErrorMessage) || dt.Rows.Count > 0)
                    {
                        if (oMsID == "" || oMsID == "null" || oMsID == "0")
                        {
                            oMsID = dt.Rows[0]["ms_id"].ToString();
                            oMsStatus = dt.Rows[0]["ms_status"].ToString();
                            oMakeCode = dt.Rows[0]["ms_makecode"].ToString();
                        }

                        //获取序列号信息
                        sql.Clear();
                        sql.Append("select nvl(ms_iostatus,0) ms_iostatus,pa_salecode,ms_salecode,ms_outno,ms_makecode,ms_prodcode,nvl(pa_downstatus,0) pa_downstatus,pa_sccode,pa_checkno,pr_packrule,");
                        sql.Append("nvl(pr_outboxinnerqty,0)pr_outboxinnerqty,nvl(pr_sendchecktype,'LineCode')pr_sendchecktype from makeserial left join product on ms_prodcode=pr_code left join packagedetail ");
                        sql.Append("on pd_barcode=ms_sncode left join package on pa_id =pd_paid where ms_id='" + oMsID + "'");
                        dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
                        string ms_makecode = "";
                        string ms_prodcode = "";
                        string ms_iostatus = "";
                        string ms_outno = "";
                        string ms_salecode_text = "";
                        if (dt.Rows.Count > 0)
                        {
                            StandardQTY = decimal.Parse(dt.Rows[0]["pr_outboxinnerqty"].ToString());
                            ms_makecode = dt.Rows[0]["ms_makecode"].ToString();
                            ms_prodcode = dt.Rows[0]["ms_prodcode"].ToString();
                            ms_iostatus = dt.Rows[0]["ms_iostatus"].ToString();
                            ms_outno = dt.Rows[0]["ms_outno"].ToString();
                            ms_salecode_text = dt.Rows[0]["ms_salecode"].ToString();
                            BaseUtil.SetFormValue(this.Controls, dt);
                        }
                        //保证箱内容量不会被重置
                        if (pa_standardqty.Text != "0" && pa_standardqty.Text != "")
                        {
                            pr_outboxinnerqty.Text = pa_standardqty.Text;
                        }
                        if (pa_outboxcode.Text == "")
                        {
                            string boxcode = dh.getFieldDataByCondition("makeserial", "ms_outboxcode", "ms_id='" + oMsID + "'").ToString();
                            //序列号存在箱号的情况下获取所有的装箱数据
                            if (boxcode != "")
                            {
                                pa_outboxcode.Text = boxcode;
                                pa_makecode.Text = "";
                                LoadGridData();
                            }
                            else
                            {
                                //如果勾选了自动生成箱号,在封箱或者首次
                                if (AutoGenBoxCode.Checked && (pa_status.Text == "1" || pa_status.Text == "" || pa_status.Text == "0"))
                                    pa_outboxcode.Text = LogicHandler.GetOutBoxCode("PACKAGE", ms_makecode, pr_code.Text, User.UserCode);
                            }
                        }
                        if (pa_outboxcode.Text == "")
                        {
                            OperateResult.AppendText(">>箱号不能为空\n", Color.Red, sn_code);
                            return;
                        }
                        //判断箱内总数必须大于0
                        if (pr_outboxinnerqty.Text == "" || pr_outboxinnerqty.Text == "0")
                        {
                            OperateResult.AppendText(">>箱内容量必须大于0\n", Color.Red);
                            return;
                        }
                        string MotherBoxCode = dh.getFieldDataByCondition("package", "pa_mothercode", "pa_outboxcode='" + pa_outboxcode.Text + "'").ToString(); ;
                        //如果未勾选了取消录入
                        if (!Cancel.Checked)
                        {
                            //判断序列号是否已经装箱
                            string ms_outboxcode = dh.getFieldDataByCondition("makeserial", "ms_outboxcode", "ms_id='" + oMsID + "'").ToString();
                            if (ms_outboxcode != "")
                            {
                                if (ms_outboxcode == pa_outboxcode.Text)
                                    OperateResult.AppendText(">>序列号" + sn_code.Text + "已在本箱内\n", Color.Red, sn_code);
                                else
                                    OperateResult.AppendText(">>序列号" + sn_code.Text + "已采集至箱" + ms_outboxcode + "\n", Color.Red, sn_code);
                                LoadData();
                            }
                            else
                            {
                                //满箱之后采集下一个之前自动清除内容,生成新的箱号
                                if ((AutoGenBoxCode.Checked && pa_currentqty.Text != "" && pr_outboxinnerqty.Text == pa_currentqty.Text) || (AutoGenBoxCode.Checked && pa_status.Text == "1"))
                                {
                                    pa_currentqty.Text = "";
                                    pa_outboxcode.Text = "";
                                    pa_status.Text = "0";
                                    BaseUtil.CleanDGVData(PackageDetail);
                                    pa_outboxcode.Text = LogicHandler.GetOutBoxCode("PACKAGE", ms_makecode, pr_code.Text, User.UserCode);
                                }
                                if (LogicHandler.Packing(sn_code.Text, pa_outboxcode.Text, AutoGenBoxCode.Checked, "特殊", User.UserSourceCode, User.UserCode, pr_outboxinnerqty.Text, Cancel.Checked, out oOutBoxCode, out ErrorMessage))
                                {
                                    DataTable dt = (DataTable)dh.ExecuteSql("select pd_barcode from packagedetail where pd_outboxcode = '" + pa_outboxcode.Text + "'", "select");
                                    if (dt.Rows.Count > 0 && dt.Rows.Count == 1)
                                    {
                                        dh.UpdateByCondition("package", "pa_makecode = '" + ms_makecode + "',pa_prodcode = '" + ms_prodcode + "',pa_salecode = '" + ms_salecode.Text + "'", "pa_outboxcode = '" + pa_outboxcode.Text + "'");
                                    }
                                    if (ErrorMessage.Contains("AFTERSUCCESS"))
                                        OperateResult.AppendText(">>" + ErrorMessage + "\n");
                                    LoadCheckQTY();
                                    OperateResult.AppendText(">>序列号" + sn_code.Text + "采集成功!\n", Color.Green);
                                    LastSncode = sn_code.Text;
                                    if (MotherBoxCode != "")
                                    {
                                        dh.ExecuteSql("update package set PA_TOTALQTY=(select sum(pd_innerqty) from packagedetail left join package on pa_id=pd_paid where pa_outboxcode='" + MotherBoxCode + "') where pa_outboxcode='" + MotherBoxCode + "' and pa_type=3", "update");
                                    }
                                    LoadData();
                                    LoadGridData();
                                    //满箱更新状态为1
                                    if (int.Parse(pa_currentqty.Text == "" ? "0" : pa_currentqty.Text) == int.Parse(pr_outboxinnerqty.Text))
                                    {
                                        ActWeigh = weight.Text == "" ? "0" : weight.Text.Replace("kg", "").Trim();
                                        float weigh = float.Parse(ActWeigh);
                                        dh.UpdateByCondition("package", "pa_status=1,pa_packageqty=pa_currentqty,pa_weight='" + weigh + "'", "pa_outboxcode='" + pa_outboxcode.Text + "'");
                                        pa_standardqty.Text = "";
                                        pa_status.Text = "1";
                                        OperateResult.AppendText(">>箱号" + pa_outboxcode.Text + "满箱封箱成功\n", Color.Green);
                                        LogicHandler.RecordProdWeight(pa_outboxcode.Text, "CARTON", float.Parse(ActWeigh.ToString()), "kg", User.UserLineCode, pr_code.Text, User.UserSourceCode, User.UserName);
                                        LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, pa_makecode.Text, User.UserLineCode, User.UserSourceCode, "卡通箱称重", "称量完成:" + weight.Text.Trim(), pa_outboxcode.Text, "");
                                        if (LogicHandler.CartonBoxStepPass(pa_makecode.Text, User.UserSourceCode, pa_outboxcode.Text, User.UserCode, "卡通箱:" + pa_outboxcode.Text + "整箱过站", out ErrorMessage))
                                        {
                                            dh.UpdateByCondition("package", "pa_nextstep='" + dh.getFieldDataByCondition("packagedetail left join makeserial on ms_sncode=pd_barcode and ms_makecode=pd_makecode", "max(ms_nextstepcode)", "pd_outboxcode='" + pa_outboxcode.Text + "'").ToString() + "', PA_CURRENTSTEP = '' ", "pa_outboxcode='" + pa_outboxcode.Text + "'");
                                        }
                                        else
                                        {
                                            OperateResult.AppendText(">>" + ErrorMessage + "\n", Color.Red);
                                        }
                                        if (AutoPrint.Checked)
                                            Print_Click(new object(), new EventArgs());
                                    }
                                    LoadCheckQTY();
                                    sn_code.Clear();
                                }
                                else OperateResult.AppendText(">>" + ErrorMessage + "\n", Color.Red);
                            }
                        }
                        //勾选了取消箱号先验证箱号存不存在,存在的话移除掉,重新加载一次数据
                        else
                        {
                            if (LogicHandler.Packing(sn_code.Text, pa_outboxcode.Text, AutoGenBoxCode.Checked, "特殊", User.UserSourceCode, User.UserCode, pr_outboxinnerqty.Text, Cancel.Checked, out oOutBoxCode, out ErrorMessage))
                            {
                                dh.ExecuteSql("update packagedetail set pd_innerqty=(select pa_packageqty from package where pa_outboxcode='" + pa_outboxcode.Text + "') where pd_innerboxcode='" + pa_outboxcode.Text + "'", "update");
                                //如果母箱号不为空,需要更新总数
                                if (MotherBoxCode != "")
                                {
                                    dh.ExecuteSql("update package set PA_TOTALQTY=(select sum(pd_innerqty) from packagedetail left join package on pa_id=pd_paid where pa_outboxcode='" + MotherBoxCode + "') where pa_outboxcode='" + MotherBoxCode + "' and pa_type=3", "update");
                                }
                                LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, oMakeCode, User.UserLineCode, User.UserSourceCode, "装箱采集", "取消采集成功", sn_code.Text, "");
                                LoadData();
                                LoadGridData();
                                pa_status.Text = "0";
                                OperateResult.AppendText(">>已从该箱中移除序列号" + sn_code.Text + "\n", Color.Green, sn_code);
                            }
                            else OperateResult.AppendText(">>" + ErrorMessage + "\n", Color.Red, sn_code);
                        }
                    }
                    else OperateResult.AppendText(">>" + ErrorMessage + "\n", Color.Red, sn_code);
                }
                else OperateResult.AppendText(">>" + ErrorMessage + "\n", Color.Red, sn_code);
            }
        }

        private void Clean_Click(object sender, EventArgs e)
        {
            OperateResult.Clear();
        }

        //private void pr_code_TextChanged(object sender, EventArgs e)
        //{

        //}

        private void 包装采集_FormClosing(object sender, FormClosingEventArgs e)
        {
            BaseUtil.ClosePrint(lbl);
            if (serialPort1.IsOpen)
            {
                GetData = false;
                serialPort1.Close();
                SystemInf.OpenPort.Remove(serialPort1.PortName);
                thread.Interrupt();
            }
            //thread.Abort();
        }

        private void Packing_Click(object sender, EventArgs e)
        {
            if (dh.CheckExist("package", "pa_outboxcode='" + pa_outboxcode.Text + "' and nvl(pa_status,0)=0"))
            {
                string Seal = MessageBox.Show(this.ParentForm, "是否确认封箱?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
                if (Seal == "Yes")
                {
                    ActWeigh = weight.Text == "" ? "0" : weight.Text.Replace("kg", "").Trim();
                    float weigh = float.Parse(ActWeigh);
                    OperateResult.AppendText(">>箱号" + pa_outboxcode.Text + "采集完成,手动封箱成功\n", Color.Green);
                    dh.UpdateByCondition("package", "pa_status=1,pa_totalqty=pa_currentqty,pa_packageqty=pa_currentqty,pa_weight=" + weigh + "", "pa_outboxcode='" + pa_outboxcode.Text + "'");
                    pa_status.Text = "1";
                    pa_standardqty.Text = "";
                    LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, pa_makecode.Text, User.UserLineCode, User.UserSourceCode, "装箱采集", "封箱成功", pa_outboxcode.Text, "");
                    if (LogicHandler.CartonBoxStepPass(pa_makecode.Text, User.UserSourceCode, pa_outboxcode.Text, User.UserCode, "卡通箱:" + pa_outboxcode.Text + "整箱过站", out ErrorMessage))
                    {
                        dh.UpdateByCondition("package", "pa_nextstep='" + dh.getFieldDataByCondition("packagedetail left join makeserial on ms_sncode=pd_barcode and ms_makecode=pd_makecode", "max(ms_nextstepcode)", "pd_outboxcode='" + pa_outboxcode.Text + "'").ToString() + "', PA_CURRENTSTEP = '' ", "pa_outboxcode='" + pa_outboxcode.Text + "'");
                    }
                    else
                    {
                        OperateResult.AppendText(">>" + ErrorMessage + "\n", Color.Red);
                    }
                    LoadCheckQTY();
                    pa_outboxcode.SelectAll();
                    pa_outboxcode.Focus();
                }
            }
            else OperateResult.AppendText(">>箱号" + pa_outboxcode.Text + "错误或者已封箱\n", Color.Red);
        }

        private void SendCheck_Click(object sender, EventArgs e)
        {
            if (dh.getFieldDataByCondition("package", "pa_status", "pa_outboxcode='" + pa_outboxcode.Text + "'").ToString() == "1")
            {
                DataTable dt = (DataTable)dh.ExecuteSql("select wm_concat(pa_outboxcode) pa_outboxcode from package where pa_checkno='" + ob_checkno.Text + "' and pa_status=0 ", "select");
                if (dt.Rows[0][0].ToString() != "")
                {
                    OperateResult.AppendText(">>批次" + ob_checkno.Text + "存在箱号" + dt.Rows[0][0].ToString() + "未封箱,请先进行封箱\n", Color.Red);
                    return;
                }
                sql.Clear();
                sql.Append("update oqcbatch set ob_status='UNCHECK',ob_breakingdate=sysdate where ob_checkno ='" + ob_checkno.Text + "'");
                dh.ExecuteSql(sql.GetString(), "select");
                ob_nowcheckqty.Text = "";
                ob_batchqty.Text = "";
                ob_nowcheckqty.ForeColor = Color.Black;
                SendCheck.Enabled = false;
                OperateResult.AppendText(">>批次" + ob_checkno.Text + "送检成功\n", Color.Green);
                LogicHandler.InsertMakeProcess(LastSncode, oMakeCode, User.UserSourceCode, "手动送检", "手动送检成功", User.UserCode);
                //记录操作日志
                LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, oMakeCode, User.UserLineCode, User.UserSourceCode, "手动送检", "手动送检成功", "", ob_checkno.Text);
                ob_checkno.Text = "";
            }
            else OperateResult.AppendText(">>必须封箱才能送检\n", Color.Red);


        }

        bool AutoCut;

        private void LoadCheckQTY()
        {
            sql.Clear();
            string condition = "";
            int nowcheckqty = int.Parse(ob_nowcheckqty.Text == "" ? "0" : ob_nowcheckqty.Text);
            int batchqty = int.Parse(ob_batchqty.Text == "" ? "0" : ob_batchqty.Text);
            if (nowcheckqty + 1 == batchqty && AutoCut)
            {
                condition = "and ob_status='UNCHECK' and ob_checkno='" + ob_checkno.Text + "'";
            }
            else
            {
                condition = "and ob_status='ENTERING' ";
            }
            if (pr_sendchecktype.Text == "SaleCode")
            {
                condition += " and ob_salecode='" + ms_salecode.Text + "'";
            }
            else if (pr_sendchecktype.Text == "MakeCode")
            {
                condition += " and ob_makecode='" + ms_makecode.Text + "'";
            }
            sql.Append("select ob_batchqty,ob_nowcheckqty,ob_checkno from oqcbatch where ");
            sql.Append("ob_linecode='" + User.UserLineCode + "' and ob_prodcode='" + pr_code.Text + "' and ");
            sql.Append("ob_stepcode='" + User.CurrentStepCode + "' " + condition);
            DataTable dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
            if (dt.Rows.Count > 0)
            {
                ob_batchqty.Text = dt.Rows[0]["ob_batchqty"].ToString();
                ob_nowcheckqty.Text = dt.Rows[0]["ob_nowcheckqty"].ToString();
                ob_checkno.Text = dt.Rows[0]["ob_checkno"].ToString();
                nowcheckqty = int.Parse(ob_nowcheckqty.Text == "" ? "0" : ob_nowcheckqty.Text);
                batchqty = int.Parse(ob_batchqty.Text == "" ? "0" : ob_batchqty.Text);
                if (nowcheckqty == batchqty)
                {
                    ob_nowcheckqty.ForeColor = Color.Red;
                    OperateResult.AppendText(">>当前采集数量已达到送检数量\n", Color.Red);
                    if (AutoCut)
                    {
                        OperateResult.AppendText(">>批次" + ob_checkno.Text + "自动断批\n", Color.Green);
                    }
                }
            }
            else
            {
                ob_batchqty.Text = "";
                ob_nowcheckqty.Text = "";
                ob_checkno.Text = "";
                SendCheck.Enabled = false;
            }
            if (ob_batchqty.Text != "")
            {
                SendCheck.Enabled = true;
            }
            else
            {
                SendCheck.Enabled = false;
            }
        }

        private void ob_checkno_TextChanged(object sender, EventArgs e)
        {
            if (ob_checkno.Text != "")
            {
                string Cut = dh.getFieldDataByCondition("product left join oqcbatch on ob_prodcode=pr_code", "pr_ifautocutcheckno", "ob_checkno='" + ob_checkno.Text + "'").ToString();
                if (Cut == "" || Cut == "0")
                    AutoCut = false;
                else
                    AutoCut = true;
                SendCheck.Enabled = true;
            }
        }

        //private void pr_outboxinnerqty_KeyDown(object sender, KeyEventArgs e)
        //{
        //    if (e.KeyCode == Keys.Enter)
        //        ResetPackQTY();
        //}

        //private void pr_outboxinnerqty_Leave(object sender, EventArgs e)
        //{
        //    ResetPackQTY();
        //}

        //private void ResetPackQTY()
        //{
        //    //数据不符合限制的时候保持原有值
        //    int curretnqty = int.Parse(pa_currentqty.Text == "" ? "0" : pa_currentqty.Text);
        //    if (!(pr_outboxinnerqty.Value >= curretnqty))
        //    {
        //        pr_outboxinnerqty.Value = StandardQTY;
        //    }
        //    else
        //    {
        //        if (dh.CheckExist("package", "pa_outboxcode='" + pa_outboxcode.Text + "'"))
        //        {
        //            string checknostatus = dh.getFieldDataByCondition("oqcbatch", "ob_status", "ob_checkno='" + pa_checkno.Text + "'").ToString();
        //            if (checknostatus == "" || checknostatus == "ENTERING")
        //            {
        //                if (pa_downstatus.Text == "0")
        //                {
        //                    if (dh.CheckExist("source", "sc_code='" + pa_sccode.Text + "' and  sc_stepcode='" + User.CurrentStepCode + "'"))
        //                    {
        //                        dh.UpdateByCondition("package", "pa_standardqty='" + pr_outboxinnerqty.Value + "'", "pa_outboxcode='" + pa_outboxcode.Text + "'");
        //                        LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, "", User.UserLineCode, User.UserSourceCode, "修改箱内容量", "原容量" + StandardQTY + ",修改为" + pr_outboxinnerqty.Value + "'", pa_outboxcode.Text, pa_checkno.Text);
        //                        return;
        //                    }
        //                    else
        //                        OperateResult.AppendText(">>箱号" + pa_outboxcode.Text + "当前所在工序不是登录岗位资源所在工序,不允许修改数量\n", Color.Red);
        //                }
        //                else
        //                    OperateResult.AppendText(">>箱号" + pa_outboxcode.Text + "处于下地状态,不允许修改标准容量\n", Color.Red);
        //            }
        //            else
        //                OperateResult.AppendText(">>箱号" + pa_outboxcode.Text + "处于送检中,不允许修改标准容量\n", Color.Red);
        //        }
        //        else
        //            OperateResult.AppendText(">>箱号" + pa_outboxcode.Text + "不存在,修改容量无效\n", Color.Red);
        //        pr_outboxinnerqty.Value = StandardQTY;
        //    }
        //}

        //private void PackageDetail_DataSourceChanged(object sender, EventArgs e)
        //{
        //    if (PackageDetail.RowCount == 1)
        //    {
        //        LoadCheckQTY();
        //        pr_code.Text = dh.getFieldDataByCondition("makeserial", "ms_prodcode", "ms_sncode='" + PackageDetail.Rows[0].Cells["pd_barcode"].Value.ToString() + "' order by ms_id desc").ToString();
        //        dt = (DataTable)dh.ExecuteSql("select la_id,substr(la_url,instr(la_url,'\\',-1)+1)la_name,la_url,la_isdefault from label where la_prodcode='" + pr_code.Text + "' and la_templatetype='卡通箱标' and la_statuscode='AUDITED' order by la_isdefault", "select");
        //        PrintLabel.DataSource = dt;
        //        PrintLabel.DisplayMember = "la_name";
        //        PrintLabel.ValueMember = "la_id";
        //        ftpOperater ftp = new ftpOperater();
        //        for (int i = 0; i < dt.Rows.Count; i++)
        //        {
        //            BaseUtil.GetPrintLabel(dt.Rows[i]["la_name"].ToString(), dt.Rows[i]["la_url"].ToString());
        //        }
        //    }
        //}

        private void PrintLabel_SelectedValueChanged(object sender, EventArgs e)
        {
            if (PrintLabel.SelectedValue != null && PrintLabel.SelectedValue.ToString() != "System.Data.DataRowView")
            {
                string PrintNums = dh.getFieldDataByCondition("label", "la_printnos", "la_id='" + PrintLabel.SelectedValue.ToString() + "'").ToString();
                PrintNum.Text = (PrintNums == "" ? "1" : PrintNums);
            }
        }

        private void DeleteAll_Click(object sender, EventArgs e)
        {
            if (pa_outboxcode.Text == "")
            {
                OperateResult.AppendText(">>箱号不能为空\n", Color.Red);
                return;
            }
            string Delete = MessageBox.Show(this.ParentForm, "是否确认拆箱?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
            if (Delete == "Yes")
            {
                DataTable dt = (DataTable)dh.ExecuteSql("select pa_checkno,ob_status,pa_mothercode,nvl(pa_downstatus,0)pa_downstatus from package left join oqcbatch on pa_checkno=ob_checkno where pa_outboxcode='" + pa_outboxcode.Text + "'", "select");
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["pa_mothercode"].ToString() == "")
                    {
                        if (dt.Rows[0]["pa_downstatus"].ToString() == "0")
                        {
                            string ob_status = dt.Rows[0]["ob_status"].ToString();
                            string pa_checkno = dt.Rows[0]["pa_checkno"].ToString();
                            //不存在抽检批次或者还未检验可以拆解
                            if (ob_status == "" || ob_status == "ENTERING" || ob_status == "UNCHECK")
                            {
                                sql.Clear();
                                sql.Append("select pd_makecode,pd_barcode,pd_prodcode,ms_status,ms_stepcode from packagedetail left join makeserial ");
                                sql.Append("on ms_sncode=pd_barcode and ms_makecode=pd_makecode where pd_outboxcode='" + pa_outboxcode.Text + "'");
                                dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
                                for (int i = 0; i < dt.Rows.Count; i++)
                                {
                                    string ma_code = dt.Rows[i]["pd_makecode"].ToString();
                                    string ms_sncode = dt.Rows[i]["pd_barcode"].ToString();
                                    string pr_code = dt.Rows[i]["pd_prodcode"].ToString();
                                    string ms_status = dt.Rows[i]["ms_status"].ToString();
                                    string ms_stepcode = dt.Rows[i]["ms_stepcode"].ToString();
                                    List<string> SQLS1 = new List<string>();
                                    if (ms_status == "2")
                                    {
                                        //已完工数-1
                                        SQLS1.Add("update make set ma_madeqty=ma_madeqty-1 where ma_code='" + ma_code + "'");
                                    }
                                    //更新序列号状态
                                    SQLS1.Add("update makecraftdetail set mcd_inqty=mcd_inqty-1,mcd_okqty=mcd_okqty-1 where mcd_macode='" + ma_code + "' and mcd_stepcode='" + ms_stepcode + "'");
                                    SQLS1.Add("update makeserial set ms_status=1,ms_nextstepcode=ms_stepcode,ms_outboxcode='' where ms_sncode='" + ms_sncode + "' and ms_makecode='" + ma_code + "'");
                                    SQLS1.Add("delete from makeprocess where mp_sncode='" + ms_sncode + "' and mp_makecode='" + ma_code + "' and mp_stepcode='" + ms_stepcode + "'");
                                    SQLS1.Add("delete from steppassed where sp_sncode='" + ms_sncode + "' and sp_makecode='" + ma_code + "' and sp_stepcode='" + ms_stepcode + "'");
                                    //抽检批次不为空的时候进行移除
                                    if (pa_checkno != "")
                                    {
                                        SQLS1.Add("update makeserial set ms_checkno='' where ms_sncode='" + ms_sncode + "' and ms_makecode='" + ma_code + "'");
                                        SQLS1.Add("update oqcbatch set ob_nowcheckqty=ob_nowcheckqty-1 where ob_checkno='" + pa_checkno + "'");
                                        SQLS1.Add("delete from oqcbatchdetail where obd_checkno='" + pa_checkno + "' and obd_sncode='" + ms_sncode + "'");
                                    }
                                    dh.ExecuteSQLTran(SQLS1.ToArray());
                                }
                                List<string> SQLS2 = new List<string>();
                                string prcode = dh.getFieldDataByCondition("packagedetail", "pd_prodcode", "pd_outboxcode = '" + pa_outboxcode.Text + "'").ToString();
                                string standqty = dh.getFieldDataByCondition("product", "pr_outboxinnerqty", "pr_code = '" + prcode + "'").ToString();
                                if (standqty != "")
                                {
                                    //置空原箱
                                    dh.ExecuteSql("update package set pa_checkno='',pa_prodcode='',pa_packtype='',pa_salecode='',pa_packageqty=0,pa_totalqty=0,pa_currentqty=0,pa_status=0,PA_STANDARDQTY = '" + standqty + "' where pa_outboxcode='" + pa_outboxcode.Text + "'", "update");
                                }
                                else
                                    //置空原箱
                                    dh.ExecuteSql("update package set pa_checkno='',pa_prodcode='',pa_packtype='',pa_salecode='',pa_packageqty=0,pa_totalqty=0,pa_currentqty=0,pa_status=0 where pa_outboxcode='" + pa_outboxcode.Text + "'", "update");
                                pa_status.Text = "0";
                                //删除箱的明细
                                SQLS2.Add("delete from packagedetail where pd_outboxcode='" + pa_outboxcode.Text + "'");
                                dh.ExecuteSQLTran(SQLS2.ToArray());
                                if (!LogicHandler.resetOutBoxStatus(pa_outboxcode.Text, out ErrorMessage))
                                {
                                    OperateResult.AppendText(">>拆箱接口回传:" + ErrorMessage + "!\n", Color.Red);
                                }
                                OperateResult.AppendText(">>箱号" + pa_outboxcode.Text + "成功拆解!\n", Color.Green);
                                LoadGridData();
                                LoadCheckQTY();
                            }
                            else OperateResult.AppendText(">>箱号" + pa_outboxcode.Text + "已送检,不允许解除\n", Color.Red);
                        }
                        else OperateResult.AppendText(">>箱号" + pa_outboxcode.Text + "已下地,不允许解除\n", Color.Red);
                    }
                    else OperateResult.AppendText(">>箱号" + pa_outboxcode.Text + "已装箱,不允许解除\n", Color.Red);
                }
                else OperateResult.AppendText(">>箱号" + pa_outboxcode.Text + "不存在\n", Color.Red);
            }
        }

        private void pr_code_TextChanged_1(object sender, EventArgs e)
        {
            LoadCheckQTY();
            dt = (DataTable)dh.ExecuteSql("select la_id,substr(la_url,instr(la_url,'\\',-1)+1)la_name,la_url,la_isdefault from label where la_prodcode='" + pr_code.Text + "' and la_templatetype='卡通箱标' and la_statuscode='AUDITED' order by la_isdefault", "select");
            PrintLabel.DataSource = dt;
            PrintLabel.DisplayMember = "la_url";
            PrintLabel.ValueMember = "la_id";

        }
    }
}