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

namespace HBLConsole.Factory
{
    public class SimpleFactory
    {

        private volatile static SimpleFactory _Instance;
        public static SimpleFactory GetInstance => _Instance ?? (_Instance = new SimpleFactory());
        private SimpleFactory() { }

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

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

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

        /// <summary>
        /// 获取物料信息
        /// </summary>
        public void GetBatchingInfo()
        {
            GetAbsMessageServer.GetBatchingInfo(InternetInfo.GetInstance.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)
            {
                ActionManagerment.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 (AbstractMessageServer)Activator.CreateInstance(type);
        }

        /// <summary>
        /// 设备初始化
        /// </summary>
        public void DeviceInit()
        {
            string NameSpace = "HBLConsole.Business";//Load 加载的是dll的名称，GetType获取的是全命名空间下的类
            Type type = Assembly.Load(NameSpace).GetType($"{NameSpace}.Devices.{DeviceType}");
            IBusiness business = (IBusiness)type?.GetProperty("GetInstance").GetValue(null);
            business?.Init();
        }

        public IGvl GetGvl()
        {
            Type type = Assembly.Load("HBLConsole.GVL").GetType($"HBLConsole.GVL.{DeviceType}");
            return (IGvl)Activator.CreateInstance(type);
        }
    }
}
