using Aitex.Core.UI.MVVM;
using Aitex.Core.Utilities;
using PunkHPX8_MainPages.PMs;
using PunkHPX8_Themes.UserControls;
using MECF.Framework.Common.DataCenter;
using MECF.Framework.Common.RecipeCenter;
using MECF.Framework.Common.Utilities;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;
namespace PunkHPX8_MainPages.ViewModels
{
    public class SequenceRecipeViewModel : BindableBase
    {
        #region 常量
        private const string ENGINEERING = "Engineering";
        private const string SEQUENCE = "seq";
        public enum PlatType 
        {
            notch,
            flat
        }
        #endregion
        #region 内部变量
        /// 
        /// Recipe节点字典
        /// 
        private Dictionary _recipeNodeDic = new Dictionary();
        /// 
        /// 可用RecipeType字典(key-ListBox内容,value-recipeType)
        /// 
        private Dictionary _aviableNodeTypeDic = new Dictionary();
        /// 
        /// Recipe节点集合
        /// 
        private ObservableCollection _recipeNodes;
        /// 
        /// 子Recipe节点集合
        /// 
        private ObservableCollection _subRecipeNodes;
        /// 
        /// uiRecipeManager
        /// 
        private UiRecipeManager _uiRecipeManager = new UiRecipeManager();
        /// 
        /// recipe
        /// 
        private SequenceRecipe _recipe;
        /// 
        /// 编辑可用性
        /// 
        private bool _editEnable;
        /// 
        /// 创建可用性
        /// 
        private bool _createEnable;
        /// 
        /// 当前节点
        /// 
        private RecipeNode _currentNode;
        /// 
        /// 可用Recipe集合
        /// 
        private List _avaibleRecipeTypeLst;
        /// 
        /// Process Recipe集合
        /// 
        private ObservableCollection _processRecipes;
        /// 
        /// 选中可用RecipeType
        /// 
        private string _selectAvaibleRecipeType;
        /// 
        /// 选中子Recipe
        /// 
        private string _selectSubRecipe;
        /// 
        /// 选中索引
        /// 
        private int _selectedProcessRecipeIndex;
        /// 
        /// 选中Process Recipe
        /// 
        private string _selectedProcessRecipe;
        /// 
        /// 
        /// csr 类型集合
        /// 
        private List _crsTypeLst = null;
        /// 
        /// 
        /// PlatType类型集合
        /// 
        private List _platTypeLst = null;
        /// 
        /// Wafer尺寸集合
        /// 
        private List _waferSizeLst = null;
        /// 
        /// 是否可用
        /// 
        private bool _enable = false;
        /// 
        /// 是否为编辑
        /// 
        private bool _editAction = false;
        /// 
        /// 是否为编辑(true-Edit,false-add)
        /// 
        private bool _isEdit = false;
        /// 
        /// 属性检验结果字典
        /// 
        private Dictionary _propertyValidResultDic = new Dictionary();
        /// 
        /// Selected Flat Type
        /// 
        private PlatType _selectedPlatType;
        /// 
        /// Selected CrsType
        /// 
        private string _selectedCrsType = "";
        #endregion
        #region 属性
        public ObservableCollection RecipeNodes
        {
            get { return _recipeNodes; }
            set { SetProperty(ref _recipeNodes, value); }
        }
        /// 
        /// 子Recipe集合
        /// 
        public ObservableCollection SubRecipeNodes
        {
            get { return _subRecipeNodes; }
            set { SetProperty(ref _subRecipeNodes, value); }
        }
        /// 
        /// Recipe
        /// 
        public SequenceRecipe Recipe
        {
            get { return _recipe; }
            set { SetProperty(ref _recipe, value); }
        }
        /// 
        /// 创建可用性
        /// 
        public bool CreateEnable
        {
            get { return _createEnable; }
            set { SetProperty(ref _createEnable, value);}
        }
        /// 
        /// 编辑可用性
        /// 
        public bool EditEnable
        {
            get { return _editEnable; }
            set { SetProperty(ref _editEnable, value);}
        }
        /// 
        /// 当前节点
        /// 
        public RecipeNode CurrentNode
        {
            get { return _currentNode; }
            set { SetProperty(ref _currentNode, value);}
        }
        /// 
        /// 可用集合
        /// 
        public List AvaibleRecipeTypeLst
        {
            get { return _avaibleRecipeTypeLst; }
            set { SetProperty(ref _avaibleRecipeTypeLst, value);}
        }
        /// 
        /// 选中
        /// 
        public string SelectedAvaibleRecipeType
        {
            get { return _selectAvaibleRecipeType; }
            set 
            {
                SetProperty(ref _selectAvaibleRecipeType, value);
                LoadSubRecipeNodes(value);
            }
        }
        /// 
        /// 选中子Recipe
        /// 
        public string SelectedSubRecipe
        {
            get { return _selectSubRecipe; }
            set { SetProperty(ref _selectSubRecipe, value);}
        }
        /// 
        /// 选中Process Recipe索引
        /// 
        public int SelectedProcessRecipeIndex
        {
            get { return _selectedProcessRecipeIndex; }
            set { SetProperty(ref _selectedProcessRecipeIndex, value); }
        }
        /// 
        /// 选中Process Recipe
        /// 
        public string SelectedProcessRecipe
        {
            get { return _selectedProcessRecipe; }
            set { SetProperty(ref _selectedProcessRecipe, value); }
        }
        /// 
        /// Process Recipe集合
        /// 
        public ObservableCollection ProcessRecipes
        {
            get { return _processRecipes; }
            set { SetProperty(ref _processRecipes,value); }
        }
        /// 
        /// crs类型集合
        /// 
        public List CrsTypeLst
        {
            get { return _crsTypeLst; }
            set { SetProperty(ref _crsTypeLst, value); }
        }
        /// 
        /// PlatType集合
        /// 
        public List PlatTypeLst
        {
            get { return _platTypeLst; }
            set { SetProperty(ref _platTypeLst, value); }
        }
        /// 
        /// Wafer 尺寸集合
        /// 
        public List WaferSizeLst
        {
            get { return _waferSizeLst; }
            set { SetProperty(ref _waferSizeLst, value); }
        }
        /// 
        /// 可用性
        /// 
        public bool Enable
        {
            get { return _enable; }
            set { SetProperty(ref _enable, value); }
        }
        /// 
        /// 属性数据检验结果
        /// 
        public Dictionary PropertyValidResultDic
        {
            get { return _propertyValidResultDic; }
            set { SetProperty(ref _propertyValidResultDic, value); }
        }
        /// 
        /// Selected Plat Type
        /// 
        public PlatType SelectedPlatType 
        {
            get { return _selectedPlatType; }
            set { SetProperty(ref _selectedPlatType, value); }
        }
        /// 
        /// SelecteCrsType
        /// 
        public string SelectedCrsType
        {
            get { return _selectedCrsType; }
            set { SetProperty(ref _selectedCrsType, value); }
        }
        #endregion
        #region 指令
        [IgnorePropertyChange]
        public ICommand OperationCommand
        {
            get;
            private set;
        }
        [IgnorePropertyChange]
        public ICommand CreateCommand { get; private set; }
        [IgnorePropertyChange]
        public ICommand EditCommand {  get; private set; }
        [IgnorePropertyChange]
        public ICommand AddRecipeCommand { get; private set; }
        [IgnorePropertyChange]
        public ICommand RemoveRecipeCommand { get; private set; }
        [IgnorePropertyChange]
        public ICommand MoveUpCommand { get; private set; }
        [IgnorePropertyChange]
        public ICommand MoveDownCommand { get; private set; }
        [IgnorePropertyChange]
        public ICommand SaveRecipeCommand { get; private set; }
        [IgnorePropertyChange]
        public ICommand SaveAsRecipeCommand { get; private set; }
        #endregion
        /// 
        /// 构造函数
        /// 
        public SequenceRecipeViewModel()
        {
            OperationCommand = new DelegateCommand
        /// 
        private void SaveAction(object param)
        {
            if (CheckValid(_isEdit))
            {
                Recipe.Recipes = new List();
                Recipe.Recipes.AddRange(ProcessRecipes);
                Recipe.SaveDate = DateTime.Now;
                Recipe.PlatType = (int)SelectedPlatType;
                Recipe.CrsType = SelectedCrsType;
                try
                {
                    _uiRecipeManager.SaveRecipe(ENGINEERING, Recipe.Ppid, "seq",Recipe);
                    if (!_editAction)
                    {
                        LoadRecipeData();
                    }
                    MessageBox.Show("Save Recipe Success", "Save Recipe", MessageBoxButton.OK, MessageBoxImage.Information);
                    Enable = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Save Recipe", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
        /// 另存为
        /// 
        /// 
        private void SaveAsAction(object param)
        {
            if (Recipe == null)
            {
                MessageBox.Show("Select a Recipe first", "SaveAs Recipe", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            SequenceRecipe recipe = new SequenceRecipe();
            if (CheckValid(_isEdit))
            {
                RecipeNameDialog recipeNameDialog = new RecipeNameDialog();
                if (recipeNameDialog.ShowDialog().Value)
                {
                    if (!CheckNameExist(recipeNameDialog.RecipeName))
                    {
                        recipe = new SequenceRecipe();
                        //赋值属性
                        //recipe.AlignmentAngle = Recipe.AlignmentAngle;
                        //recipe.CrsType = Recipe.CrsType;
                        //recipe.FiducialType = Recipe.FiducialType;
                        //recipe.LastSingleWaferToSideB = Recipe.LastSingleWaferToSideB;
                        //recipe.SubstrateSize = Recipe.SubstrateSize;
                        //recipe.SequenceType = Recipe.SequenceType;
                        //recipe.Recipes = new List();
                        //foreach (var item in Recipe.Recipes)
                        //{
                        //    recipe.Recipes.Add(item); 
                        //}
                        recipe = (SequenceRecipe)PropertyUtil.Clone(Recipe);
                        recipe.Recipes.Clear();
                        recipe.Recipes.AddRange(ProcessRecipes);
                        recipe.CreateDate = DateTime.Now;
                        recipe.Ppid = recipeNameDialog.RecipeName;
                        recipe.Description = recipeNameDialog.RecipeDescription;
                    }
                    else if (recipeNameDialog.RecipeName != null)
                    {
                        MessageBox.Show("Name can not be Null", "Create Recipe", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                    else
                    {
                        return;
                    }
                }
                try
                {
                    _uiRecipeManager.SaveRecipe(ENGINEERING, recipe.Ppid, "seq", recipe);
                    LoadRecipeData();
                    MessageBox.Show("Save As Recipe Success", "SaveAs Recipe", MessageBoxButton.OK, MessageBoxImage.Information);
                    Enable = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Save As Recipe", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
        /// 
        /// 检验合法性
        /// 
        /// 
        /// 
        private bool CheckValid(bool editType)
        {
            foreach (string key in _propertyValidResultDic.Keys)
            {
                bool valid = _propertyValidResultDic[key];
                if (!valid)
                {
                    MessageBox.Show($"{key} data invalid", "Save Recipe", MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }
            }
            return true;
        }
        /// 
        /// 检验名称是否已经存在
        /// 
        /// 
        /// 
        private bool CheckNameExist(string name)
        {
            foreach (string item in _recipeNodeDic.Keys)
            {
                if (item == name)
                {
                    MessageBox.Show($"{name} is exsit", "Save Recipe", MessageBoxButton.OK, MessageBoxImage.Error);
                    return true;
                }
            }
            return false;
        }
        #endregion
        /// 
        /// 选择可用RecipeType
        /// 
        private void GetAvaibleRecipeType()
        {
            AvaibleRecipeTypeLst = new List();
            ActiveRecipeType[] values=(ActiveRecipeType[]) Enum.GetValues(typeof(ActiveRecipeType));
            foreach (var item in values)
            {
                object[] objAttrs = item.GetType().GetField(item.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (objAttrs != null &&objAttrs.Length > 0)
                {
                    DescriptionAttribute descAttr = objAttrs[0] as DescriptionAttribute;
                    AvaibleRecipeTypeLst.Add($"{item}({descAttr.Description})");
                    _aviableNodeTypeDic.Add($"{item}({descAttr.Description})", item.ToString());
                }
            }
        }
        /// 
        /// 加载子Recipe集合
        /// 
        /// 
        private void LoadSubRecipeNodes(string selectedRecipeType)
        {
            if(_aviableNodeTypeDic.ContainsKey(selectedRecipeType))
            {
                SubRecipeNodes = new ObservableCollection();
                string recipeType = _aviableNodeTypeDic[selectedRecipeType].ToLower();
                ObservableCollection tmpRecipeNodes = _uiRecipeManager.GetEngineeringRecipesByType(recipeType);
                foreach(RecipeNode item in tmpRecipeNodes)
                {
                    SubRecipeNodes.Add(item.FileName);
                }
            }
        }
    }
}