using HslCommunication.Robot.FANUC;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Threading;
using static Focas1;

namespace MesWork
{
    public partial class Temp { }
    public partial class B_Robot_Fanuc
    {
        /// <summary>
        /// 
        /// </summary>
        private FanucInterfaceNet fanuc = 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 DeviceCode = "";
        /// <summary>
        /// 
        /// </summary>
        string OpName = "";
        /// <summary>
        /// 焊接中
        /// </summary>
        int welding = 0;
        /// <summary>
        /// 
        /// </summary>
        public string Id = "-1";
        /// <summary>
        /// 
        /// </summary>
        string Name = "";
        /// <summary>
        /// 
        /// </summary>
        List<JointConfig> Joints = null;
        /// <summary>
        /// 
        /// </summary>
        public string md5Pos = "";

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

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="interval"></param>
        /// <param name="intervalUpdate"></param>
        /// <param name="cmd"></param>
        /// <param name="cmd_Welding"></param>
        /// <param name="Id"></param>
        /// <param name="Name"></param>
        /// <param name="Joints"></param>
        public void Start(string ip, int port, int interval, int intervalUpdate, string cmd, string cmd_Welding, string Id, string Name, List<JointConfig> Joints)
        {
            this.ip = ip;
            this.port = port;
            this.interval = interval;
            this.cmd = cmd;
            this.cmd_Welding = cmd_Welding;
            this.Id = Id;
            this.Name = Name;
            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 (fanuc == null)
                        {
                            ReConnRobot();
                        }
                        var r = fanuc.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_FANUC_{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);//FANUC机床的轴位置
                        }

                    }
                    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_FANUC_{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_Fanuc()
        {
            FanucClose();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public void FanucClose()
        {
            isRun = false;
            Thread.Sleep(199);
            fanuc?.ConnectClose();

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        private void ReConnRobot()
        {
            if (MesWorkForm.IsDemoMesServer == 1)
            {
                fanuc = new FanucInterfaceNet();
                return;
            }

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

        }
        public void DisConn()
        {
            if (fanuc != null)
            {
                fanuc?.ConnectClose();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="j1_6"></param>
        /// <returns></returns>
        private double[] ReadResult_To_Array(string readResult)
        {
            if (MesWorkForm.IsDemoMesServer == 1)
            {
                return jDemo;
            }

            double[] joint = new double[12];

            var recdata = readResult;
            var jsc = ((JObject)JsonConvert.DeserializeObject(recdata))["Joint"];
            joint[0] = Convert.ToDouble(jsc[0]);
            joint[1] = Convert.ToDouble(jsc[1]);
            joint[2] = Convert.ToDouble(jsc[2]);
            joint[3] = Convert.ToDouble(jsc[3]);
            joint[4] = Convert.ToDouble(jsc[4]);
            joint[5] = Convert.ToDouble(jsc[5]);
            joint[6] = Convert.ToDouble(jsc[6]);
            joint[7] = Convert.ToDouble(jsc[7]);
            joint[8] = Convert.ToDouble(jsc[8]);

            joint[9] = Convert.ToDouble(0);
            joint[10] = Convert.ToDouble(0);
            joint[11] = Convert.ToDouble(0);

            joint = new double[]
            {
                 //Math.Round(Convert.ToDouble(joint[0])*Math.PI/180,4),
                 //Math.Round(Convert.ToDouble(joint[1])*Math.PI/180,4),
                 //Math.Round(( Convert.ToDouble(joint[2])+ Convert.ToDouble(joint[1]))*Math.PI/180 ,4),
                 //Math.Round(Convert.ToDouble(joint[3])*Math.PI/180,4),
                 //Math.Round(Convert.ToDouble(joint[4])*Math.PI/180,4),
                 //Math.Round(Convert.ToDouble(joint[5])*Math.PI/180,4),
                 //Convert.ToDouble(joint[6])/1000,
                 //Convert.ToDouble(joint[7])/1000,
                 //Convert.ToDouble(joint[8])/1000

                 Math.Round(Convert.ToDouble(joint[0]),2),
                 Math.Round(Convert.ToDouble(joint[1]),2),
                 Math.Round((Convert.ToDouble(joint[2])+ Convert.ToDouble(joint[1])) ,2),
                 Math.Round(Convert.ToDouble(joint[3]),2),
                 Math.Round(Convert.ToDouble(joint[4]),2),
                 Math.Round(Convert.ToDouble(joint[5]),2),
                 Convert.ToDouble(joint[6])/1000,
                 Convert.ToDouble(joint[7])/1000,
                 Convert.ToDouble(joint[8])/1000,
                 Convert.ToDouble(joint[9]),
                 Convert.ToDouble(joint[10]),
                 Convert.ToDouble(joint[11])
            };


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




    }
}
