using BPA.Message;
using BPASmartClient.Device;
using BPASmartClient.EventBus;
using BPASmartClient.Helper;
using BPASmartClient.Http;
using BPASmartClient.Message;
using BPASmartClient.Model;
using BPASmartClient.Peripheral;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace BPASmartClient.Business
{
    /// <summary>
    /// 设备管理器，统一管理所有设备资源
    /// </summary>
    public class DeviceMgr : IPlugin
    {
        //设备集合
        private List<IDevice> devices = new List<IDevice>();

        public void Dispose()
        {
        }

        public void Initialize()
        {
        }

        public void Start()
        {
            LoadDevice();
        }

        public List<IDevice> GetDevices()
        {
            return devices;
        }

        /// <summary>
        /// 设备加载
        /// </summary>
        private void LoadDevice()
        {

            #region 启动设备对象

            var text = TextHelper.GetInstance.ReadTextInfo("StartShop", "DeviceConfig");
            string path = $"{LocaPath.GetInstance().GetDeviceConfigPath}{text}.json";
            if (File.Exists(path))
            {
                string JsonString = File.ReadAllText(path);
                var result = JsonConvert.DeserializeObject<ObservableCollection<DeviceConfigModelJson>>(JsonString);
                if (result != null)
                {
                    foreach (var shop in result)//店铺集合
                    {
                        foreach (var device in shop.deviceModels)//设备集合
                        {

                            string Namespace = device.DeviceNamespace.Substring(0, device.DeviceNamespace.LastIndexOf('.'));
                            var deviceTemp = Assembly.Load(Namespace).CreateInstance(device.DeviceNamespace) as IDevice;
                            deviceTemp.Name = device?.DeviceName;
                            deviceTemp.DeviceId = int.Parse(device.DeviceId);

                            //通讯模块
                            List<IPeripheral> peripherals = new List<IPeripheral>();
                            foreach (var comms in device.communicationDevcies)//通讯集合
                            {
                                string IPeripheralNamespace = comms.CommunicationNamespace.Substring(0, comms.CommunicationNamespace.LastIndexOf('.'));
                                var peripheralTemp = Assembly.Load(IPeripheralNamespace).CreateInstance(comms.CommunicationNamespace) as IPeripheral;
                                peripheralTemp.variables = comms.variables;
                                peripheralTemp.communicationPar = comms.communicationPar;
                                peripherals.Add(peripheralTemp);
                            }

                            deviceTemp.Initliaze(peripherals);
                            this.devices.Add(deviceTemp);
                        }
                    }
                }
            }

            #endregion



            //var devices = Plugin.GetInstance().GetPlugin<ConfigMgr>().GetDeviceConfigs();
            //foreach (var device in devices)
            //{
            //    var deviceTemp = Assembly.Load(device.Module.Substring(0, device.Module.LastIndexOf('.'))).CreateInstance(device.Module) as IDevice;
            //    deviceTemp.Name = device.Name;
            //    deviceTemp.DeviceId = device.DeviceId;
            //    foreach (var pars in device.Parameters)
            //    {
            //        deviceTemp.GetType().GetProperty(pars.Key).SetValue(deviceTemp, Convert.ChangeType(pars.Value, deviceTemp.GetType().GetProperty(pars.Key).PropertyType));
            //    }

            //    List<IPeripheral> peripherals = new List<IPeripheral>();
            //    foreach (var peripheral in device.Peripherals)
            //    {
            //        var peripheralTemp = Assembly.Load(peripheral.Module.Substring(0, peripheral.Module.LastIndexOf('.'))).CreateInstance(peripheral.Module) as IPeripheral;

            //        foreach (var pars in peripheral.Parameters)
            //        {
            //            peripheralTemp.GetType().GetProperty(pars.Key).SetValue(peripheralTemp, Convert.ChangeType(pars.Value, peripheralTemp.GetType().GetProperty(pars.Key).PropertyType));
            //        }
            //        peripherals.Add(peripheralTemp);
            //    }
            //    deviceTemp.Initliaze(peripherals);
            //    this.devices.Add(deviceTemp);
            //}
        }

        public void StartService()
        {
            this.devices.ForEach(device =>
            {
                device.StartMain();

                #region 获取物料数据
                string result = string.Empty;
                for (int i = 0; i < 2; i++)
                {
                    try
                    {
                        int PushType = i;//0:主料   1：辅料
                        int clientId = device.DeviceId;
                        var jsondata = new { clientId, PushType };
                        string header = $"[/stock/GetItemInfo]_[{DateTime.Now.Ticks}]".AESEncrypt();
                        string url = $"{InternetInfo.StockServer}GetItemInfo";
                        result = APIHelper.GetInstance.HttpRequest(url, header, jsondata, RequestType.POST);

                        if (PushType == 1)
                        {
                            new RecipeBomEvent()
                            {
                                DeviceId = device.DeviceId,
                                recipeBoms = JsonConvert.DeserializeObject<RecipeBoms>(result)
                            }.Publish();
                            MessageLog.GetInstance.Show("接收到【 API 】获取的辅料信息");
                        }
                        else if (PushType == 0)
                        {
                            var apiData = JsonConvert.DeserializeObject<OrderMaterialDelivery>(result);
                            new MaterialDeliveryEvent()
                            {
                                DeviceId = device.DeviceId,
                                orderMaterialDelivery = apiData
                            }.Publish();
                            MessageLog.GetInstance.Show("接收到【 API 】获取的物料信息");
                            apiData?.BatchingInfo?.ForEach(x =>
                            {
                                MessageLog.GetInstance.Show($"物料ID:=[{x.BatchingId}]，{x.BatchingLoc}号位置：{x.BatchingCount}");
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageLog.GetInstance.ShowEx(ex.ToString());
                    }
                }
                #endregion

            });
        }

        public void StopService()
        {
            this.devices.ForEach(device => device.Stop());
        }


    }
}
