using BPA.Message;
using BPASmartClient.Business;
using BPASmartClient.Control;
using BPASmartClient.CustomResource.UserControls;
using BPASmartClient.CustomResource.UserControls.MessageShow;
using BPASmartClient.Device;
using BPASmartClient.EventBus;
using BPASmartClient.Helper;
using BPASmartClient.IoT;
using BPASmartClient.Message;
using BPASmartClient.Model;
using BPASmartClient.Model.冰淇淋.Enum;
using BPASmartClient.Model.咖啡机.Enum;
using BPASmartClient.Peripheral;
using BPASmartClient.ViewModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BPASmartClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainConsole mainConsole;
        public MainWindow()
        {
            InitializeComponent();
            MainViewModel.GetInstance().window = this;
            this.DataContext = MainViewModel.GetInstance();
            ActionManage.GetInstance.Register(new Action(() =>
            {
                myMenu.Visibility = Visibility.Visible;
                MenuItem_Click(new MenuItem() { Tag = "LogView", Header = "日志监视" },null);
            }), "LoginSuccess");
            Initialize();
        }

        #region 私有
        /// <summary>
        /// 初始化
        /// </summary>
        private void Initialize()
        {
            this.ButClose.Click += (o, e) => { this.Close(); };
            this.br.MouseLeftButtonDown += (o, e) =>
            {
                if (e.ClickCount > 1)
                {
                    if (this.WindowState == WindowState.Maximized)
                        this.WindowState = WindowState.Normal;
                    else if (this.WindowState == WindowState.Normal)
                        this.WindowState = WindowState.Maximized;
                }
                if (e.LeftButton == MouseButtonState.Pressed) this.DragMove();
            };
            MenuItem_Click(new MenuItem() { Tag = "LogView", Header = "日志监视" }, null);

            ThreadManage.GetInstance().Start(new Action(() =>
            {
                mainConsole = new MainConsole();
                mainConsole.Start();
                GetDevices();
            }), "启动主控制台", false);

            ThreadManage.GetInstance().Start(new Action(() =>
            {
                try
                {
                    DataVClient.GetInstance().Initialize();
                    DataVClient.GetInstance().Start();
                }
                catch (Exception ex)
                {
                    MessageLog.GetInstance.ShowEx(ex.ToString());
                }
            }), "启动主IoT", false);

            ActionManage.GetInstance.Register(new Action<object>((o) =>
            {
                App.Current.Dispatcher.Invoke(new Action(() =>
                {
                    if (o is IOTCommandModel iot)
                    {
                        switch (iot.CommandName)
                        {
                            case 0://控制类
                                if (iot.CommandValue != null && iot.CommandValue.Count>0)
                                {
                                    switch (iot.CommandValue.Keys.ToList()[0])
                                    {
                                        case "程序启动":
                                            //mainConsole.Start();
                                            break;
                                            //mainConsole.Stop();
                                        case "程序停止":
                                            break;
                                        case "程序复位":
                                            //mainConsole.Stop();
                                            //mainConsole.Start();
                                            break;
                                        default:
                                            break;
                                    }
                                    NoticeDemoViewModel.OpenMsg(EnumPromptType.Info, MainViewModel.GetInstance().window, "大屏控制", iot.CommandValue.Keys.ToList()[0]);
                                }
                                break;
                            case 1://设置类
                                break;
                            case 2://通知类
                                if (iot.CommandValue != null && iot.CommandValue.ContainsKey("text"))
                                {
                                    NoticeDemoViewModel.OpenMsg(EnumPromptType.Info, MainViewModel.GetInstance().window, "大屏通知", iot.CommandValue["text"]);
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }));
            }), "IotBroadcast");
        }
        /// <summary>
        /// 获取设备集合
        /// </summary>
        private void GetDevices()
        {
            //List<string> IDevices = new List<string>();
            //List<string> IPeripherals = new List<string>();

            DirectoryInfo directoryInfo = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
            var files = directoryInfo.GetFiles().Where(p => p.FullName.Contains("BPASmartClient.") && p.FullName.Contains("dll")).ToList();
            List<string> fileList = new List<string>();

            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            var dlls = assemblies?.Where(p => p.FullName.Contains("BPASmartClient.")).ToList();
            List<string> dllList = new List<string>();

            if (files != null)
            {
                foreach (var item in files)
                {
                    var res = System.IO.Path.GetFileNameWithoutExtension(item.FullName);
                    if (res != null && res.Length > 0 && res.Contains(".") && !res.Contains("dll")) fileList.Add(res);
                }
            }

            if (dlls != null)
            {
                dlls.ForEach((item) =>
                {
                    item.GetTypes().ToList().ForEach((type) =>
                    {
                        if (type.GetInterfaces().Contains(typeof(IDevice)))
                        {
                            if (!type.FullName.Contains("BaseDevice")) ShopDeviceConfigViewModel.IDevices.Add(type.FullName);
                        }
                        else if (type.GetInterfaces().Contains(typeof(IPeripheral)))
                        {
                            if (!type.FullName.Contains("BasePeripheral")) ShopDeviceConfigViewModel.IPeripherals.Add(type.FullName);
                        }
                    });

                    dllList.Add(System.IO.Path.GetFileNameWithoutExtension(item.EscapedCodeBase));
                });
            }

            dllList.ForEach((item) => { if (fileList.Contains(item)) fileList.Remove(item); });

            fileList.ForEach((item) =>
            {
                Assembly.Load(item).GetTypes().ToList().ForEach((type) =>
                {
                    if (type.GetInterfaces().Contains(typeof(IDevice)))
                    {
                        if (!type.FullName.Contains("BaseDevice")) ShopDeviceConfigViewModel.IDevices.Add(type.FullName);
                    }
                    else if (type.GetInterfaces().Contains(typeof(IPeripheral)))
                    {
                        if (!type.FullName.Contains("BasePeripheral")) ShopDeviceConfigViewModel.IPeripherals.Add(type.FullName);
                    }
                });
            });

        }
        #endregion

        #region Click
        /// <summary>
        /// 菜单切换栏
        /// </summary>
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (sender is MenuItem)
                {
                    Type type = Type.GetType($"BPASmartClient.Control.{(sender as MenuItem).Tag?.ToString()}");
                    if (type == null) { MenuClick((sender as MenuItem).Tag?.ToString()); return; }
                    ConstructorInfo cti = type.GetConstructor(System.Type.EmptyTypes);
                    contentRegion.Content = (FrameworkElement)cti.Invoke(null);
                    Title.Text = (sender as MenuItem).Header?.ToString() + "界面";
                }
            }
            catch (Exception ex)
            {
                MessageLog.GetInstance.ShowEx($"BPASmartClient 中引发错误,MainWindow.xaml.cs 类MenuItem_Click(),描述：[{ex.Message}]");
            }
        }
        #endregion

        #region 公用
        /// <summary>
        /// 菜单点击
        /// </summary>
        /// <param name="name"></param>
        public void MenuClick(string name)
        {
            try
            {
                switch (name)
                {
                    case "Close":
                        this.Close();
                        break;
                    case "IOT":
                        BrowserHelper.OpenDefaultBrowserUrl("http://iot.black-pa.com");
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageLog.GetInstance.ShowEx($"BPASmartClient 中引发错误,MainWindow.xaml.cs 类MenuClick(),描述：[{ex.Message}]");
            }
        }
        #endregion

        #region 临时测试代码
        /// <summary>
        /// 测试按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //new Demo_MakeCoffeeEvent() { Id = 1 }.Publish();
            //new DRCoffee_MakeCoffeeEvent() { Id = 1, DrinkCode= DrCoffeeDrinksCode.两杯意式浓缩 }.Publish();
            //new DRCoffee_CoffeeCommCmdEvent() { Id = 1,CommCmd = DrCoffeeCommCmd.冲煮系统快速冲洗指令}.Publish();

            MorkOrderPush morkOrderPush = new MorkOrderPush() { DeviceId = 2 };
            var temp = BPAPackage.Make(morkOrderPush, 12, BPA.Message.Enum.DeviceClientType.MORKS);
            Plugin.GetInstance().GetPlugin<MQTTMgr>().Publish("DOWN/MORKS/ORDER/12", temp.Serialize());
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void init_Click(object sender, RoutedEventArgs e)
        {
            ActionManage.GetInstance.Send("InitDevice");
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Login(object sender, RoutedEventArgs e)
        {
            try
            {
                Type type = Type.GetType($"BPASmartClient.Control.AdminstratorsView");
                if (type == null) { MenuClick((sender as MenuItem).Tag?.ToString()); return; }
                ConstructorInfo cti = type.GetConstructor(System.Type.EmptyTypes);
                contentRegion.Content = (FrameworkElement)cti.Invoke(null);
                Title.Text = "管理员登录界面";
            }
            catch (Exception ex)
            {

                MessageLog.GetInstance.ShowEx($"BPASmartClient 中引发错误,MainWindow.xaml.cs 类MenuItem_Click(),描述：[{ex.Message}]");
            }

        }
        /// <summary>
        /// 注销
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_LogOut(object sender, RoutedEventArgs e)
        {
            myMenu.Visibility = Visibility.Hidden;
        }
        #endregion

    }
}
