using DeviceDriver_BasicData;
using ExternalDataSync;
using Newtonsoft.Json;
using NJ_ZC;
using NPOI.OpenXmlFormats.Spreadsheet;
using OpcBasic;
using Rhino.Geometry;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Security.Policy;
using System.Threading;
using System.Windows.Forms;
using SystemFramework;
using static Focas1;
using static System.Configuration.ConfigurationManager;

namespace MesWork
{
    public partial class Temp {
        public static MesWorkForm mesWorkForm = null;
    }
    public partial class MesWorkForm
    {       
        /// <summary>
        /// 
        /// </summary>
        public static int IsWriteMonitorLog = Convert.ToInt32(AppSettings["IsWriteMonitorLog"]);
        public static int IsDemoMesServer = Convert.ToInt32(AppSettings["IsDemoMesServer"]);
        public static string BasicDataTableFile = AppSettings["BasicDataTableFile"];
        /// <summary>
        /// 
        /// </summary>
        public static int ConnectType = Convert.ToInt32(AppSettings["ConnectType"]);

        public static string IpPortSub = AppSettings["IpPortSub"];
        public static string MesServer_SendProtocol_Tag = AppSettings["MesServer_SendProtocol_Tag"];
        public static string MesServer_SendProtocol_Joint = AppSettings["MesServer_SendProtocol_Joint"];
        public static string MesServer_SendProtocol_Info_Fast = AppSettings["MesServer_SendProtocol_Info_Fast"];
        public static string MesServer_SendProtocol_Info_Slow = AppSettings["MesServer_SendProtocol_Info_Slow"];
        public static string MesServer_SendProtocol_Plc = AppSettings["MesServer_SendProtocol_Plc"];
        
        public static string MesServer_SendProtocol_DeviceInfo = AppSettings["MesServer_SendProtocol_DeviceInfo"];

        public static string ConnectionString = AppSettings["ConnectionString"];

        public static string WebSvrUrlPort = AppSettings["WebSvrUrlPort"];

        public static string MarkingMachine_Ip = AppSettings["MarkingMachine_Ip"];
        public static string MarkingMachine_Port = AppSettings["MarkingMachine_Port"];
        public static string Url_WebApi_Char = AppSettings["Url_WebApi_Char"];
        public static string AK = AppSettings["AK"];
        public static string SK = AppSettings["SK"];
        public static string salt = AppSettings["salt"];

        public static int TokenSyncTime = Convert.ToInt32(AppSettings["TokenSyncTime"]);
        public static int SyncTime = Convert.ToInt32(AppSettings["SyncTime"]);
        public static string charDataToken = "";
        public static long charDataTokenTime = 0;

        /// <summary>
        /// 
        /// </summary>
        public static Dictionary<string,object> dc_Robot = new Dictionary<string, object>();
        /// <summary>
        /// 
        /// </summary>
        public static Dictionary<string, B_Read_N_Axis> dc_Name_Axis = new Dictionary<string, B_Read_N_Axis>();
        public static Dictionary<string, B_Read_N_AxisCard> dc_Name_Axis_Card = new Dictionary<string, B_Read_N_AxisCard>();
        /// <summary>
        /// 
        /// </summary>
        public static AgvRead agvRead = null;
        /// <summary>
        /// 
        /// </summary>
        public static ScadaConfig scadaConfig = null;
        /// <summary>
        ///  
        /// </summary>
        public static ConcurrentQueue<ParamT> taskSql = new ConcurrentQueue<ParamT>();
        /// <summary>
        /// 
        /// </summary>
        public static string StationName = "DDV_SXYJ";
        /// <summary>
        /// 
        /// </summary>
        public static bool OnLine_PLC_1 = false;
        public static bool OnLine_PLC_2 = false;
        /// <summary>
        /// 
        /// </summary>
        public static bool OnLine_SQL = false;

