using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Simple3.RCS;
using Simple3.RCS.CarTypes;
using SimpleCore;
using Newtonsoft.Json;
using Simple3.CADTools;
using Simple3.Props;
using Simple3.UI;
using SimpleCore.Library;
using System.Threading.Tasks;
using System.Diagnostics;
using IoTClient.Clients.PLC;
using IoTClient.Enums;
using SimpleCore.Traffic;
using SimpleCore.PropType;
using System.Net.Http;
using System.Reflection;
using LessokajiWeaverUtilities.Utilities;


namespace StandardScene.Scheduler
{
    [MissionType(Name = "安全信号交互", editor = typeof(SecuritySignalMission))]
    [I18N.DocumentTranslation(Name = "Security Signal Mission", locale = "en")]
    public class SecuritySignalMission : Mission
    {
        public static Mission Create()
        {
            return new SecuritySignalMission();
        }

        public int[] stringToInt(string str)
        {
            return str.Split(' ').Select(s => (int)Convert.ToInt16(s, 10)).ToArray();
        }

        public class NOdeIsEnableMissionStatus : MissionStatus
        {
            public static List<string> staions = new List<string>() { "One","Two","Three","Four","Five"};
            public static List<string> signalDB = new List<string>() { "beat", "request", "allowRequest", "entering", "inplace","requestLeave" ,"allowLeave","leaving","safeLeave","AGVAlarm","PlcAlarm"};
   
            public  List<bool> One = Enumerable.Repeat(false, signalDB.Count()).ToList();

            public Dictionary<string, Dictionary<string,bool>> signal = new Dictionary<string, Dictionary<string, bool>>();

          
            public  List<bool> Two = Enumerable.Repeat(false, signalDB.Count()).ToList();

        
            public  List<bool> Three = Enumerable.Repeat(false, signalDB.Count()).ToList();
            public  List<bool> Four = Enumerable.Repeat(false, signalDB.Count()).ToList();

         
            public   List<bool> Five = Enumerable.Repeat(false, signalDB.Count()).ToList();
            public  List<bool> Six = Enumerable.Repeat(false, signalDB.Count()).ToList();
            public  List<bool> Seven = Enumerable.Repeat(false, signalDB.Count()).ToList();
            public  List<bool> Eight = Enumerable.Repeat(false, signalDB.Count()).ToList();
            public float readOnceTime = 0;
            public float readAllDataTime = 0;
            public float writeOnceTime = 0;
            public float writeAllDataTime = 0;


        }

        public override MissionStatus status { get; set; } = new NOdeIsEnableMissionStatus();

     
        [JsonIgnore] public Thread myThread;

        [JsonIgnore] private bool started = false;

        [JsonIgnore] private int iterationComm = 0;


        [JsonIgnore] private object sync = new();
        [JsonIgnore] public static HttpClient hc = new HttpClient() { Timeout = TimeSpan.FromSeconds(2) };

        [MethodMember(Name = "启动进程", Description = "开始处理上下料队列")]
        public override void Execute()
        {
            started = true;
            Task.Factory.StartNew(() => {
                HttpPostData httpPostData = new HttpPostData();
                 Dictionary<string, Dictionary<string, bool>> Allsignal = new Dictionary<string, Dictionary<string, bool>>();
                //Dictionary<string, bool> stationSignals = new Dictionary<string, bool>();
                while (started)
                {
                    try
                    {

                        foreach (var station in NOdeIsEnableMissionStatus.staions)
                        {
                           Dictionary<string, bool> stationSignals = new Dictionary<string, bool>();
                            foreach (var signalName in NOdeIsEnableMissionStatus.signalDB)
                            {
                                // 根据station和signalName获取对应的bool值
                                bool signalValue;
                                switch (station)
                                {
                                    case "One":
                                        signalValue = ((NOdeIsEnableMissionStatus)status).One[(NOdeIsEnableMissionStatus.signalDB).IndexOf(signalName)];
                                        break;
                                    case "Two":
                                        signalValue = ((NOdeIsEnableMissionStatus)status).Two[(NOdeIsEnableMissionStatus.signalDB).IndexOf(signalName)];
                                        break;
                                    case "Three":
                                        signalValue = ((NOdeIsEnableMissionStatus)status).Three[(NOdeIsEnableMissionStatus.signalDB).IndexOf(signalName)];
                                        break;
                                    case "Four":
                                        signalValue = ((NOdeIsEnableMissionStatus)status).Four[(NOdeIsEnableMissionStatus.signalDB).IndexOf(signalName)];
                                        break;
                                    case "Five":
                                        signalValue = ((NOdeIsEnableMissionStatus)status).Five[(NOdeIsEnableMissionStatus.signalDB).IndexOf(signalName)];
                                        break;
                                    case "Six":
                                        signalValue = ((NOdeIsEnableMissionStatus)status).Six[(NOdeIsEnableMissionStatus.signalDB).IndexOf(signalName)];
                                        break;
                                    case "Seven":
                                        signalValue = ((NOdeIsEnableMissionStatus)status).Seven[(NOdeIsEnableMissionStatus.signalDB).IndexOf(signalName)];
                                        break;
                                    case "Eight":
                                        signalValue = ((NOdeIsEnableMissionStatus)status).Eight[(NOdeIsEnableMissionStatus.signalDB).IndexOf(signalName)];
                                        break;
                                    default:
                                        throw new Exception("Invalid station name");
                                }
                               
                                // 检查字典中是否存在指定的键，如果存在则修改其值，否则添加新的键值对
                                if (stationSignals.ContainsKey(signalName))
                                {
                                    stationSignals[signalName] = signalValue;
                                }
                                else
                                {
                                    stationSignals.Add(signalName, signalValue);
                                }
                            }
                            if (Allsignal.ContainsKey(station))
                            {
                                Allsignal[station] = stationSignals;
                            }
                            else {
                                Allsignal.Add(station, stationSignals);
                            }
                            
                        }
                        string result=JsonConvert.SerializeObject(Allsignal);
                        //string result = GetListsAsStrings((NOdeIsEnableMissionStatus)status);

                      
                        Diagnosis.Log($"向迷毂提供安全信号---{result}", "signalinfo", true);
                       

                        httpPostData.UploadSignal(result);
                        Thread.Sleep(500);
                    }
                    catch (Exception e)
                    {

                        Diagnosis.Post($"{ExceptionFormatter.FormatEx(e)}", "安全信号");
                    }
                 
                }


            });
        }

        [MethodMember(Name = "关闭机构进程", Description = "关闭机构进程")]
        public override void Stop()
        {
            started = false;
            status.status = $"已停止-循环";
        }
        Stopwatch stopwatch3 = new Stopwatch();
        Stopwatch stopwatch2 = new Stopwatch();


        public static string GetListsAsStrings(object obj)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            Type type = obj.GetType();
            FieldInfo[] fieldInfo= type.GetFields();
            foreach (FieldInfo property in fieldInfo)
            {
                if (property.FieldType== typeof(List<bool>))
                {
                    List<bool> list = (List<bool>)property.GetValue(obj);
                    result[property.Name] = String.Join(",", list.Select(b => b ? "1" : "0"));
                    
                }
            }
            return JsonConvert.SerializeObject(result);
        }

    }
}
