using Prism.Regions;
using System.Collections.Generic;
using System.Windows;
using Venus_Themes.CustomControls;
using Venus_UI.Themes.Attach;
using Venus_Unity;
using System.Linq;
using System.Threading;
using System;
using Venus_MainPages.Views;
using System.Windows.Controls;
using Aitex.Core.UI.View.Frame;
using System.Windows.Media;
using Venus_Core;
using System.Reflection;
using Venus_MainPages.Unity;
using MECF.Framework.Common.DataCenter;
using Aitex.Core.RT.SCCore;
using MECF.Framework.Common.OperationCenter;
using Aitex.Core.RT.OperationCenter;
using Venus_MainPages.ViewModels;
using MECF.Framework.Common.CommonData;
using System.Windows.Controls.Primitives;
using System.Timers;
using System.Windows.Threading;
using Venus_Themes.Unity;

namespace Venus_UI.Views
{
    /// <summary>
    /// ShellView.xaml 的交互逻辑
    /// </summary>
    public partial class ShellView : Window
    {
        IRegionManager m_regionManager;
        IRegionNavigationService m_regionNavigationService;
        List<VenusMenu> VenusMenu;
        List<TabControl>  centerTabViews=new List<TabControl> ();
        List<Button> buttonList=new List<Button> ();
        DispatcherTimer timer = new DispatcherTimer();

        public ShellView(IRegionManager regionManager, IRegionNavigationService regionNavigationService)
        {

            InitializeComponent();
            m_regionManager = regionManager;
            m_regionNavigationService = regionNavigationService;

            m_regionManager.RegisterViewWithRegion("TopRegion", typeof(Venus_MainPages.Views.TopView));

            VenusGlobalEvents.SlotRightClickChangedEvent += Instance_SlotRightClickChangedEvent;
            VenusGlobalEvents.SlotWaferTransferEvent += Instance_SlotStartTransferEvent;
            timer.Tick += timer_Tick;
            timer.Interval = TimeSpan.FromSeconds(0.5);
            timer.Start();
            UIEvents.PMDoorRaiseChangedEvent += UIEvents_PMDoorRaiseChangedEvent;

            UIEvents.LLTDoorRaiseChangedEvent += UIEvents_LLTDoorRaiseChangedEvent;

            UIEvents.LLEDoorRaiseChangedEvent += UIEvents_LLEDoorRaiseChangedEvent;

            UIEvents.ChamberCreateDeleteWaferEvent += UIEvents_ChamberCreateDeleteWaferEvent;
        }
        void timer_Tick(object sender, EventArgs e)
        {
            if (Anychange.needchange)
            {
                Anystationchange(Anychange.menuname, Anychange.args);
                Anychange.needchange=false;
            }
        }
        private void Instance_SlotRightClickChangedEvent(OpenSEMI.Ctrlib.Controls.Slot slot)
        {
            if (slot != null)
            {
                ContextMenu cm = ContextMenuManager.Instance.GetSlotMenus(slot);
                if (cm != null)
                {
                    slot.ContextMenu = cm;
                }

                return;
            }
        }

        private void Instance_SlotStartTransferEvent(OpenSEMI.Ctrlib.Controls.DragDropEventArgs e)
        {
            InvokeClient.Instance.Service.DoOperation("System.MoveWafer",
                e.TranferFrom.ModuleID,e.TranferFrom.SlotID, e.TranferTo.ModuleID, e.TranferTo.SlotID,false,1,false,1,"");
            e.TranferFrom.ClearDragDropStatus();
            e.TranferTo.ClearDragDropStatus();
        }

