using Aitex.Core.RT.Log;
using Aitex.Core.RT.RecipeCenter;
using Aitex.Core.UI.MVVM;
using Aitex.Core.Utilities;
using MECF.Framework.Common.Equipment;
using MECF.Framework.Common.OperationCenter;
using MECF.Framework.Common.Persistent.Prewet;
using MECF.Framework.Common.Persistent.SRD;
using MECF.Framework.Common.RecipeCenter;
using MECF.Framework.Common.Routine;
using CyberX8_Core;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
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 CyberX8_Themes.UserControls
{
    /// <summary>
    /// RecipeControl.xaml 的交互逻辑
    /// </summary>
    public partial class RecipeControl : UserControl
    {
        public RecipeControl()
        {
            InitializeComponent();
        }

        #region 属性
        public static readonly DependencyProperty ModuleNameProperty = DependencyProperty.Register(
            "ModuleName", typeof(string), typeof(RecipeControl),
                new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.AffectsRender));
        /// <summary>
        /// 模块名称
        /// </summary>
        public string ModuleName
        {
            get
            {
                return (string)this.GetValue(ModuleNameProperty);
            }
            set
            {
                this.SetValue(ModuleNameProperty, value);
            }
        }
        public static readonly DependencyProperty ModuleTitleProperty = DependencyProperty.Register(
           "ModuleTitle", typeof(string), typeof(RecipeControl),
               new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.AffectsRender));
        /// <summary>
        /// 模块名称
        /// </summary>
        public string ModuleTitle
        {
            get
            {
                return (string)this.GetValue(ModuleTitleProperty);
            }
            set
            {
                this.SetValue(ModuleTitleProperty, value);
            }
        }

        public static readonly DependencyProperty InputCycleTimesProperty = DependencyProperty.Register(
          "InputCycleTimes", typeof(int), typeof(RecipeControl), new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsRender));
        /// <summary>
        /// InputCycleTimes
        /// </summary>
        public int InputCycleTimes
        {
            get
            {
                return (int)this.GetValue(InputCycleTimesProperty);
            }
            set
            {
                this.SetValue(InputCycleTimesProperty, value);
            }
        }

        public static readonly DependencyProperty AchievedCycleTimesProperty = DependencyProperty.Register(
      "AchievedCycleTimes", typeof(int), typeof(RecipeControl), new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsRender));
        /// <summary>
        /// AchievedCycleTimes
        /// </summary>
        public int AchievedCycleTimes
        {
            get
            {
                return (int)this.GetValue(AchievedCycleTimesProperty);
            }
            set
            {
                this.SetValue(AchievedCycleTimesProperty, value);
            }
        }
        public static readonly DependencyProperty NumberOfSelectedRecipeScansProperty = DependencyProperty.Register(
            "NumberOfSelectedRecipeScans", typeof(int), typeof(RecipeControl), new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsRender));
        /// <summary>
        /// NumberOfSelectedRecipeScans
        /// </summary>
        public int NumberOfSelectedRecipeScans
        {
            get
            {
                return (int)this.GetValue(NumberOfSelectedRecipeScansProperty);
            }
            set
            {
                this.SetValue(NumberOfSelectedRecipeScansProperty, value);
            }
        }
        public static readonly DependencyProperty SelectedRecipeNodeProperty = DependencyProperty.Register(
            "SelectedRecipeNode", typeof(RecipeNode), typeof(RecipeControl),new FrameworkPropertyMetadata(null, new PropertyChangedCallback(SelectedRecipeNodeChanged)));
        /// <summary>
        /// 当前选中recipe节点
        /// </summary>
        public RecipeNode SelectedRecipeNode
        {
            get
            {
                return (RecipeNode)this.GetValue(SelectedRecipeNodeProperty);
            }
            set
            {
                this.SetValue(SelectedRecipeNodeProperty, value);
            }
        }
        public static readonly DependencyProperty RecipeTypeProperty = DependencyProperty.Register(
            "RecipeType", typeof(string), typeof(RecipeControl));
        /// <summary>
        /// Recipe类型
        /// </summary>
        public string RecipeType
        {
            get
            {
                return (string)this.GetValue(RecipeTypeProperty);
            }
            set
            {
                this.SetValue(RecipeTypeProperty, value);
            }
        }
        public static readonly DependencyProperty LoadEnabledProperty = DependencyProperty.Register(
            "LoadEnabled", typeof(bool), typeof(RecipeControl),new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender));
        /// <summary>
        /// 按钮可用性
        /// </summary>
        public bool LoadEnabled
        {
            get
            {
                return (bool)this.GetValue(LoadEnabledProperty);
            }
            set
            {
                this.SetValue(LoadEnabledProperty, value);
            }
        }
        /// <summary>
        /// 选中Recipe文件的触发的方法
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        private static void SelectedRecipeNodeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue != null)
            {
                d.SetValue(LoadEnabledProperty, true);
                
            }
            else
            {
                d.SetValue(LoadEnabledProperty, false);
            }
        }
        public static readonly DependencyProperty CurrentOperationModeProperty = DependencyProperty.Register(
           "CurrentOperationMode", typeof(string), typeof(RecipeControl));
        /// <summary>
        /// CurrentOperationMode
        /// </summary>
        public string CurrentOperationMode
        {
            get
            {
                return (string)this.GetValue(CurrentOperationModeProperty);
            }
            set
            {
                this.SetValue(CurrentOperationModeProperty, value);
            }
        }


        public static readonly DependencyProperty IsEngineeringProperty = DependencyProperty.Register(
   "IsEngineering", typeof(bool), typeof(RecipeControl), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender));
        /// <summary>
        /// IsEngineering
        /// </summary>
        public bool IsEngineering
        {
            get
            {
                return (bool)this.GetValue(IsEngineeringProperty);
            }
            set
            {
                this.SetValue(IsEngineeringProperty, value);
            }
        }

        public static readonly DependencyProperty IsProductionProperty = DependencyProperty.Register(
    "IsProduction", typeof(bool), typeof(RecipeControl), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender));
        /// <summary>
        /// IsProduction
        /// </summary>
        public bool IsProduction
        {
            get
            {
                return (bool)this.GetValue(IsProductionProperty);
            }
            set
            {
                this.SetValue(IsProductionProperty, value);
            }
        }
        public static readonly DependencyProperty RecipeModeValueProperty = DependencyProperty.Register(
           "RecipeModeValue", typeof(string), typeof(RecipeControl), new FrameworkPropertyMetadata("", new PropertyChangedCallback(OnItemsSourceChanged)));
        /// <summary>
        /// OpertationModeValue
        /// </summary>
        public string RecipeModeValue
        {
            get
            {
                return (string)this.GetValue(RecipeModeValueProperty);
            }
            set
            {
                this.SetValue(RecipeModeValueProperty, value);
            }
        }

        private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue != null)
            {
                string currentMode = (string)e.NewValue;
                switch (currentMode)
                {
                    case "Engineering":
                        d.SetValue(IsEngineeringProperty, true);
                        d.SetValue(IsProductionProperty, false);
                        break;
                    case "Production":
                        d.SetValue(IsEngineeringProperty, false);
                        d.SetValue(IsProductionProperty, true);
                        break;
                    default:
                        break;
                }
            }
        }


        #endregion

        private void GetRecipeType()
        {
            if (SelectedRecipeNode.RecipeFullFileName.Contains("pwt"))
            {
                PwtRecipe pwtRecipe = RecipeFileManager.Instance.LoadGenericityRecipe<PwtRecipe>(SelectedRecipeNode.RecipeFullFileName);
                if (pwtRecipe != null) 
                {
                    NumberOfSelectedRecipeScans = pwtRecipe.NumberOfScans;
                }
            }
        }

        private void Pause_Click(object sender, RoutedEventArgs e)
        {
            if ("Manual".Equals(CurrentOperationMode))
            {
                InvokeClient.Instance.Service.DoOperation($"{ModuleName}.PauseWaferRecipe", SelectedRecipeNode.RecipeFullFileName, InputCycleTimes);
            }
            else
            {
                MessageBox.Show("Current OperationMode Can't Perform This Action", $"Current OperationMode is {CurrentOperationMode}", MessageBoxButton.OK, MessageBoxImage.Error);
            } 
        }

        private void Resume_Click(object sender, RoutedEventArgs e)
        {
            if ("Manual".Equals(CurrentOperationMode))
            {
                InvokeClient.Instance.Service.DoOperation($"{ModuleName}.ResumeWaferRecipe", SelectedRecipeNode.RecipeFullFileName, InputCycleTimes);
            }
            else
            {
                MessageBox.Show("Current OperationMode Can't Perform This Action", $"Current OperationMode is {CurrentOperationMode}", MessageBoxButton.OK, MessageBoxImage.Error);
            }
           
        }

        private void Abort_Click(object sender, RoutedEventArgs e)
        {
            if ("Manual".Equals(CurrentOperationMode))
            {
                InvokeClient.Instance.Service.DoOperation($"{ModuleName}.Abort");
            }
            else
            {
                if (RecipeModeValue != SelectedRecipeNode.RecipeLocation)
                {
                    MessageBox.Show("Recipe OperationMode is not match!", $"Current Recipe OperationMode is {RecipeModeValue}", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    MessageBox.Show("Current OperationMode Can't Perform This Action", $"Current OperationMode is {CurrentOperationMode}", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            
        }

        private void Edit_Click(object sender, RoutedEventArgs e)
        {
            string _recipeName = "";
            string pattern3 = @"^SRD\d$";
            string pattern2 = @"^Dryer\d$";
            string pattern1 = @"^Rinse\d$";
            string pattern4 = @"^Reservoir\d$";
            Regex regex3 = new Regex(pattern3);
            Regex regex2 = new Regex(pattern2);
            Regex regex1 = new Regex(pattern1);
            Regex regex4 = new Regex(pattern4);
            switch (ModuleName)
            {
                case "Prewet1":
                    _recipeName = "PwtRecipe";
                    break;
                case string str when regex1.IsMatch(str):
                    _recipeName = "QdrRecipe";
                    break;
                case string str when regex2.IsMatch(str):
                    _recipeName = "HvdRecipe";
                    break;
                case string str when regex3.IsMatch(str):
                    _recipeName = "SrdRecipe";
                    break;
                case string str when regex4.IsMatch(str):
                    _recipeName = "ResRecipe";
                    break;
                default:
                    break;
                       
            }
            if (!"Manual".Equals(CurrentOperationMode))
            {
                MessageBox.Show("Current OperationMode Can't Perform This Action", $"Current OperationMode is {CurrentOperationMode}", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                if (RecipeModeValue != SelectedRecipeNode.RecipeLocation)
                {
                    MessageBox.Show("Recipe OperationMode is not match!", $"Current Recipe OperationMode is {RecipeModeValue}", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    GlobalEvents.OnSwitchFixedTabItem("Recipe", "", _recipeName);
                }
            }
            
        }

        private void RunRecipe_Click(object sender, RoutedEventArgs e)
        {
            GetRecipeType();
            if ("Manual".Equals(CurrentOperationMode))
            {
                if (InputCycleTimes==0)
                {
                    MessageBox.Show("Please Enter CycleTimes First!", "Current Cycle is 0", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                   InvokeClient.Instance.Service.DoOperation($"{ModuleName}.CycleManualProcessRecipe", SelectedRecipeNode.RecipeFullFileName, InputCycleTimes);
                }     
            }
            else
            {
                MessageBox.Show("Current OperationMode Can't Perform This Action", $"Current OperationMode is {CurrentOperationMode}", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}