using Aitex.Core.RT.Fsm;
using Aitex.Core.Util;
using MECF.Framework.Common.CommonData;
using MECF.Framework.Common.DataCenter;
using MECF.Framework.Common.Equipment;
using MECF.Framework.Common.Layout;
using MECF.Framework.Common.ProcessCell;
using MECF.Framework.Common.Reservior;
using MECF.Framework.Common.Utilities;
using PunkHPX8_Core;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
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;
using System.Windows.Threading;
using System.Runtime.InteropServices;
namespace PunkHPX8_Themes.UserControls
{
    /// 
    /// ProcessControl.xaml 的交互逻辑
    /// 
    public partial class ProcessControl : UserControl
    {
        #region 常量
        private const int RESERVIOR_MARGIN_LEFT = 10;
        #endregion
        
        public ProcessControl()
        {
            InitializeComponent();
        }
        public static readonly DependencyProperty ControlLoadProperty = DependencyProperty.Register("ControlLoad", typeof(bool), typeof(ProcessControl),
        new PropertyMetadata(false));
        public bool ControlLoad
        {
            get { return (bool)this.GetValue(ControlLoadProperty); }
            set
            {
                this.SetValue(ControlLoadProperty, value);
            }
        }
        public static readonly DependencyProperty LoaderTransoprterWaferHolderVisibleProperty = DependencyProperty.Register("LoaderTransoprterWaferHolderVisible", typeof(bool), typeof(ProcessControl),
        new PropertyMetadata(false));
        public bool LoaderTransoprterWaferHolderVisible
        {
            get { return (bool)this.GetValue(LoaderTransoprterWaferHolderVisibleProperty); }
            set
            {
                this.SetValue(LoaderTransoprterWaferHolderVisibleProperty, value);
            }
        }
        public static readonly DependencyProperty LoaderGantryPositionProperty = DependencyProperty.Register("LoaderGantryPosition", typeof(double), typeof(ProcessControl));
        public double LoaderGantryPosition
        {
            get { return (double)this.GetValue(LoaderGantryPositionProperty); }
            set
            {
                this.SetValue(LoaderGantryPositionProperty, value);
            }
        }
        public static readonly DependencyProperty ProcessGantryPositionProperty = DependencyProperty.Register("ProcessGantryPosition", typeof(double), typeof(ProcessControl),new PropertyMetadata((double)1725));
        public double ProcessGantryPosition
        {
            get { return (double)this.GetValue(ProcessGantryPositionProperty); }
            set
            {
                this.SetValue(ProcessGantryPositionProperty, value);
            }
        }
        public static readonly DependencyProperty LoaderVerticalPositionProperty = DependencyProperty.Register("LoaderVerticalPosition", typeof(double), typeof(ProcessControl), new PropertyMetadata((double)100));
        public double LoaderVerticalPosition
        {
            get { return (double)this.GetValue(LoaderVerticalPositionProperty); }
            set
            {
                this.SetValue(LoaderVerticalPositionProperty, value);
            }
        }
        public static readonly DependencyProperty ProcessVerticalPositionProperty = DependencyProperty.Register("ProcessVerticalPosition", typeof(double), typeof(ProcessControl), new PropertyMetadata((double)100));
        public double ProcessVerticalPosition
        {
            get { return (double)this.GetValue(ProcessVerticalPositionProperty); }
            set
            {
                this.SetValue(ProcessVerticalPositionProperty, value);
            }
        }
        public static readonly DependencyProperty ProcessTransoprterWaferHolderVisibleProperty = DependencyProperty.Register("ProcessTransoprterWaferHolderVisible", typeof(bool), typeof(ProcessControl),
     new PropertyMetadata(true));
        public bool ProcessTransoprterWaferHolderVisible
        {
            get { return (bool)this.GetValue(ProcessTransoprterWaferHolderVisibleProperty); }
            set
            {
                this.SetValue(ProcessTransoprterWaferHolderVisibleProperty, value);
            }
        }
        public static readonly DependencyProperty LoaderTransoprterWaferHolderEnableProperty = DependencyProperty.Register("LoaderTransoprterWaferHolderEnable", typeof(bool), typeof(ProcessControl),
        new PropertyMetadata(true));
        public bool LoaderTransoprterWaferHolderEnable
        {
            get { return (bool)this.GetValue(LoaderTransoprterWaferHolderEnableProperty); }
            set
            {
                this.SetValue(LoaderTransoprterWaferHolderEnableProperty, value);
            }
        }
        public static readonly DependencyProperty ProcessTransoprterWaferHolderEnableProperty = DependencyProperty.Register("ProcessTransoprterWaferHolderEnable", typeof(bool), typeof(ProcessControl),
     new PropertyMetadata(false));
        public bool ProcessTransoprterWaferHolderEnable
        {
            get { return (bool)this.GetValue(ProcessTransoprterWaferHolderEnableProperty); }
            set
            {
                this.SetValue(ProcessTransoprterWaferHolderEnableProperty, value);
            }
        }
        private ConcurrentDictionary _cellWaferHolderDictionary=new ConcurrentDictionary();
        /// 
        /// RT查询data集合
        /// 
        private Dictionary _rtDataValues;
        /// 
        /// RT查询key集合
        /// 
        private List _rtDataKeys = new List();
        /// 
        /// layout对象
        /// 
        private ProcessLayout _processLayout;
        /// 
        /// Reservoir-Metals
        /// 
        private SerializableDictionary> _reservoirMetals;
        /// 
        /// 定时器
        /// 
        DispatcherTimer _timer = null;
        /// 
        /// 可见变化事件
        /// 
        /// 
        /// 
        private void UserControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if(!ControlLoad)
            {
                return;
            }
            if (e.NewValue != null)
            {
                bool isShow = (bool)e.NewValue;
                if (isShow)
                {
                    LoadCells();
                    if (_timer == null)
                    {
                        _timer = new DispatcherTimer();
                        _timer.Interval = TimeSpan.FromSeconds(0.2);
                        _timer.Tick += Timer_Tick;
                    }
                    InitialKeys();
                    _timer.Start();
                }
                else
                {
                    if (_timer != null)
                    {
                        _timer.Stop();
                        _timer.IsEnabled = false;
                        _timer = null;
                    }                
                }
            }
        }
        private void LoadCells()
        {
            _rtDataKeys.Clear();
            _rtDataKeys.Add("System.Layout");
            _rtDataKeys.Add("System.ReservoirMetals");
            _rtDataValues = QueryDataClient.Instance.Service.PollData(_rtDataKeys);
            if (_rtDataValues != null)
            {
                _processLayout = CommonFunction.GetValue(_rtDataValues, "System.Layout");
                _reservoirMetals = CommonFunction.GetValue>>(_rtDataValues, "System.ReservoirMetals");
                if (_processLayout != null && _processLayout.Items.Count != 0)
                {
                    totalCanvas.Children.Clear();
                    foreach (ProcessLayoutCellItem item in _processLayout.Items)
                    {
                        if (string.IsNullOrEmpty(item.ModuleName))
                        {
                            continue;
                        }
                        if (item.Type == "Cell")
                        {
                            AddCellControl(item);
                        }
                        else if (item.Type == "Buffer")
                        {
                            
                        }
                    }
                }
                if (_reservoirMetals != null && _reservoirMetals.Keys.Count != 0)
                {
                    foreach(string item in _reservoirMetals.Keys)
                    {
                        ReserviorControl reserviorControl = new ReserviorControl();
                        reserviorControl.ReserviorName = item;
                        var maxmin = GetReserviorWidth(_reservoirMetals[item]);
                        reserviorControl.ReserviorInfo = GenerateReserviorInfo($"Res{item.Substring(item.Length - 1, 1)}", maxmin.max - maxmin.min + 2 * RESERVIOR_MARGIN_LEFT);
                        Canvas.SetLeft(reserviorControl, maxmin.min - RESERVIOR_MARGIN_LEFT);
                        Canvas.SetTop(reserviorControl, maxmin.minTop);
                        Canvas.SetZIndex(reserviorControl, -1);
                        totalCanvas.Children.Add(reserviorControl);
                    }
                }
            }
        }
       