        private void CustomWnd_Loaded(object sender, RoutedEventArgs e)
        {
            VenusMenu = SerializeHelper.Instance.ReadFromJsonFile<List<VenusMenu>>($"Config/UIMenu.json");            
            int index = 0;
            for (int i = 0; i < VenusMenu.Count; i++)
            {
                if (VenusMenu[i].IsShow == false)
                { 
                    continue;
                }
                string[] allModules = QueryDataClient.Instance.Service.GetConfig($"System.InstalledModules").ToString().Split(',');
                if (VenusMenu[i].Id == "PMA" || VenusMenu[i].Id == "PMB" || VenusMenu[i].Id == "PMC" || VenusMenu[i].Id == "PMD" || VenusMenu[i].Id == "TM")
                {
                    if (!allModules.Contains(VenusMenu[i].Id))
                    {
                        continue;
                    }
                }
                    AduRadioButtonIcon aduRadioButtonIcon = new AduRadioButtonIcon();
                if (i == 0)
                {
                    aduRadioButtonIcon.IsChecked = true;
                }
                IconElement.SetPathData(aduRadioButtonIcon,(Geometry)aduRadioButtonIcon.FindResource($"Icon_{VenusMenu[i].Id}"));
                aduRadioButtonIcon.Content = VenusMenu[i].Id;
                aduRadioButtonIcon.Click += AduRadioButtonIcon_Click;
                aduRadioButtonIcon.SelectBackground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#6AD7FF"));
                aduRadioButtonIcon.SelectColor = new SolidColorBrush((Colors.Black));
                aduRadioButtonIcon.DefaultBackground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#94BCD7"));
                //aduRadioButtonIcon.DefaultBackground = new SolidColorBrush(Colors.DarkGray);
                

                aduRadioButtonIcon.Width = 180;
                aduRadioButtonIcon.Height= 40;
                
                //aduRadioButtonIcon.Foreground=Brushes.White;
                aduRadioButtonIcon.Tag = index;
                index += 1;
                Bottom_Frame.Children.Add(aduRadioButtonIcon);
                //if (VenusMenu[i].Id == "PMC")
                //{
                //    AduRadioButtonIcon aduRadioButtonIcon2 = new AduRadioButtonIcon();
                   
                //    IconElement.SetPathData(aduRadioButtonIcon2, (Geometry)aduRadioButtonIcon.FindResource($"Icon_{VenusMenu[i].Id}"));
                //    aduRadioButtonIcon2.Content = "PMD";
                //    //aduRadioButtonIcon2.Click += AduRadioButtonIcon_Click;
                //    aduRadioButtonIcon2.SelectBackground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#6AD7FF"));
                //    aduRadioButtonIcon2.SelectColor = new SolidColorBrush((Colors.Black));
                //    aduRadioButtonIcon2.DefaultBackground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#94BCD7"));
                //    //aduRadioButtonIcon.DefaultBackground = new SolidColorBrush(Colors.DarkGray);


                //    aduRadioButtonIcon2.Width = 180;
                //    aduRadioButtonIcon2.Height = 40;
                //    Bottom_Frame.Children.Add(aduRadioButtonIcon2);
                //}
                TabControl tabControl = new TabControl();
                for (int j = 0; j < VenusMenu[i].MenuItem.Count; j++)
                {
                    if (VenusMenu[i].MenuItem[j].IsShow == false)
                    {
                        continue;
                    }
                    string className;
                    if ((VenusMenu[i].Id == "PMA" || VenusMenu[i].Id == "PMB" || VenusMenu[i].Id == "PMC" || VenusMenu[i].Id == "PMD")&& VenusMenu[i].MenuItem[j].Id== "Operation")
                    {
                        JetChamber jetChamber = (JetChamber)(Convert.ToInt32(QueryDataClient.Instance.Service.GetConfig($"{VenusMenu[i].Id}.ChamberType")));
                        className = $"Venus_MainPages.Views.Over{jetChamber.ToString()}View";
                    }
                    else
                    {
                        className = $"Venus_MainPages.Views.{VenusMenu[i].MenuItem[j].View}";
                    }

                    Type t = Type.GetType($"{className},Venus_MainPages");
                    var obj = System.Activator.CreateInstance(t);
                    

                    if (VenusMenu[i].Id=="PMA" || VenusMenu[i].Id == "PMB" || VenusMenu[i].Id == "PMC" || VenusMenu[i].Id == "PMD" || VenusMenu[i].Id == "TM")
                    {                     
                        MethodInfo methodInfo = t.GetMethod("Init", new Type[] { typeof(string) });
                        methodInfo?.Invoke(obj, new object[] { VenusMenu[i].Id });
                    }
                    tabControl.Items.Add(new TabItem() { Header = VenusMenu[i].MenuItem[j].Name, Content = obj });
                }
                centerTabViews.Add(tabControl);               
            }
            Main_Frame.Content = centerTabViews[0];
            ModuleManager.Initialize();

        }
         
        public void Anystationchange(string menuviewItem, WaferHistoryWafer queryFilter)
        {
            UserControl address = new ProcessHistoryView();          
            ProcessHistoryViewModel vm = new ProcessHistoryViewModel() {};
            vm.SearchRecipe(queryFilter.StartTime, queryFilter.EndTime);
            vm.OnDataGridSelectionChanged(new Venus_MainPages.ViewModels.RecipeItem { StartTime=queryFilter.StartTime, EndTime= queryFilter.EndTime});
            address.DataContext = vm;
            centerTabViews.Last().Items[2]= new TabItem() { Header = menuviewItem, Content = address };
            centerTabViews.Last().SelectedIndex = 2;
            Main_Frame.Content = centerTabViews.Last();
        }
        private void AduRadioButtonIcon_Click(object sender, RoutedEventArgs e)
        {
            var currentButton = sender as AduRadioButtonIcon;
            Main_Frame.Content = centerTabViews[Convert.ToInt32(currentButton.Tag)];
        }

        private void CustomWnd_Closed(object sender, EventArgs e)
        {
            System.Diagnostics.Process.GetCurrentProcess().Kill();
        }
        private void UIEvents_ChamberCreateDeleteWaferEvent(WaferOperation obj)
        {
            if (obj.IsCreate == true)
            {
                InvokeClient.Instance.Service.DoOperation("CreateWafer", obj.ModuleName, 0);
            }
            else
            {
                InvokeClient.Instance.Service.DoOperation("DeleteWafer", obj.ModuleName, 0);
            }
        }
        private void UIEvents_PMDoorRaiseChangedEvent(DoorPara obj)
        {
            //InvokeClient.Instance.Service.DoOperation($"{obj?.ModuleName}.SlitDoor.{obj?.IsOpen}");
            InvokeClient.Instance.Service.DoOperation($"{obj?.ModuleName}.SetSlitDoor", obj.IsOpen == "Open" ? true : false);
        }
        private void UIEvents_LLTDoorRaiseChangedEvent(DoorPara obj)
        {
            InvokeClient.Instance.Service.DoOperation($"TM.SetMFSlitDoor", obj.ModuleName, obj.IsOpen == "Open" ? true : false);
        }
        private void UIEvents_LLEDoorRaiseChangedEvent(DoorPara obj)
        {
            InvokeClient.Instance.Service.DoOperation($"TM.SetEFEMSlitDoor", obj.ModuleName, obj.IsOpen == "Open" ? true : false);
        }
    }
}