using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using UAS_MES_NEW.DataOperate;
using UAS_MES_NEW.Entity;
using UAS_MES_NEW.PublicMethod;

namespace UAS_MES_NEW.Packing
{
    public partial class Packing_ProdWeightSet : Form
    {

        AutoSizeFormClass asc = new AutoSizeFormClass();

        LogStringBuilder sql = new LogStringBuilder();

        DataTable Dbfind;//存储工单号查询出来的信息

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

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

        DataHelper dh;

        Thread thread;

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

        int samplesCount = 0;

        //string maxValue = "";//存储最大值

        //string minValue = "";//存储最小值

        List<string> sncodes = new List<string>();//存序列号
        List<string> indates = new List<string>();//存时间
        List<string> weights = new List<string>();//存重量

        string recordSW = ""; //存标准重量
        string recordEV = "";//存误差值
        public Packing_ProdWeightSet()
        {
            InitializeComponent();
        }

        private void Packing_ProdWeightSet_Load(object sender, EventArgs e)
        {
            asc.controllInitializeSize(this);
            ComList.Text = BaseUtil.GetCacheData("PortName").ToString();
            BaudRate.Text = BaseUtil.GetCacheData("BaudRate").ToString();
            //工单号放大镜配置
            ma_code.TableName = "make left join product on ma_prodcode=pr_code";
            ma_code.SelectField = "ma_code # 工单号,pr_code # 产品编号,pr_detail # 产品名称,pr_spec # 规格,ma_qty # 工单数量";
            ma_code.FormName = Name;
            ma_code.SetValueField = new string[] { "ma_code","pr_code","pr_detail","pr_spec" };
            ma_code.DbChange += Ma_code_DbChange;

            dh = SystemInf.dh;
            //开始称重
            startWeigh.PerformClick();
        }
        private void Ma_code_DbChange(object sender, EventArgs e)
        {
            Dbfind = ma_code.ReturnData;
            BaseUtil.SetFormValue(this.Controls, Dbfind);
            //取误差值
            errorValue.Text = dh.GetConfig("prodWeightErrorValue", "MESSetting").ToString();
        }
        private void recordResult(int index,string palletcode, string weigh, DateTime time)
        {
            //创建一个item
            ListViewItem lvi = new ListViewItem();
            //分条赋值
            lvi.SubItems.Add(index+"");
            lvi.SubItems.Add(palletcode);
            lvi.SubItems.Add(weigh);
            lvi.SubItems.Add(time.ToString());
            //添加结果的信息进去
            showResult.Items.Add(lvi);
            //更新已称重量最大值最小值
            if (index > 1)
            {
                //maxValue = double.Parse(weigh) > double.Parse(maxValue) ? weigh : maxValue;
                //minValue = double.Parse(weigh) < double.Parse(minValue) ? weigh : minValue;
            }
            else
            {
                //maxValue = weigh;
                //minValue = weigh;
                //每次添加第一条数据的时候清空list的值
                sncodes.Clear();
                indates.Clear();
                weights.Clear();
            }
            //将重量信息加到集合中
            sncodes.Add(palletcode);
            indates.Add(time.ToString("yyyy-MM-dd HH:mm:ss"));
            weights.Add(weigh.Replace("kg", "").Trim());
        }

