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

namespace UAS_MES.Make
{
    public partial class Make_CartonBoxWeighN : Form
    {
        AutoSizeFormClass asc = new AutoSizeFormClass();

        DataHelper dh;

        DataTable dt;

        LogStringBuilder sql = new LogStringBuilder();

        ApplicationClass lbl;

        Document doc;

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

        Thread thread;

        string PR_CHECKCARTONW = "0";
        //创建串口实例
        SerialPort serialPort1 = new SerialPort();

        //true的时候表示从串口读取数据
        bool GetData = true;
        //箱内总数
        int pa_totalqty;
        //称量的标准重量
        Double Weight;
        //最大重量
        Double MaxWeight;
        //最小重量
        Double MinWeight;
        DataTable ListC = new DataTable();

        Thread InitPrint;

        public Make_CartonBoxWeighN()
        {
            InitializeComponent();
        }

        protected override void OnVisibleChanged(EventArgs e)
        {
            base.OnVisibleChanged(e);
            if (!IsHandleCreated)
            {
                this.Close();
            }
        }

        private void 卡通箱称重_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;
            asc.controllInitializeSize(this);
            ComList.Text = BaseUtil.GetCacheData("PortName").ToString();
            BaudRate.Text = BaseUtil.GetCacheData("BaudRate").ToString();
            InitPrint = new Thread(InPrint);
            SetLoadingWindow stw = new SetLoadingWindow(InitPrint, "初始化打印程序");
            BaseUtil.SetFormCenter(stw);
            stw.ShowDialog();
            StartWeight.PerformClick();
            dh = SystemInf.dh;
            StepCount.StepCode = User.CurrentStepCode;
            StepCount.Source = User.UserSourceCode;
            StepCount.LineCode = User.UserLineCode;
            StepCount.Dh = dh;
            StepCount.Start();
        }

        private void InPrint()
        {
            try
            {
                lbl = new ApplicationClass();
                BaseUtil.WriteLbl();
            }
            catch (Exception)
            {
                OperateResult.AppendText("未正确安装CodeSoft软件\n", Color.Red);
            }
        }

        private void 卡通箱称重_SizeChanged(object sender, EventArgs e)
        {
            weight.Location = new Point(weight_label.Location.X + weight_label.Size.Width - 10, weight_label.Location.Y - 20);
            asc.controlAutoSize(this);
        }

