using HBLConsole.Abstract;
using HBLConsole.Interface;
using System;
using System.Reflection;
using BPA.Message.Enum;
using HBLConsole.GVL;
using BPA.Message;
using HBLConsole.Service;
using HBLConsole.Communication;

namespace HBLConsole.Factory
{
    public class SimpleFactory
    {

        private volatile static SimpleFactory _Instance;
        public static SimpleFactory GetInstance => _Instance ?? (_Instance = new SimpleFactory());
        private SimpleFactory() { ActionManage.GetInstance.Register(new Action(() => { GetInterfaceData(); }), "ResetProgram"); }

        public AbstractMessageServer GetAbsMessageServer => _GetAbsMessageServer ?? (_GetAbsMessageServer = GetAbstractMessageServer());
        private AbstractMessageServer _GetAbsMessageServer;

        private string DeviceType => GeneralConfig.DeviceType.ToString();

        private object debugControl;

        public void MqttMessage(IMessage message)
        {
            GetAbsMessageServer.AddOrder(message);
            GetAbsMessageServer.GetBatchingInfo(message);
            GetAbsMessageServer.GetRecipeBom(message);
        }

        /// <summary>
        /// 获取物料信息
        /// </summary>
        public void GetBatchingInfo()
        {
            GetAbsMessageServer.GetBatchingInfo(InternetInfo.ClientId);
        }

        /// <summary>
        /// 订单状态更改
        /// </summary>
        /// <param name="subid"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public bool OrderChanged(string subid, ORDER_STATUS status)
        {
            bool res = GetAbsMessageServer.OrderStatusChange(subid, status);
            if (res)
            {
                ActionManage.GetInstance.Send("OrderStatusChange", new OrderStatusChange()
                {
                    CookingStatus = status,
                    SuborderId = subid
                });
            }
            return res;
        }

        private AbstractMessageServer GetAbstractMessageServer()
        {
            string NameSpace = "HBLConsole.Business";
            Type type = Assembly.Load(NameSpace).GetType($"{NameSpace}.MessageServer.{DeviceType}");
            if (type == null)
                type = Assembly.Load(NameSpace).GetType($"{NameSpace}.MessageServer.Base");
            return Activator.CreateInstance(type) as AbstractMessageServer;
        }

        public IControl control { get; set; }
        public IGvl GVL { get; set; }
        public IAlarm Alarm { get; set; }


        /// <summary>
        /// 设备初始化
        /// </summary>
        public void DeviceInit()
        {
            string NameSpace = $"HBLConsole.{DeviceType}";//Load 加载的是dll的名称，GetType获取的是全命名空间下的类
            Type type = Assembly.Load(NameSpace).GetType($"{NameSpace}.Control_{DeviceType}");
            control = Activator.CreateInstance(type) as IControl;
            //control = (IControl)type?.GetProperty("Instance").GetValue(null);
            //IControl business = (IControl)type?.GetProperty("GetInstance").GetValue(null);
            GetBatchingInfo();
            GetInterfaceData();
            control?.Init();
            ActionManage.GetInstance.Register(new Action<object>((o) => { control?.DataParse(o); }), "DataParse");
            ActionManage.GetInstance.Register(new Action(() => { control?.ConnectOk(); }), $"{GeneralConfig.DeviceType.ToString()}/ConnectOk");
            ActionManage.GetInstance.Register(new Action<object>((o) => { control?.SimOrder(o); }), "SimOrder");
            ActionManage.GetInstance.Register(new Action<object>((o) => { control?.IotBroadcast(o); }), "IotBroadcast");
            ConnectHelper.GetInstance.Init();

        }

        /// <summary>
        /// 获取接口数据
        /// </summary>
        private void GetInterfaceData()
        {
            Type type = control?.GetType();

            //通过字段查找
            var Fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (Fields != null)
            {
                foreach (var item in Fields)
                {
                    var interfaces = item.FieldType.GetInterfaces();
                    if (interfaces != null)
                    {
                        foreach (var inters in interfaces)
                        {
                            if (inters.Name.Equals("IGvl"))
                            {
                                GVL = (item.GetValue(control)) as IGvl;
                            }
                            else if (inters.Name.Equals("IAlarm"))
                            {
                                Alarm = (item.GetValue(control)) as IAlarm;
                            }
                        }
                    }
                }
            }

            //if (GVL != null && Alarm != null) return;

            ////通过属性查找
            //var prop = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            //if (prop != null)
            //{
            //    foreach (var item in prop)
            //    {
            //        var interfaces = item.PropertyType.GetInterfaces();
            //        if (interfaces != null)
            //        {
            //            foreach (var inters in interfaces)
            //            {
            //                if (inters.Name.Equals("IGvl"))
            //                {
            //                    GVL = (type?.GetProperty(item.Name).GetValue(control, null)) as IGvl;
            //                }
            //                else if (inters.Name.Equals("IAlarm"))
            //                {
            //                    Alarm = (type?.GetProperty(item.Name).GetValue(control, null)) as IAlarm;
            //                }
            //            }
            //        }
            //    }
            //}

            //return default;
        }


        public object GetDebugControl()
        {
            if (null == debugControl)
            {
                debugControl = Assembly.Load("HBLConsole.Debug").CreateInstance($"HBLConsole.Debug.Debug_{DeviceType}");
            }
            return debugControl;
        }
    }
}