        /// <summary>
        /// 监控数据的所有变化，从这里产生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OPCTagData_TagDataOnChangeMIS(object sender, CustomeEvetnArgs e)
        {
            ThreadPool.QueueUserWorkItem(MIS_Funtion, e);
        }
        /// <summary>
        /// 定时触发，检测PLC在线状态，周期：3 s
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="eState"></param>
        public override void PlcStateEvent(object sender, PlcStateEvetnArgs eState)
        {
            var ip = eState.IP.ToString();
            var onLine = (bool)eState.OnLine;

            switch (ip)
            {
                case "192.168.10.40":
                    OnLine_PLC_1 = onLine;
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="t"></param>
        /// <param name="location"></param>
        /// <param name="content"></param>
        public override void E_WriteLog(Enum_LogType t, string location, string content)
        {
            WriteLog(content);
        }
        /// <summary>
        /// 
        /// </summary>
        [STAThread]
        static void Main()
        {
            new System.Threading.Mutex(true, $"DT_SCADA_{IpPortSub}", out bool bCanRun);
            if (!bCanRun)
            {
                MessageBox.Show("产线信号监控 程序 已经在运行！不可重复启动！");
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(Temp.mesWorkForm = new MesWorkForm());
        }

        /// <summary>
        /// 读写取方法
        /// </summary>
        /// <param name="readWhat"></param>
        /// <param name="opOrIp"></param>
        private void DemoRead(string doWhat, string opOrIp)
        {
            try
            {
                string opName = "OP1010";
                object tagValue = 1;
                bool result = false;
                ConcurrentDictionary<string, object> tagAdrListTagFormat = null;

                switch (doWhat)
                {
                    case "TagID":
                        tagValue = ReadPLC("71010001");
                        result = WritePLC("71010001", tagValue);
                        break;
                    case "TagTypeCodeID":
                        tagValue = ReadPLC(10, opName);
                        result = WritePLC(10, opName, tagValue);
                        break;                   
                    case "OpAllTag"://OP所有点
                        tagAdrListTagFormat = ReadPLC_GroupData(opOrIp);
                        break;
                    case "OpMonitorTag"://OP监控点
                        tagAdrListTagFormat = ReadPLC_GroupMonitor(opOrIp);
                        break;
                    case "IpAllTag"://IP所有点
                        tagAdrListTagFormat = ReadPLC_IpTag(opOrIp);
                        break;
                    case "IpMonitorTag"://IP监控点
                        tagAdrListTagFormat = ReadPLC_IpMonitorTag(opOrIp);
                        break;
                    case "RegionRead"://按区域读取（起始地址 + 长度）
                        {
                            string tagStartAdr = "DB411.10";
                            ushort tagAdrListMaxLength = 100;
                            GetDbAndMaxLengthByOpName(opOrIp, out tagStartAdr, out tagAdrListMaxLength);
                            tagAdrListTagFormat = ReadQualityDataList(opOrIp, tagStartAdr, tagAdrListMaxLength);
                        }
                        break;
                    case "ReadBytes"://按区域读取（起始地址 + 长度）
                        {
                            string tagStartAdr = "DB411.10";
                            ushort tagAdrListMaxLength = 100;
                            var bates1 = ReadByteData_Op(opOrIp, tagStartAdr, tagAdrListMaxLength);
                            var bates2 = ReadByteData_Ip(opOrIp, tagStartAdr, tagAdrListMaxLength);
                        }
                        break;
                    case "WriteBytes"://按区域读取（起始地址 + 长度）
                        {
                            string tagStartAdr = "DB411.10";
                            var result1 = WritePLC_Bytes_Op(opOrIp, tagStartAdr, new byte[1024]);
                            var result2 = WritePLC_Bytes_Ip(opOrIp, tagStartAdr, new byte[1024]);
                        }
                        break;
                    default:
                        break;
                }
                //ReadByteData_Op(string opName, string startAdrr, ushort length)
                foreach (System.Collections.Generic.KeyValuePair<string, object> de in tagAdrListTagFormat)//得到工位监控点哈希表
                {
                    TagFormat TF = (TagFormat)de.Value;
                    string recResult = TF.OpName + "  (" + TF.TagTypeCodeID + ")" + TF.TagValue.ToString(); ;
                }
            }
            catch (System.Exception err)
            {
                ApplicationLog.WriteLog("listView_ShowQualityData_Init" + err);
            }

            //var tagTypeCodeIDList = DriverCache[CacheType.Cache_OpTagTypeCodeIDList];
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        private string Hello_You_All_Never_Know(string[] args)
        {
            return Guid.NewGuid().ToString()+ Guid.NewGuid().ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        static private void Loop()
        {
            while (true)
            {
                taskSql.TryDequeue(out ParamT tp);
                if (tp != null)
                {
                    var procedureName = tp.procedureName;
                    var sqlParameter = tp.sqlParameter;
                    DataLinkMesWork.SQLCommon.ExecuteStoredProcedure(procedureName, MesWorkForm.ConnectionString, ref sqlParameter, out string errorMessage);
                    if (errorMessage.Length > 0)
                    {
                        errorMessage = errorMessage.Replace("'", "**");
                        LogRecord.LogRecord.Insert_Log(LogRecord.LogRecord.Type_Log.Alarm, errorMessage);
                    }
                }
                if (taskSql.Count < 5)
                {
                    Thread.Sleep(15);
                }
            }
        }

        private void CommunicationCheckOnLine()
        {

            new Thread(new ThreadStart(delegate ()
            {
                while (true)
                {
                    try
                    {
                        MesWorkForm.OnLine_SQL = DataLinkMesWork.SQLCommon.ExecuteDataTable("select getdate()", ConnectionString, out DataTable dt, out string err);
                    }
                    catch (Exception) { }
                    Thread.Sleep(5000);
                }
            }))
            { IsBackground = true }.Start();

        }

        static private void LineCount()
        {
            while (true)
            {
                try
                {
                    foreach (var opName in MesWorkForm.opNameList)
                    {
                        var count_Total = ReadPLC(10, opName).ToString();
                        var count_OK = count_Total;
                        var count_NG = count_Total;

                        var pName = "Event_ProduceCount_Update";
                        var sqlParameter = new SqlParameter[] {
                         new SqlParameter("@DeviceCode", opName),
                         new SqlParameter("@Online", true.ToString()),
                         new SqlParameter("@StationName", opName),
                         new SqlParameter("@Count_OK", count_OK),
                         new SqlParameter("@Count_NG", count_NG),
                         new SqlParameter("@Count_Total", count_Total),
                        };
                        MesWorkForm.taskSql.Enqueue(new NJ_ZC.ParamT
                        {
                            procedureName = pName,
                            sqlParameter = sqlParameter
                        });
                    }
                       
                }
                catch (Exception err)
                {
                }
                Thread.Sleep(5000);
            }
        }

        static private void StationNameStatus_Insert()
        {
            while (true)
            {
                try
                {
                    foreach (var opName in MesWorkForm.opNameList)
                    {
/*
1	警报数
2	运行
*/
                        var status = "-1";
                        try
                        {
                            var alarm = ReadPLC(1, opName).ToString().ToLower().Replace("true","1").Replace("false", "0");
                            var run = ReadPLC(2, opName).ToString().ToLower().Replace("true", "1").Replace("false", "0");
                            if (Convert.ToInt32(alarm) > 0)
                            {
                                status = "2";
                            }
                            else
                            {
                                if (Convert.ToInt32(run) > 0)
                                {
                                    status = "1";
                                }
                                else
                                {
                                    status = "0";
                                }
                            }
                            if (alarm == "-1" & run == "-1")
                            {
                                status = "-1";
                            }
                        }
                        catch (Exception errr)
                        {
                        }

                        var pName = "Event_StationStatus_Insert";
                        var sqlParameter = new SqlParameter[] {
                                     new SqlParameter("@OpName", opName),
                                     new SqlParameter("@Status", status),
                                     new SqlParameter("@ChangeTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")),
                                    };
                        MesWorkForm.taskSql.Enqueue(new NJ_ZC.ParamT
                        {
                            procedureName = pName,
                            sqlParameter = sqlParameter
                        });

                    }
                }
                catch (Exception err)
                {
                }
                Thread.Sleep(60_000);
            }
        }
        static private void StationNameStatus_Update()
        {
            while (true)
            {
                try
                {
                    foreach (var opName in MesWorkForm.opNameList)
                    {
                        /*
  1	警报数
  2	运行
  */
                        var status = "-1";
                        try
                        {
                            var alarm = ReadPLC(1, opName).ToString().ToLower().Replace("true", "1").Replace("false", "0");
                            var run = ReadPLC(2, opName).ToString().ToLower().Replace("true", "1").Replace("false", "0");
                            if (Convert.ToInt32(alarm) > 0)
                            {
                                status = "2";
                            }
                            else
                            {
                                if (Convert.ToInt32(run) > 0)
                                {
                                    status = "1";
                                }
                                else
                                {
                                    status = "0";
                                }
                            }
                            if (alarm == "-1" & run == "-1")
                            {
                                status = "-1";
                            }
                        }
                        catch (Exception errr)
                        {
                        }


                        var pName = "Event_StationStatus_Update";
                        var sqlParameter = new SqlParameter[] {
                                     new SqlParameter("@OpName", opName),
                                     new SqlParameter("@Status", status),
                                     new SqlParameter("@ChangeTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")),
                                    };
                        MesWorkForm.taskSql.Enqueue(new NJ_ZC.ParamT
                        {
                            procedureName = pName,
                            sqlParameter = sqlParameter
                        });

                    }
                }
                catch (Exception err)
                {
                }
                Thread.Sleep(2000);
            }
        }
        static private void StationNameDeviceData_Insert()
        {
            while (true)
            {
                try
                {
                    foreach (var opName in MesWorkForm.opNameList)
                    {

                        var CreatTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                        var opData = ReadPLC_GroupData(opName);
                        foreach (KeyValuePair<string, object> item in opData)
                        {
                            var thisTagID = item.Key;
                            var thisTF = (TagFormat)item.Value;
                            var thisTagTypeCodeID = thisTF.TagTypeCodeID;
                            var thisItemName = thisTF.ItemName;
                            var thisValue = thisTF.TagValue;

                            var pName = "Event_DeviceData_Insert";
                            var sqlParameter = new SqlParameter[] {
                         new SqlParameter("@DeviceCode", opName),
                         new SqlParameter("@Online", true.ToString()),
                         new SqlParameter("@StationName", opName),
                         new SqlParameter("@TagTypeCodeID", thisTagTypeCodeID),
                         new SqlParameter("@ItemName", thisItemName),
                         new SqlParameter("@TagValue", thisValue),
                         new SqlParameter("@TagID", thisTagID),
                         new SqlParameter("@CreateTime", CreatTime),
                        };
                            MesWorkForm.taskSql.Enqueue(new NJ_ZC.ParamT
                            {
                                procedureName = pName,
                                sqlParameter = sqlParameter
                            });


                        }

                    }
                }
                catch (Exception err)
                {
                }
                Thread.Sleep(60_000);
            }
        }

        static private void StationNameDeviceData_Update()
        {
            while (true)
            {
                try
                {
                    foreach (var opName in MesWorkForm.opNameList)
                    {
                        var CreatTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                        var opData = ReadPLC_GroupData(opName);
                        foreach (KeyValuePair<string, object> item in opData)
                        {
                            var thisTagID = item.Key;
                            var thisTF = (TagFormat)item.Value;
                            var thisTagTypeCodeID = thisTF.TagTypeCodeID;
                            var thisItemName = thisTF.ItemName;
                            var thisValue = thisTF.TagValue;

                            var pName = "Event_DeviceData_Update";
                            var sqlParameter = new SqlParameter[] {
                         new SqlParameter("@DeviceCode", opName),
                         new SqlParameter("@Online", true.ToString()),
                         new SqlParameter("@StationName", opName),
                         new SqlParameter("@TagTypeCodeID", thisTagTypeCodeID),
                         new SqlParameter("@ItemName", thisItemName),
                         new SqlParameter("@TagValue", thisValue),
                         new SqlParameter("@TagID", thisTagID),
                         new SqlParameter("@CreateTime", CreatTime),
                        };
                            MesWorkForm.taskSql.Enqueue(new NJ_ZC.ParamT
                            {
                                procedureName = pName,
                                sqlParameter = sqlParameter
                            });


                        }
                    }
                }
                catch (Exception err)
                {
                }
                Thread.Sleep(2000);
            }
        }

        static private void SelectData_WritePLC_Task()
        {
            while (true)
            {
                try
                {
                    B_DB_Opera.SelectData_WritePLC();
                }
                catch (Exception err)
                {
                }
                Thread.Sleep(5000);
            }
        }



        public static void WriteLog(string msg)
        {
            MW_Log.LoggerHelper.Info("Alarm", msg);
        }


    }
} 
