using com.hnshituo.core.webapp.vo;
using Common;
using Infragistics.Win;
using JC_MeasuringSystem;
using MeterPlugInLibrary;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CraneScaleSystem
{
    public partial class frmCraneScale : Form
    {
        public frmCraneScale()
        {
            InitializeComponent();
            ClsControlPack.ShowGridCaption<MeterWorkCraneActual>(ultraGridYb.DisplayLayout.Bands[0]);
        }

        CraneScaleCollectModel scModel1 = new CraneScaleCollectModel(); //静态1

        //实时表数据采集
        private CraneScaleControl collection = new CraneScaleControl();

        MeterWorkCraneActualService craneActualService = new MeterWorkCraneActualService();
        PreTrackScaleService trackScaleService = new PreTrackScaleService();
        private Log l = Log.GetInstance(); //日志

        Thread tkWgt = null;//采集线程
        bool wgtStart = false, bLock = false, btest = false;
        bool bMsgVisible = false;

        PreTrackScale scale = null;

        private CoreAppUser userinfo = null;
        private void frmCraneScale_Load(object sender, EventArgs e)
        {
            userinfo = ((ST_MainForm)(this.MdiParent)).AppUser;
            ClsControlPack.SetUltraGridRowFilter(ref ultraGridYb, true);

            ValueList vValid = new ValueList(); //状态（0=作废，1=有效，2=结净）
            vValid.ValueListItems.Add("2", "生成");
            vValid.ValueListItems.Add("1", "有效");
            vValid.ValueListItems.Add("0", "作废");
            ultraGridYb.DisplayLayout.Bands[0].Columns["valueFlag"].ValueList = vValid.Clone();


            ValueList vValidFst = new ValueList(); //状态（0=作废，1=有效，2=结净）
            vValidFst.ValueListItems.Add("2", "校磅");
            vValidFst.ValueListItems.Add("1", "皮重");
            vValidFst.ValueListItems.Add("0", "毛重");//weightType
            ultraGridYb.DisplayLayout.Bands[0].Columns["weightType"].ValueList = vValidFst.Clone();


            //LoadDb(); 通过moxic直接才的方式

            collection.EventDataCollectionArgs += new CraneScaleEventDataCollection(EventData);//数据采集1
            collection.Start("CAR18");
        }

        private void EventData(object o, CraneScaleCollectModel e)
        {
            //这里每隔0.5秒执行一次
            try
            {
                scModel1.mainWgt = e.mainWgt;
                scModel1.weightStatus = e.weightStatus;
                scModel1.datetime = e.datetime;
                if (!bLock)
                {
                    if (!btest)
                    {
                        txtWeight.Invoke(new Action(() => { txtWeight.Text = scModel1.mainWgt + ""; }));
                    }
                    else 
                    {
                        txtWeight.Invoke(new Action(() => { txtWeight.Text = "2000"; }));
                    }
                }

                if (bMsgVisible) 
                { 
                    lbMsgInfo.Invoke(new Action(() => { lbMsgInfo.Text = ""; })); 
                }
                bMsgVisible = false;
            }
            catch (Exception ex)
            {
                if (!bMsgVisible) 
                {
                    lbMsgInfo.Invoke(new Action(() => { lbMsgInfo.Text = "数据采集异常！" + ex; }));
                    bMsgVisible = true;
                }
                
                l.WriteLog(13, "frmCraneScale.EventData数据采集异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        #region 通过moxic直接才的方式
        /*
        Socket client = null;
        IPAddress ip = null;
        IPEndPoint point = null;
        DbEntiry db = null;

        private void LoadDb() 
        {
            db = new DbEntiry
            {
                pointNo = "00001",
                pointName = "贵金属吊钩秤",
                moxicIp = "192.168.184.60",
                printName = @"\\172.31.170.14\7201h",
                endStr = 10,
                dbLength = 18,
                startLocation = 9,
                getLength = 6
            };
            ip = IPAddress.Parse(db.moxicIp);
            point = new IPEndPoint(ip, 4001);

            Start();
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //连接到服务器
            client.Connect(point);
        }

        private void Start() 
        {
            tkWgt = new Thread(new ThreadStart(TaskWgtGet));
            tkWgt.Start();
        }

        private void Stop() 
        {
            if (tkWgt != null)
            {
                tkWgt.Abort();
                tkWgt = null;
            }
        }

        
        private void TaskWgtGet()
        {
            while (wgtStart)
            {
                if (PbCache.collect_no == null) wgtStart = false;
                else
                {
                    try
                    {
                        //这里每隔0.5秒执行一次
                        if (!bLock)
                        {
                            if (btest)
                            {
                                txtWeight.Invoke(new Action(() => { txtWeight.Text = "2000"; }));
                                continue;
                            }
                        }

                        byte[] buffer = new byte[32 * 32];
                        int n = client.Receive(buffer);

                        if (db != null && db.isFz)
                        {
                            byte[] bf = buffer.Reverse().ToArray();
                            int m = 0;
                            foreach (byte b in bf)
                            {
                                if (b > 0) buffer[m++] = b;
                            }
                        }

                        byte[] bt = new byte[db.dbLength];

                        int iLast = 0, iCnt = 0;
                        for (int i = n - 1; i > -1; i--)
                        {
                            //byte字节里面都是数值       0-15          0-12
                            if (iLast == 0 && buffer[i] == db.endStr)
                            {
                                iLast = i;
                                bt[iCnt] = buffer[i];
                            }
                            else if (iLast != 0)
                            {
                                if (iCnt < db.dbLength - 1)
                                {
                                    bt[++iCnt] = buffer[i];
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                        Array.Reverse(bt);

                        if (iCnt + 1 != db.dbLength) continue;


                        byte[] btDb = new byte[db.getLength];
                        int iC = 0;
                        for (int i = db.startLocation; i < (db.startLocation + db.getLength); i++)
                        {
                            btDb[iC++] = bt[i - 1];
                        }

                        string str = Encoding.UTF8.GetString(btDb, 0, btDb.Length);
                        int iWgt = Convert.ToInt32(str);

                        if (bMsgVisible)
                        {
                            lbMsgInfo.Invoke(new Action(() =>
                            {
                                lbMsgInfo.Visible = false;
                            }));
                        }
                    }
                    catch (Exception ex)
                    {
                        lbMsgInfo.Invoke(new Action(() =>
                        {
                            lbMsgInfo.Text = "moxic取数解析失败！";
                        }));
                        bMsgVisible = true;
                        l.WriteLog(23, $"moxic取数解析失败：{ex.Message}");
                    }
                    finally
                    {
                        Thread.Sleep(500);
                    }
                }
            }
            try
            {
                //client.Shutdown();
                client.Disconnect(true);
            }
            catch { }
        }
        //*/
        #endregion


        //*
        /// <summary>
        ///完整终端地址:MOXAIP+MOXAPORT
        /// </summary>
        private IPEndPoint serverFullAddr;

        /// <summary>
        /// 连接套接字
        /// </summary>
        private Socket sock;
        //*/

        private void btnZero_Click(object sender, EventArgs e)
        {
            try
            {
                //*
                //设置IP和端口
                serverFullAddr = new IPEndPoint(IPAddress.Parse("192.168.184.60"), 4001);
                sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //指定本地主机地址和端口号
                sock.Connect(serverFullAddr);
                //*/

                //发送固定的指令“Z“到串口服务器
                byte[] byteSend = System.Text.Encoding.Default.GetBytes("Z");
                byte[] message = new byte[1024];
                try
                {
                    //发送数据
                    sock.Send(byteSend);
                    //client.Send(byteSend);
                    l.WriteLog(23, "远程清零成功！");
                    MessageBox.Show("远程清零下发指令下发成功，请关注重量变化！");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("远程清零下发指令出现错误，请联系管理员" + ex);
                }
                finally 
                {
                    if (!sock.Connected)
                    {
                        sock.Disconnect(true);
                    }
                    sock.Close();
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show("服务器清零失败。。。请联系系统管理员" + ee);
            }
        }

        

        private void btnQuery_Click(object sender, EventArgs e)
        {
            scale = null;
            if (string.IsNullOrEmpty(txtQPredictionNo.Text.Trim())) 
            {
                MessageBox.Show("请输入预报编号");
                txtQPredictionNo.Focus();
                return;
            }

            RESTfulResult<List<PreTrackScale>> resultPre = trackScaleService.doQueryWf(new PreTrackScale { predictionNo = txtQPredictionNo.Text.Trim() });
            if (resultPre.Succeed)
            {
                foreach (Control cn in gbEdit.Controls)
                {
                    if (cn is TextBox)
                    {
                        cn.Text = "";
                    }
                }
                cbIsTare.Checked = false;
                if (resultPre.Data == null || resultPre.Data.Count == 0)
                {
                    MessageBox.Show("未找到预报信息");
                    return;
                }
                else 
                {
                    txtPredictionNo.Text = resultPre.Data[0].predictionNo;
                    txtCarrierUnitName.Text = resultPre.Data[0].carrierUnitName;
                    txtForwardingUnitName.Text = resultPre.Data[0].forwardingUnitName;
                    txtMatterName.Text = resultPre.Data[0].matterName;
                    txtMemo.Text = resultPre.Data[0].memo;
                    txtMeterTypeName.Text = resultPre.Data[0].meterTypeName;
                    txtReceivingUnitName.Text = resultPre.Data[0].receivingUintName;
                    txtCarNo.Text = resultPre.Data[0].carNo;

                    scale = resultPre.Data[0];
                }
            }
            else
            {
                MessageBox.Show("查询失败：" + resultPre.ResultMessage);
                return;
            }

            Query();
        }

        private void btnRecover_Click(object sender, EventArgs e)
        {
            SaveDb("复磅");
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveDb();
        }

        private void SaveDb(string sFb = default)
        {
            int iWgt = 0;
            int.TryParse(txtWeight.Text.Trim(), out iWgt);
            if (iWgt == 0) 
            {
                MessageBox.Show("当前过磅重量为0，无法保存");
                return;
            }
            if (string.IsNullOrEmpty(sFb) && scale == null)
            {
                MessageBox.Show("请先输入预报编号进行查询");
                return;
            }

            bLock = true;
            MeterWorkCraneActual mwca = new MeterWorkCraneActual();
            if (scale != null)
            {
                //相同名称的均赋值一次
                EntityBase<PreTrackScale> entityBase = new EntityBase<PreTrackScale>();
                mwca = entityBase.format<MeterWorkCraneActual>(scale, mwca);
            }
            mwca.weightType = "0";//毛重
            mwca.meterWeight = iWgt;
            mwca.valueFlag = "1";

            int seqNum = 1, meterNum = 1;
            int.TryParse(txtSeqNum.Text.Trim(), out seqNum);
            mwca.seqnum = seqNum;

            if (!string.IsNullOrEmpty(sFb)) 
            {
                cbIsTare.Checked = false;
                mwca.weightType = "2";//复磅
                mwca.seqnum = 1;
                mwca.predictionNo = null;
            }

            if (cbIsTare.Checked)
            {
                int.TryParse(txtMeterNum.Text.Trim(), out meterNum);
                if (meterNum < 1 || string.IsNullOrEmpty(txtMeterNum.Text.Trim())) 
                {
                    MessageBox.Show("计量皮重的时候，请输入大于0的件数");
                    return;
                }

                mwca.meterNum = meterNum;
                mwca.weightType = "1";//皮重
            }

            mwca.createManNo = userinfo.userid;
            mwca.createManName = userinfo.username;
            mwca.createTime = DateTime.Now;
            mwca.actualFirstNo = DateTime.Now.ToString("yyyyMMddHHmmss");

            mwca.baseSpotNo = "00018";
            mwca.baseSpotName = "东区吊钩秤";

            RESTfulResult<MeterWorkCraneActual> result = craneActualService.doAddWf(mwca);
            bLock = false;
            if (result.Succeed)
            {
                MessageBox.Show("执行成功!");
                Query();
            }
            else
            {
                MessageBox.Show("保存失败：" + result.ResultMessage);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            btest = true;
        }

        private void Query() 
        {
            MeterWorkCraneActual mwca = new MeterWorkCraneActual();
            mwca.predictionNo = txtQPredictionNo.Text.Trim();
            mwca.valueFlag = "1";

            RESTfulResult<List<MeterWorkCraneActual>> result = craneActualService.doQueryWf(mwca);
            if (result.Succeed)
            {
                if (result.Data == null || result.Data.Count == 0)
                {
                    meterWorkCraneActualBindingSource.DataSource = new List<MeterWorkCraneActual>();
                    txtSeqNum.Text = "1";
                }
                else
                {
                    meterWorkCraneActualBindingSource.DataSource = result.Data;
                    txtSeqNum.Text = (result.Data.Count + 1) + "";
                }
                ClsControlPack.RefreshAndAutoSize(ultraGridYb, true);
            }
            else
            {
                MessageBox.Show("查询失败：" + result.ResultMessage);
            }
        }


        private void frmCraneScale_FormClosing(object sender, FormClosingEventArgs e)
        {
            collection.Stop();
        }
    }
}
