using System;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using System.Collections.Generic;
using Newtonsoft.Json;
using HslCommunication.Robot.FANUC;
using HslCommunication.Robot.KUKA;
using System.Net.Sockets;
using Org.BouncyCastle.Bcpg;
using System.Text;
using Adapters;
using static Focas1;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace MesWork
{
    public class B_Robot_Espon
    {
        /// <summary>
        /// 
        /// </summary>
        private Socket espon = null;
        /// <summary>
        /// 
        /// </summary>
        public bool OnLine = false;
        /// <summary>
        /// 
        /// </summary>
        public string ip = "-1";
        /// <summary>
        /// 
        /// </summary>
        public int port = -1;
        /// <summary>
        /// 
        /// </summary>
        public int interval = -1;
        /// <summary>
        /// 
        /// </summary>
        public bool isRun = true;
        /// <summary>
        /// 
        /// </summary>
        public string sendV_Temp = "-1";
        /// <summary>
        /// 
        /// </summary>
        public double[] j = new double[12];
        /// <summary>
        /// 
        /// </summary>
        public double[] jDemo = new double[12];
        /// <summary>
        /// 记录老值
        /// </summary>
        string axis_act_Old = "-1";
        /// <summary>
        /// 焊接中
        /// </summary>
        public string clamp_Old = "";
        /// <summary>
        /// 
        /// </summary>
        public string clamp = "";
        /// <summary>
        /// 
        /// </summary>
        public string Id = "-1";
        /// <summary>
        /// 
        /// </summary>
        public string Name = "";
        /// <summary>
        /// 
        /// </summary>
        public List<JointConfig> Joints = null;
        /// <summary>
        /// 
        /// </summary>
        public string md5Pos = "";


        /// <summary>
        /// 
        /// </summary>
        public B_Robot_Espon()
        {

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="ipPort"></param>
        /// <param name="interval"></param>
        /// <param name="j1_6"></param>
        /// <param name="modelManagement"></param>
        /// <param name="modelCode"></param>
        public void Start(string ip, int port,int interval, int intervalUpdate, string DeviceCode, string OpName, List<JointConfig> Joints,string TagID_Clamp)
        {
            this.ip = ip;
            this.port = port;
            this.interval = interval;
            this.Id = DeviceCode;
            this.Name = OpName;
            this.Joints = Joints;
            var dataRec = new byte[1024 * 1024];

            new Thread(new ThreadStart(delegate ()
            {
                while (isRun)
                {
                    try
                    {
                        int readlen = 0;
                        if (espon == null)
                        {
                            continue;
                        }
                        try
                        {
                            espon.ReceiveTimeout = 5000;
                            readlen = espon.Receive(dataRec, 0, dataRec.Length, SocketFlags.None);
                        }
                        catch (Exception err)
                        {
                            continue;
                        }
                        if (readlen <= 0)
                        {
                            continue;
                        }

                        var str = Encoding.Default.GetString(dataRec, 0, readlen);

                        j = ReadResult_To_Array(str, out string clamp);

                        if (clamp_Old != clamp)
                        {
                            MesWorkForm.S_C_B_TagIDTrigger(OpName, TagID_Clamp, clamp);
                        }
                        clamp_Old = clamp;

                        for (int i = 0; i < Joints.Count; i++)
                        {
                            Joints[i].DeviceCode = $"ROBOT_ESPON_{ip.Split('.')[3]}";
                            Joints[i].Value = j[i].ToString();
                        }

                        var payload = MesWorkForm.Move_Joint(Joints);
                        var md5Str = JsonConvert.SerializeObject(payload);
                        if (md5Pos != md5Str)
                        {
                            md5Pos = md5Str;
                            MesWorkForm.SendMsg(payload);
                        }


                    }
                    catch (Exception err) { }
                    Thread.Sleep(15);
                }
            }))
            { IsBackground = true }.Start();


            new Thread(new ThreadStart(delegate ()
            {
                while (isRun)
                {
                    try
                    {
                      
                        try
                        {
                            if (MesWorkForm.IsDemoMesServer == 1)
                            {
                                j = jDemo;
                                OnLine = true;
                                continue;
                            }
                            if (espon == null)
                            {
                                ReConnRobot();
                            }
                            var data = Encoding.Default.GetBytes("1");
                            espon.Send(data, 0, data.Length, SocketFlags.None);
                            OnLine = true;
                        }
                        catch (Exception err)
                        {
                            OnLine = false;
                            Thread.Sleep(2000);
                            ReConnRobot();
                            continue;
                        }
                         
                    }
                    catch (Exception err) { }
                    Thread.Sleep(interval);
                }
            }))
            { IsBackground = true }.Start();


            new Thread(new ThreadStart(delegate () {
                while (isRun)
                {
                    try
                    {
                        for (int i = 0; i < Joints.Count; i++)
                        {
                            Joints[i].DeviceCode = $"ROBOT_ESPON_{ip.Split('.')[3]}";
                            Joints[i].Value = j[i].ToString();
                        }

                        var payload = MesWorkForm.Move_Joint(Joints);
                        MesWorkForm.SendMsg(payload);//FANUC机床的轴位置

                        UpdateDataToSql();
                    }
                    catch (Exception err) 
                    { }
                    Thread.Sleep(intervalUpdate);
                }
            }))
            { IsBackground = true }.Start();

            new Thread(new ThreadStart(delegate ()
            {
                while (isRun)
                {
                    var deviceInfo = new DeviceInfo();
                    deviceInfo.order = "";
                    deviceInfo.Name = Name;
                    deviceInfo.Id = Id;

                    deviceInfo.Axis = new List<AxisInfo>();
                    deviceInfo.OtherParameter = new List<ParameterInfo>();

                    deviceInfo.Axis.Add(new AxisInfo() { AxisName = "J1", AxisValue = Math.Round(j[0], 2).ToString() });
                    deviceInfo.Axis.Add(new AxisInfo() { AxisName = "J2", AxisValue = Math.Round(j[1], 2).ToString() });
                    deviceInfo.Axis.Add(new AxisInfo() { AxisName = "J3", AxisValue = Math.Round(j[2], 2).ToString() });
                    deviceInfo.Axis.Add(new AxisInfo() { AxisName = "J4", AxisValue = Math.Round(j[3], 2).ToString() });
                    deviceInfo.Axis.Add(new AxisInfo() { AxisName = "J5", AxisValue = Math.Round(j[4], 2).ToString() });
                    deviceInfo.Axis.Add(new AxisInfo() { AxisName = "J6", AxisValue = Math.Round(j[5], 2).ToString() });

                    var payloadInfoStr = MesWorkForm.Make_DeviceInfo(new List<DeviceInfo>() { deviceInfo });

                    MesWorkForm.SendMsg(payloadInfoStr);

                    Thread.Sleep(300);
                }
            }))
            { IsBackground = true }.Start();


        }

        public void TimelyUpdate()
        {
            var sendStr = MesWorkForm.Move_Joint(Joints);
            MesWorkForm.SendMsg(sendStr);
        }



        ~B_Robot_Espon()
        {
            DisConn();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public void DisConn()
        {
            isRun = false;
            Thread.Sleep(199);
            espon?.Close();
            espon = null;

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        private void ReConnRobot()
        {
            if (MesWorkForm.IsDemoMesServer == 1)
            {
                espon = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                return;
            }

            if (espon != null)
            {
                espon?.Close();
                espon = null;
            }
            espon = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            espon.Connect(ip, port);

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="j1_6"></param>
        /// <returns></returns>
        private double[] ReadResult_To_Array(string readResult,out string clamp)
        {
            clamp = "-1";

            var joint = new double[12];
            var jStr = readResult.Split(',');

            joint[0] = Math.Round(Convert.ToDouble(jStr[0]), 2);
            joint[1] = Math.Round(Convert.ToDouble(jStr[1]), 2);
            joint[2] = Math.Round(Convert.ToDouble(jStr[2]), 2);
            joint[3] = Math.Round(Convert.ToDouble(jStr[3]), 2);
            joint[4] = Math.Round(Convert.ToDouble(jStr[4]), 2);
            joint[5] = Math.Round(Convert.ToDouble(jStr[5]), 2);

            clamp = jStr[6];

            return joint;
        }


        /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="addr"></param>
        /// <returns></returns>
        public string Read_Welding(string addr)
        {
            string str = "-1";
            //if (kuka != null)
            //{
            //    var r = kuka.ReadString(addr);
            //    if (r.IsSuccess)
            //    {
            //        str = r.Content;
            //    }
            //}

            return str;
        }

        /// <summary>
        /// 手动测试读取
        /// </summary>
        /// <param name="j1_6"></param>
        /// <param name="j7"></param>
        /// <returns></returns>
        public string ReadTest(string robotName)
        {
            return "【" + robotName + "】" + MesWorkForm.Move_Joint(Joints);  
        }

        public void UpdateDataToSql()
        {
            StoredProcedure("Event_Robot_Update");
        }
        private void StoredProcedure(string pName)
        {
            //var sqlParameter = new SqlParameter[] {
            //     new SqlParameter("@DeviceCode", DeviceCode),
            //     new SqlParameter("@Online", OnLine),
            //     new SqlParameter("@StationName", OpName),
            //     new SqlParameter("@SlaveAddr", $"{ip}:{port}"),

            //     new SqlParameter("@Joint1", j[0]),
            //     new SqlParameter("@Joint2", j[1]),
            //     new SqlParameter("@Joint3", j[2]),

            //     new SqlParameter("@Joint4", j[3]),
            //     new SqlParameter("@Joint5", j[4]),
            //     new SqlParameter("@Joint6", j[5]),

            //     new SqlParameter("@Joint7", j[6]),
            //     new SqlParameter("@Joint8", j[7]),
            //     new SqlParameter("@Joint9", j[8]),

            //     new SqlParameter("@Joint10",j[9]),
            //     new SqlParameter("@Joint11",j[10]),
            //     new SqlParameter("@Joint12",j[11]),
            //     new SqlParameter("@Clamp", welding)
            //    };
            //MesWorkForm.taskSql.Enqueue(new NJ_ZC.ParamT
            //{
            //    procedureName = pName,
            //    sqlParameter = sqlParameter
            //});
        }



    }
}