        private void sncode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //根据箱号查询表单数据
                sql.Clear();
                sql.Append("select pa_totalqty,ma_code,ma_qty,ma_salecode,PA_STANDARDQTY,PA_CURRENTQTY,pr_detail,pr_cartonunit,pr_code,pr_cartongw,");
                sql.Append("pr_cartonmaxw,pr_cartonminw,nvl(PR_CHECKCARTONW,'0') PR_CHECKCARTONW,nvl(pr_sendchecktype,'LineCode')pr_sendchecktype,nvl(ma_iflpn_user,0)ma_iflpn_user from package left join packagedetail ");
                sql.Append("on pa_id=pd_paid left join makeserial on ms_sncode=pd_barcode and ms_makecode=pa_makecode left join product on pr_code=pd_prodcode left join make on ma_code=pd_makecode ");
                sql.Append(" where pa_outboxcode='" + outboxcode.Text + "' and pa_nextstep='" + User.CurrentStepCode + "'");
                DataTable dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
                //填充打印文件选项的DataGridView
                if (dt.Rows.Count > 0)
                {
                    BaseUtil.SetFormValue(this.Controls, dt);
                    string ErrorMessage = "";
                    //重量的临时变量
                    PR_CHECKCARTONW = dt.Rows[0]["PR_CHECKCARTONW"].ToString();
                    string _weight = dt.Rows[0]["pr_cartongw"].ToString();
                    string _maxweight = dt.Rows[0]["pr_cartonmaxw"].ToString();
                    string _minweight = dt.Rows[0]["pr_cartonminw"].ToString();
                    string pa_pr_cartonunit = dt.Rows[0]["pr_cartonunit"].ToString();
                    string PA_STANDARDQTY = dt.Rows[0]["PA_STANDARDQTY"].ToString();
                    string PA_CURRENTQTY = dt.Rows[0]["PA_CURRENTQTY"].ToString();
                    string ma_iflpn_user = dt.Rows[0]["ma_iflpn_user"].ToString();
                    Weight = double.Parse(_weight == "" ? "0" : _weight);
                    MaxWeight = double.Parse(_maxweight == "" ? "0" : _maxweight);
                    MinWeight = double.Parse(_minweight == "" ? "0" : _minweight);
                    pa_totalqty = int.Parse(dt.Rows[0]["pa_totalqty"].ToString());
                    if (Weight - MinWeight == MaxWeight - Weight)
                        pr_cartongw.Text = Weight + "±" + (MaxWeight - Weight) + dt.Rows[0]["pr_cartonunit"].ToString();
                    else
                        pr_cartongw.Text = MinWeight + "-" + MaxWeight + dt.Rows[0]["pr_cartonunit"].ToString();
                    double ActualWeight = double.Parse(weight.Text == "" ? "0" : weight.Text.Replace("kg", "").Trim());

                    if (sncheck.Checked && sn.Text == "")
                    {
                        OperateResult.AppendText(">>SN校验不可为空\n", Color.Red);
                        sn.Text = "";
                        outboxcode.Text = "";
                        sn.Focus();
                        return;
                    }

                    if (sn.Text != "" && !dh.CheckExist("packagedetail", "pd_outboxcode = '" + outboxcode.Text + "' and pd_barcode = '" + sn.Text + "'"))
                    {
                        OperateResult.AppendText(">>SN:" + sn.Text + "不存在与箱号:" + outboxcode.Text + "中\n", Color.Red);
                        sn.Text = "";
                        outboxcode.Text = "";
                        sn.Focus();
                        return;
                    }

                    if (ma_iflpn_user == "-1")
                    {
                        if (!LogicHandler.CheckLpn(outboxcode.Text, lpn.Text, out ErrorMessage))
                        {
                            OperateResult.AppendText(">卡通箱" + outboxcode.Text + "LPN校验未通过\n", Color.Red, outboxcode);
                            sn.Text = "";
                            lpn.Text = "";
                            sn.Focus();
                            return;
                        }
                        else
                        {
                            lpn.Text = "";
                        }
                    }



                    //需要检查称重重量
                    if (PR_CHECKCARTONW != "0" && PA_STANDARDQTY == PA_CURRENTQTY)
                    {
                        //称量合格或不合格都记录重量
                        if (ActualWeight >= MinWeight && ActualWeight <= MaxWeight && ActualWeight != 0)
                        {
                            LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, ma_code.Text, User.UserLineCode, User.UserSourceCode, "卡通箱" + outboxcode.Text + "称重", "称量合格:" + weight.Text.Trim(), outboxcode.Text, "");
                            LogicHandler.RecordProdWeight(outboxcode.Text, "CARTON", float.Parse(ActualWeight.ToString()), "kg", User.UserLineCode, pr_code.Text, User.UserSourceCode, User.UserName);
                            OperateResult.AppendText(">>箱号" + outboxcode.Text + "检测合格\n", Color.Green);
                        }
                        else
                        {
                            LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, ma_code.Text, User.UserLineCode, User.UserSourceCode, "卡通箱" + outboxcode.Text + "称重", "称量不合格:" + weight.Text.Trim(), outboxcode.Text, "");
                            LogicHandler.RecordProdWeight(outboxcode.Text, "CARTON", float.Parse(ActualWeight.ToString()), "kg", User.UserLineCode, pr_code.Text, User.UserSourceCode, User.UserName);
                            OperateResult.AppendText(">>箱号" + outboxcode.Text + "检测未通过\n", Color.Red, outboxcode);
                            sn.Text = "";
                            if (sncheck.Checked)
                            {
                                sn.Focus();
                            }
                            return;
                        }
                    }
                    else
                    {
                        LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, ma_code.Text, User.UserLineCode, User.UserSourceCode, "卡通箱" + outboxcode.Text + "称重", "称量完成:" + weight.Text.Trim(), outboxcode.Text, "");
                        LogicHandler.RecordProdWeight(outboxcode.Text, "CARTON", float.Parse(ActualWeight.ToString()), "kg", User.UserLineCode, pr_code.Text, User.UserSourceCode, User.UserName);
                    }
                    dh.UpdateByCondition("package", "pa_printcount= nvl(pa_printcount,0)+1,pa_weight='" + ActualWeight + "',pa_status=1,pa_packageqty=pa_currentqty,pa_totalqty=pa_currentqty", "pa_outboxcode='" + outboxcode.Text + "'");
                    if (AutoPrint.Checked)
                    {
                        if (PrintLabel.Items.Count > 0)
                        {
                            Confirm.PerformClick();
                        }
                        else
                        {
                            OperateResult.AppendText(">>产品" + pr_code.Text + "未维护卡通标签\n", Color.Red);
                        }
                    }
                    ListViewItem lsi = new ListViewItem();
                    lsi.SubItems.Add(outboxcode.Text);
                    lsi.SubItems.Add(ActualWeight.ToString() + pr_cartonunit.Text);
                    lsi.SubItems.Add(System.DateTime.Now.ToString());
                    WeighRecord.Items.Add(lsi);
                    OperateResult.AppendText(">>箱号" + outboxcode.Text + "称重完成\n", Color.Green);
                    //if (LogicHandler.CartonBoxStepPass(ma_code.Text, User.UserSourceCode, outboxcode.Text, User.UserCode, "卡通箱:" + outboxcode.Text + "整箱过站", out ErrorMessage))
                    //{
                    //    dh.UpdateByCondition("package", "pa_printcount= nvl(pa_printcount,0)+1,pa_weight='" + ActualWeight + "',pa_status=1,pa_packageqty=pa_currentqty,pa_totalqty=pa_currentqty", "pa_outboxcode='" + outboxcode.Text + "'");
                    //    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='" + outboxcode.Text + "'").ToString() + "' ,PA_CURRENTSTEP = '' ", "pa_outboxcode='" + outboxcode.Text + "'");
                    //}
                    //else
                    //{
                    //    OperateResult.AppendText(">>" + ErrorMessage + "\n", Color.Red);
                    //}
                    DataTable dt1 = (DataTable)dh.ExecuteSql("select wm_concat(ms_sncode) from makeserial where  ms_downstatus=-1 and ms_outboxcode='" + outboxcode.Text + "'", "select");
                    if (dt1.Rows.Count > 0)
                    {

                        if (dt1.Rows[0][0].ToString() != "")
                        {
                            OperateResult.AppendText(">序列号:" + dt1.Rows[0][0].ToString() + "处于下地状态,箱不允许过站\n", Color.Red);

                            return;
                        }
                    }
                    if (!LogicHandler.OutBoxStepPass(outboxcode.Text, ma_code.Text, User.UserSourceCode, User.UserCode, "卡通箱:" + outboxcode.Text + "整箱过站", "卡通箱整箱过站", out ErrorMessage))
                    {
                        OperateResult.AppendText(">>" + ErrorMessage + "\n", Color.Red, outboxcode);
                        sn.Text = "";
                        if (sncheck.Checked)
                        {
                            sn.Focus();
                        }
                        return;
                    }

                    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='" + outboxcode.Text + "'").ToString() + "' ,PA_CURRENTSTEP = '' ", "pa_outboxcode='" + outboxcode.Text + "'");
                    LoadCheckQTY();
                    outboxcode.Clear();
                    sn.Text = "";
                    if (sncheck.Checked)
                    {
                        sn.Focus();
                    }

                }
                else
                {
                    OperateResult.AppendText(">>箱号" + outboxcode.Text + "当前执行工序不是" + User.CurrentStepCode + "\n", Color.Red, outboxcode);

                    sn.Text = "";
                    if (sncheck.Checked)
                    {
                        sn.Focus();
                    }
                }
            }
        }

        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;
                            }
                            catch (Exception)
                            {
                                GetData = false;
                            }
                        }
                    }
                    catch (IOException ex) { OperateResult.AppendText(">>" + ex.Message + "\n", Color.Red, outboxcode); }
                }
                else OperateResult.AppendText(">>端口已被占用,请关闭其他窗口\n", Color.Red, outboxcode);
            }
        }

        //确认打印
        private void Confirm_Click(object sender, EventArgs e)
        {
            //doc = lbl.Documents.Open(PrintLabel.Text);
            string ErrorMessage = "";
            if (!Print.CodeSoft(Tag.ToString(), ref lbl, PrintLabel.Text, PrintLabel.SelectedValue.ToString(), PrinterList.Text, outboxcode.Text, int.Parse(PrintNum.Text), ma_code.Text, pr_code.Text, "卡通箱标", "0", out ErrorMessage))
            {
                OperateResult.AppendText(ErrorMessage + "\n", Color.Red);
            }
        }

        //停止进程,关闭串口
        private void StopWeight_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                GetData = false;
                serialPort1.Close();
                SystemInf.OpenPort.Remove(serialPort1.PortName);
                thread.Abort();
            }
        }

        //关闭窗口的时候停止进程,不再读取串口数据
        private void 卡通箱称重_FormClosing(object sender, FormClosingEventArgs e)
        {
            BaseUtil.ClosePrint(lbl);
            StopWeight.PerformClick();
            InitPrint.Abort();
            if (serialPort1.IsOpen)
            {
                GetData = false;
                serialPort1.Close();
                SystemInf.OpenPort.Remove(serialPort1.PortName);
                thread.Interrupt();
            }
            //thread.Abort();
        }

        private void StartWeight_Click(object sender, EventArgs e)
        {
            thread = new Thread(getSerialData);
            try
            {
                GetData = true;
                serialPort1.PortName = this.ComList.Text;
                serialPort1.BaudRate = int.Parse(BaudRate.Text);
                serialPort1.Open();
                thread.Start();
            }
            catch (Exception mes)
            {
                if (BaudRate.Text == "" || ComList.Text == "")
                    OperateResult.AppendText(">>请先在电子秤调试界面维护波特率和串口\n", Color.Red);
                else
                    OperateResult.AppendText(">>" + mes.Message + "\n", Color.Red);
            }
        }

        private void pr_code_TextChanged(object sender, EventArgs e)
        {
            dt = (DataTable)dh.ExecuteSql("select la_id,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";
        }

        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 SendCheck_Click(object sender, EventArgs e)
        {
            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("", ma_code.Text, User.UserSourceCode, "手动送检", "手动送检成功", User.UserCode);
            //记录操作日志
            LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, ma_code.Text, User.UserLineCode, User.UserSourceCode, "手动送检", "手动送检成功", "", ob_checkno.Text);
            ob_checkno.Text = "";
        }
        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='" + ma_salecode.Text + "'";
            }
            else if (pr_sendchecktype.Text == "MakeCode")
            {
                condition += " and ob_makecode='" + ma_code.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 RefreshWeigh_Click(object sender, EventArgs e)
        {
            sql.Clear();
            sql.Append("select pr_cartonmaxw,pr_cartonunit,pr_cartonminw,pr_cartongw from product where pr_code='" + pr_code.Text + "'");
            DataTable dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
            //填充打印文件选项的DataGridView
            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);
                if (Weight - MinWeight == MaxWeight - Weight)
                    pr_cartongw.Text = Weight + "±" + (MaxWeight - Weight) + dt.Rows[0]["pr_cartonunit"].ToString();
                else
                    pr_cartongw.Text = MinWeight + "-" + MaxWeight + dt.Rows[0]["pr_cartonunit"].ToString();
            }
        }

        private void sn_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (dh.CheckExist("makeserial left join make on ms_makecode = ma_code",
                    "ms_sncode = '" + sn.Text + "' and nvl(ma_iflpn_user,0) = -1"))
                {
                    lpn.Focus();
                    lpn.SelectAll();
                }
                else
                {
                    outboxcode.Focus();
                    outboxcode.SelectAll();
                }
            }
        }

        private void lpn_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                outboxcode.Focus();
                outboxcode.SelectAll();
            }
        }
    }
}