        private void startWeigh_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 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;
                                //weight.Text = Regex.Replace(serialPort1.ReadLine(), "\\D+", "");
                            }
                            catch (Exception)
                            {
                                GetData = false;
                            }
                        }
                    }
                    catch (IOException ex) { MessageBox.Show(ex.Message); }
                }
                else
                    MessageBox.Show("端口已被占用,请关闭其他窗口");
            }
        }
        //停止称重
        private void stopWeigh_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                GetData = false;
                serialPort1.Close();
                SystemInf.OpenPort.Remove(serialPort1.PortName);
                thread.Abort();
            }
        }

        private void confirm_Click(object sender, EventArgs e)
        {
            //按确认更新产品重量
            if (ma_code.Text=="")
            {
                OperateResult.AppendText("<<请先选择工单\n", Color.Red);
                return;
            }
            //判断是否达到已称数量
            if (showResult.Items.Count<samplesCount)
            {
                OperateResult.AppendText("<<采样个数不足\n", Color.Red);
                return;
            }
            //double sum = 0;
            ////点击取平均值
            //foreach (string s in weights)
            //{
            //    sum += double.Parse(s);
            //}
            //sum = sum / weights.Count;
            //更新彩盒重量最大值最小值
            dh.ExecuteSql("update product set PR_COLORBOXMAXW ='" + (double.Parse(standardWeight.Text) + double.Parse(errorValue.Text)) + "', PR_COLORBOXMINW = '" + (double.Parse(standardWeight.Text) - double.Parse(errorValue.Text)) + "' where pr_code='" + pr_code.Text + "'", "update");
            //更新此产品需要检测彩盒重量
            dh.ExecuteSql("update product set pr_checkcolorboxw = 1 where pr_code='" + pr_code.Text + "'", "update");
            OperateResult.AppendText("<<重量设置成功,最大值" + (double.Parse(standardWeight.Text) + double.Parse(errorValue.Text)) +unit.Text+ ",最小值" + (double.Parse(standardWeight.Text) - double.Parse(errorValue.Text)) + unit.Text+"\n", Color.Green);
            LogicHandler.DoCommandLog(Tag.ToString(),User.UserCode,"",User.UserLineCode,User.UserSourceCode,"产品重量设置","产品编号"+pr_code.Text+",最大"+ (double.Parse(standardWeight.Text) + double.Parse(errorValue.Text))+unit.Text+"最小"+ (double.Parse(standardWeight.Text) - double.Parse(errorValue.Text))+unit.Text,"","");
            //更新采样记录表
            string serialNum = dh.GetSerialNumberByCaller("ProdWeightSample");
            sql.Clear();
            sql.Append("insert into PRODWEIGHTSAMPLE(PWS_CODE,PWS_SNCODE,PWS_MAKECODE,PWS_PRODCODE,PWS_INDATE,PWS_WEIGHT,PWS_UNIT) ");
            sql.Append("values ('"+serialNum+"',:sncode,'"+ma_code.Text+"','"+pr_code.Text+ "',TO_Date(:indate,'YYYY-MM-dd HH24:mi:ss'),:weight,'" + unit.Text+"')");
            dh.BatchInsert(sql.GetString(), new string[] { "sncode", "indate" , "weight" },sncodes.ToArray(),indates.ToArray(),weights.ToArray());
        }

        private void sncode_KeyDown(object sender, KeyEventArgs e)
        {
            //按下了enter键
            if (e.KeyCode == Keys.Enter)
            {
                if (sncode.Text == "")
                {
                    OperateResult.AppendText("<<输入不能为空\n", Color.Red);
                    return;
                }
                if (weight.Text == "")
                {
                    OperateResult.AppendText("<<未读取到重量信息\n", Color.Red);
                    return;
                }
                if (double.Parse(weight.Text.Replace("kg", "").Trim()) == 0)
                {
                    OperateResult.AppendText("<<重量不能等于0\n", Color.Red, sncode);
                    return;
                }
                //验证序列号是否存在
                if (!dh.CheckExist("makeserial", "ms_sncode = '" + sncode.Text + "'"))
                {
                    OperateResult.AppendText("<<序列号" + sncode.Text + "不存在\n", Color.Red, sncode);
                    return;
                }
                //验证彩盒是否与产品对应
                if (!dh.CheckExist("makeserial","ms_prodcode='"+pr_code.Text+"' and ms_sncode = '"+sncode.Text+"'"))
                {
                    OperateResult.AppendText("<<序列号"+sncode.Text+"对应产品编号不是"+pr_code.Text+"\n", Color.Red, sncode);
                    return;
                }
                //验证所称彩盒是否重复
                if (sncodes.Contains(sncode.Text))
                {
                    OperateResult.AppendText("<<序列号" + sncode.Text + "已经称过\n", Color.Red, sncode);
                    return;
                }
                //判断称重记录是否满足标准重量+-误差值
                double ActualWeight = double.Parse(weight.Text == "" ? "0" : weight.Text.Replace("kg", "").Trim());
                if (ActualWeight < (double.Parse(standardWeight.Text)- double.Parse(errorValue.Text))|| ActualWeight > (double.Parse(standardWeight.Text) + double.Parse(errorValue.Text)))
                {
                    OperateResult.AppendText("<<序列号" + sncode.Text + "重量不在预设范围内\n", Color.Red, sncode);
                    return;
                }
                //记录重量
                recordResult(showResult.Items.Count+1,sncode.Text, weight.Text, System.DateTime.Now);
                sncode.Text = "";
            }
        }

        private void Packing_ProdWeightSet_AutoSizeChanged(object sender, EventArgs e)
        {

        }

        private void Packing_ProdWeightSet_SizeChanged(object sender, EventArgs e)
        {
            asc.controlAutoSize(this);
        }

        private void ma_code_UserControlTextChanged(object sender, EventArgs e)
        {
            //赋值
            sql.Clear();
            sql.Append("select ma_code,pr_code,pr_detail,pr_spec,ma_qty from make left join product on ma_prodcode=pr_code ");
            sql.Append("where ma_code='" + ma_code.Text + "'");
            Dbfind = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
            if (Dbfind.Rows.Count == 0)
            {
                return;
            }
            BaseUtil.SetFormValue(this.Controls, Dbfind);
            //清空称量记录
            showResult.Items.Clear();
            indates.Clear();
            sncodes.Clear();
            weights.Clear();
        }

        private void ma_code_TextKeyDown(object sender, KeyEventArgs e)
        {

        }

        private void Packing_ProdWeightSet_FormClosing(object sender, FormClosingEventArgs e)
        {
            stopWeigh.PerformClick();
            if (serialPort1.IsOpen)
            {
                GetData = false;
                serialPort1.Close();
                SystemInf.OpenPort.Remove(serialPort1.PortName);
                thread.Interrupt();
            }
            //thread.Abort();
        }

        private void standardWeight_Leave(object sender, EventArgs e)
        {
            //在采样的时候不能更改
            if (showResult.Items.Count > 0)
            {
                if ((sender as TextBox).Name == "standardWeight"&& standardWeight.Text == recordSW)
                {
                    return;
                }
                else if((sender as TextBox).Name == "errorValue" && errorValue.Text == recordEV)
                {
                    return;
                }
                if (MessageBox.Show("是否修改标准重量或误差值重新采样", "提示", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                {
                    //选择取消,数据回退
                    standardWeight.Text = recordSW;
                    errorValue.Text = recordEV;
                }
                else
                {
                    //选择确认,重新采样
                    showResult.Items.Clear();
                    indates.Clear();
                    sncodes.Clear();
                    weights.Clear();
                }
            }
        }

        private void standardWeight_Enter(object sender, EventArgs e)
        {
            recordSW = standardWeight.Text;
            recordEV = errorValue.Text;
        }

        private void pr_code_TextChanged(object sender, EventArgs e)
        {
            //产品更换的时候
            DataTable d = (DataTable)dh.ExecuteSql("select PR_COLORBOXMAXW,PR_COLORBOXMINW,PR_COLORBOXUNIT from product where pr_code='" + pr_code.Text + "'", "select");
            //给标准重量赋值
            if (d.Rows[0]["PR_COLORBOXMAXW"].ToString() == "" || d.Rows[0]["PR_COLORBOXMINW"].ToString() == "")
            {
                standardWeight.Text = 0 + "";
            }
            else
            {
                //取二者平均值来
                standardWeight.Text = (double.Parse(d.Rows[0]["PR_COLORBOXMAXW"].ToString()) + double.Parse(d.Rows[0]["PR_COLORBOXMINW"].ToString())) / 2 + "";
            }
            if (d.Rows[0]["PR_COLORBOXUNIT"].ToString() != "")
            {
                unit.Text = d.Rows[0]["PR_COLORBOXUNIT"].ToString();
            }
            else
            {
                unit.Text = "kg";
            }
            //取误差值
            errorValue.Text = dh.GetConfig("prodWeightErrorValue", "MESSetting").ToString();
            //查询重量设置采样个数
            try
            {
                samplesCount = int.Parse(dh.GetConfig("prodWeightSetting", "MESSetting").ToString());
            }
            catch (Exception ess)
            {
                //如果没维护的话默认是10
                samplesCount = 10;
            }
            OperateResult.AppendText("<<重量设置需采样个数为" + samplesCount + "\n", Color.Black);
            //清空称量记录
            showResult.Items.Clear();
            indates.Clear();
            sncodes.Clear();
            weights.Clear();
        }
    }
}