        /// 
        /// 初始化Keys
        /// 
        private void InitialKeys()
        {
            _rtDataKeys.Clear();
            _rtDataKeys.Add("System.CellWaferHolderDictionary");
            foreach (ProcessLayoutCellItem item in _processLayout.Items)
            {
                if (item.Type == "Cell"&&!string.IsNullOrEmpty(item.ModuleName))
                {
                    _rtDataKeys.Add($"{item.ModuleName}.IsInit");
                    _rtDataKeys.Add($"{item.ModuleName}.IsIdle");
                    _rtDataKeys.Add($"{item.ModuleName}.IsError");
                    _rtDataKeys.Add($"{item.ModuleName}.IsBusy");
                    _rtDataKeys.Add($"{item.ModuleName}.IsDisable");
                }
            }
            foreach(string key in _reservoirMetals.Keys)
            {
                _rtDataKeys.Add($"{key}.IsInit");
                _rtDataKeys.Add($"{key}.IsIdle");
                _rtDataKeys.Add($"{key}.IsError");
                _rtDataKeys.Add($"{key}.IsBusy");
                _rtDataKeys.Add($"{key}.IsDisable");
            }
        }
        /// 
        /// 获取Reservior属性信息
        /// 
        /// 
        /// 
        /// 
        private ReserviorInfo GenerateReserviorInfo(string item,int width)
        {
            ReserviorInfo info = new ReserviorInfo();
            info.Name = item;
            info.Width = width;
            info.Cells = new List();
            return info;
        }
        /// 
        /// 定时器执行
        /// 
        /// 
        /// 
        private void Timer_Tick(object sender, EventArgs e)
        {
            if (_rtDataKeys.Count != 0)
            {
                _rtDataValues = QueryDataClient.Instance.Service.PollData(_rtDataKeys);
                if (_rtDataValues != null)
                {
                    _cellWaferHolderDictionary = CommonFunction.GetValue>(_rtDataValues, "System.CellWaferHolderDictionary");
                    //判断Chanmber状态
                    foreach (DependencyObject child in totalCanvas.Children)
                    {
                       if (child is ReserviorControl)
                        {
                            ReserviorControl reservior = child as ReserviorControl;
                        }
                    }
                }
            }
        }
        /// 
        /// 增加Cell元素
        /// 
        /// 
        private void AddCellControl(ProcessLayoutCellItem item)
        {    
        }
        /// 
        /// 获取Reservior宽度
        /// 
        /// 
        /// 
        private (int max,int min,int minTop) GetReserviorWidth(List metals)
        {
            int min = int.MaxValue;
            int max = 0;
            int minTop = int.MaxValue;
            foreach (ProcessLayoutCellItem subitem in _processLayout.Items)
            {
                if (metals.Contains(subitem.ModuleName))
                {
                    if (subitem.Left < min)
                    {
                        min = subitem.Left;
                    }
                    if (subitem.Left + subitem.Width > max)
                    {
                        max = subitem.Left + subitem.Width;
                    }
                    if (subitem.Top < min)
                    {
                        minTop = subitem.Top;
                    }
                }
            }
            return (max,min,minTop);
        }
    }
        
}