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;

namespace MesWork
{
    public partial class Temp { }
    public partial class B_Robot_Kuka
    {
        /// <summary>
        /// 
        /// </summary>
        private KukaAvarProxyNet kuka = null;
        /// <summary>
        /// 
        /// </summary>
        public bool OnLine = false;
        /// <summary>
        /// 
        /// </summary>
        private string ip = "-1";
        /// <summary>
        /// 
        /// </summary>
        private int port = -1;
        /// <summary>
        /// 
        /// </summary>
        private int interval = -1;
        /// <summary>
        /// 
        /// </summary>
        private bool isRun = true;
        /// <summary>
        /// 
        /// </summary>
        private string cmd = "";
        /// <summary>
        /// 
        /// </summary>
        private string cmd_Welding = "";
        /// <summary>
        /// 
        /// </summary>
        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>
        int welding = 0;
        /// <summary>
        /// 
        /// </summary>
        public string Id = "-1";
        /// <summary>
        /// 
        /// </summary>
        string Name = "";
        /// <summary>
        /// 
        /// </summary>
        public List<JointConfig> Joints = null;
        /// <summary>
        /// 
        /// </summary>
        public string md5Pos = "";


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

        }


        /// <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 cmd, string cmd_Welding, string DeviceCode, string OpName, List<JointConfig> Joints)
        {
            this.ip = ip;
            this.port = port;
            this.interval = interval;
            this.cmd = cmd;
            this.cmd_Welding = cmd_Welding;
            this.Id = DeviceCode;
            this.Name = OpName;
            this.Joints = Joints;

            new Thread(new ThreadStart(delegate ()
            {
                while (isRun)
                {
                    try
                    {
                        //var weldingStr = Read_Welding(cmd_Welding);
                        //switch (weldingStr.ToLower())
                        //{
                        //    case "1":
                        //    case "true":
                        //        welding = 1;
                        //        break;
                        //    default:
                        //        welding = 0;
                        //        break;
                        //}

                        if (kuka == null)
                        {
                            ReConnRobot();
                        }
                        var r = kuka.ReadString(cmd);
                        OnLine = r.IsSuccess;
                        if (OnLine)
                        {
                            j = ReadResult_To_Array(r.Content);
                        }
                        else
                        {
                            Thread.Sleep(10 * 1000);
                            ReConnRobot();
                            continue;
                        }
                        for (int i = 0; i < Joints.Count ; i++)
                        {
                            Joints[i].DeviceCode = $"ROBOT_KUKA_{ip.Split('.')[3]}";
                            Joints[i].Value = j[i].ToString();
                        }
                        //Joints[0].Value = j[0].ToString();
                        //Joints[1].Value = j[1].ToString();
                        //Joints[2].Value = j[2].ToString();
                        //Joints[3].Value = j[3].ToString();
                        //Joints[4].Value = j[4].ToString();
                        //Joints[5].Value = j[5].ToString();
                        //Joints[6].Value = j[6].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(interval);
                }
            }))
            { IsBackground = true }.Start();

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

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

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

        }

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



        ~B_Robot_Kuka()
        {
            DisConn();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public void DisConn()
        {
            isRun = false;
            Thread.Sleep(199);
            kuka?.ConnectClose();

        }


        /// <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)
            {
                kuka = new KukaAvarProxyNet();
                return;
            }

            if (kuka != null)
            {
                kuka?.ConnectClose();
            }
            kuka = new KukaAvarProxyNet();
            kuka.IpAddress = ip;
            kuka.Port = port;
            var connect = kuka.ConnectServer();
            if (connect.IsSuccess)
            {
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="j1_6"></param>
        /// <returns></returns>
        private double[] ReadResult_To_Array(string readResult)
        {
            //string readResult = "{E6AXIS: A1 -12.03, A2 -97.15, A3 116.47, A4 -30.16, A5 -23.85, A6 27.48, E1 0.0, E2 0.0, E3 0.0, E4 0.0, E5 0.0, E6 0.0}";

            if (MesWorkForm.IsDemoMesServer == 1)
            {
                return jDemo;
            }

            var axis_act = readResult;

            double[] joint = new double[12];

            if (axis_act == "-1")
            {
                axis_act = axis_act_Old;
            }
            else
            {
                //axis_act = Regex.Split(axis_act, ", E4", RegexOptions.IgnoreCase)[0];
                axis_act = Regex.Split(axis_act, "}", RegexOptions.IgnoreCase)[0];
                axis_act = axis_act.Replace("{E6AXIS: A1 ", "").Replace(", A2 ", "&").Replace(", A3 ", "&").Replace(", A4 ", "&").Replace(", A5 ", "&").Replace(", A6 ", "&")
                    .Replace(", E1 ", "&").Replace(", E2 ", "&").Replace(", E3 ", "&").Replace(", E4 ", "&").Replace(", E5 ", "&").Replace(", E6 ", "&");
                axis_act_Old = axis_act;
            }

            string[] jStr = axis_act.Split('&');

            for (int i = 0; i < jStr.Length; i++)
            {
                joint[i] = Math.Round(Convert.ToDouble(jStr[i]), 2); 
                //joint[i] = Convert.ToDouble(jStr[i]);
                //if (i == 6 | i == 7 | i == 8 | i == 9 | i == 10 | i == 11)
                //    joint[i] = Math.Round(joint[i] / 1000.0, 2);
                //else
                //    joint[i] = Math.Round(joint[i] * Math.PI / 180, 2);
            }

            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
            //});
        }



    }
}
