using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Log;
using Aitex.Core.UI.Dialog;
using Aitex.Core.UI.MVVM;
using Aitex.Core.Utilities;
using Caliburn.Micro.Core;
using MECF.Framework.Common.DataCenter;
using MECF.Framework.Common.RecipeCenter;
using CyberX8_Core;
using CyberX8_MainPages.PMs;
using CyberX8_Themes.UserControls;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace CyberX8_MainPages.ViewModels
{
    public class RecipeManageViewModel : BindableBase
    {
        #region 常量
        private const string ENGINEERING = "Engineering";
        private const string PRODUCTION = "Production";
        private const string HVD = "hvd";
        #endregion

        #region 内部变量
        /// <summary>
        /// Recipe节点字典
        /// </summary>
        private Dictionary<string, RecipeNode> _recipeNodeDic = new Dictionary<string, RecipeNode>();
        private Dictionary<string, RecipeNode> _recipeName = new Dictionary<string, RecipeNode>();

        /// <summary>
        /// Recipe节点集合
        /// </summary>
        private ObservableCollection<RecipeNode> _recipeNodes;
        /// <summary>
        /// Archive节点集合
        /// </summary>
        private ObservableCollection<RecipeNode> _archiveNodes;
        /// <summary>
        /// uiRecipeManager
        /// </summary>
        private UiRecipeManager _uiRecipeManager = new UiRecipeManager();
        //  选中文件名
        private List<string> _filePaths = new List<string>();
        private List<string> _fileNames = new List<string>();

        //目录文件
        List<string> ProductionFileList = new List<string>();
        private SequenceRecipe _recipe;


        #endregion
        #region 属性
        public SequenceRecipe SeqRecipe
        {
            get { return _recipe; }
            set { SetProperty(ref _recipe, value); }
        }
        public List<string> FilePaths
        {
            get { return _filePaths; }
            set { SetProperty(ref _filePaths, value); }
        }
        public List<string> FileNames
        {
            get { return _fileNames; }
            set { SetProperty(ref _fileNames, value); }
        }
        public ObservableCollection<RecipeNode> RecipeNodes
        {
            get { return _recipeNodes; }
            set { SetProperty(ref _recipeNodes, value); }
        }

        public ObservableCollection<RecipeNode> ArchiveNodes
        {
            get { return _archiveNodes; }
            set { SetProperty(ref _archiveNodes, value); }
        }
        #endregion

        #region 指令
        [IgnorePropertyChange]
        public ICommand OperationCommand
        {
            get;
            private set;
        }
        [IgnorePropertyChange]
        public ICommand SelectedCommand
        {
            get;
            private set;
        }
        [IgnorePropertyChange]
        public ICommand PromoteCommand { get; private set; }

        [IgnorePropertyChange]
        public ICommand DeleteRecipeCommand { get; private set; }
        #endregion

        /// <summary>
        /// 构造函数
        /// </summary>
        public RecipeManageViewModel()
        {
            OperationCommand = new DelegateCommand<object>(SelectionChangedAction);
            PromoteCommand = new DelegateCommand<object>(Promote);
            DeleteRecipeCommand=new DelegateCommand<object>(DeleteFile);
        }
        /// <summary>
        /// 加载数据
        /// </summary>
        public void LoadData(string system)
        {
            List<string> directoryList = new List<string>();
            directoryList.Add(ENGINEERING);
            directoryList.Add(PRODUCTION);
            RecipeNodes = _uiRecipeManager.GetRecipeByDirectoryList(directoryList);
            directoryList.Clear();
            directoryList.Add("Archive");
            ArchiveNodes = _uiRecipeManager.GetRecipeByDirectoryList(directoryList);
            _recipeNodeDic.Clear();
            _recipeName.Clear();
            InitializeDictionary(RecipeNodes);
            InitializeDictionary(ArchiveNodes);
            checkSeqRecipe(RecipeNodes);

            FilePaths.Clear();
            FileNames.Clear();
        }
        /// <summary>
        /// 初始化字典
        /// </summary>
        /// <param name="nodes"></param>
        private void InitializeDictionary(ObservableCollection<RecipeNode> nodes)
        {
            if (nodes != null)
            {
                foreach (var node in nodes)
                {
                    if (node.NodeType == RecipeNodeType.File)
                    {
                        _recipeNodeDic[node.Name] = node;
                    }
                    if ((node.NodeType == RecipeNodeType.File) && (node.RecipeLocation == "Production"))
                    {
                        _recipeName[node.FileName] = node;
                    }

                    InitializeDictionary(node.Children);
                }
            }
        }

        /// <summary>
        /// 操作
        /// </summary>
        /// <param name="param"></param>
        private void SelectionChangedAction(object param)
        {
            if (param != null)
            {
                if (_recipeNodeDic.ContainsKey(param.ToString()))
                {

                }
                else
                {
                    if (param.ToString() == ENGINEERING)
                    {
                    }
                    else
                    {
                    }
                }
            }

        }
        private void checkSeqRecipe(ObservableCollection<RecipeNode>  nodes)
        {
            //检验sequence文件是否合法
            if (nodes != null)
            {
                foreach (var node in nodes)
                {
                    if((node.NodeType == RecipeNodeType.Directory) && (node.Name == PRODUCTION))
                    {
                        node.FileName = PRODUCTION;
                    }
                    if ((node.NodeType == RecipeNodeType.Directory) && (node.Name == ENGINEERING))
                    {
                        node.FileName = ENGINEERING;
                    }
                    if ((node.NodeType == RecipeNodeType.File) && (node.RecipeLocation == "Production") && node.FileName.Contains("seq.rcp"))
                    {
                        if (node.FileName.Contains("seq.rcp"))
                        {
                            bool isValid = true;
                            SeqRecipe = _uiRecipeManager.LoadRecipe<SequenceRecipe>(node.RecipeFullFileName);
                            if (SeqRecipe != null && SeqRecipe.Recipes.Count != 0)
                            {
                                foreach (string recipe in SeqRecipe.Recipes)
                                {
                                    if (!(_recipeName.Keys.Contains(recipe)))
                                    {
                                        isValid = false;
                                    }
                                }
                                if (!isValid)
                                {
                                    node.NodeType = RecipeNodeType.Error;
                                }
                            }
                        }
                    }
                    checkSeqRecipe(node.Children);
                }
            }
        }
       
        private void Promote(object param)
        {
            string SelectedFileNames = null;
            if (FilePaths.Count == 0)
            {
                return;
            }
            foreach (var fileItem in FilePaths)
            {
                string[] _content = fileItem.Split('\\');
                string projectName = _content[_content.Length - 2];
                if ("Production".Equals(projectName))
                {
                    MessageBox.Show($"所选文件包含Production文件,无法执行该操作!", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                string _fileName = _content[_content.Length - 1];
                SelectedFileNames += _fileName + '\r'; 
                ////检验sequence文件是否合法
                //if (_fileName.Contains("seq.rcp"))
                //{
                //    bool isValid = true;
                //    string _notValidFileNames = null;
                //    SeqRecipe = _uiRecipeManager.LoadRecipe<SequenceRecipe>(fileItem);

                //    if (SeqRecipe != null && SeqRecipe.Recipes.Count != 0)
                //    {
                //        foreach (string recipe in SeqRecipe.Recipes)
                //        {
                //            if (!(FileNames.Contains(recipe)))
                //            {
                //                isValid = false;
                //                _notValidFileNames += recipe + ',';
                //            }
                //        }
                //        if (!isValid)
                //        {
                //            MessageBox.Show($"未选中{_fileName}中的{_notValidFileNames}文件!", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
                //            return;
                //        }
                //    }
                //}
                //检验文件是否已存在,已存在是否覆盖文件
                foreach (string item in _recipeName.Keys)
                {
                    if (item == _fileName)
                    {
                        if (MessageBox.Show($"{_fileName} 已经存在是否覆盖?", "保存", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                        {
                            continue;
                        }
                        else
                        {
                            return;
                        }
                    }

                }

            }
            if (MessageBox.Show($"确认需要将{SelectedFileNames}文件移至production吗?", "确认", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                SaveFile(FilePaths);
            }

        }
        private void SaveFile(List<string> FilePaths) 
        {
            _uiRecipeManager.PromoteRecipe(FilePaths);
            LoadData("");
        }
        private void DeleteFile(object param)
        {
            string FileNames = null;
            if (FilePaths.Count == 0)
            {
                return;
            }
            if (MessageBox.Show($"确认删除{FileNames}文件吗?", "确认", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                foreach (var fileItem in FilePaths)
                {
                    string[] _content = fileItem.Split('\\');
                    string _fileName = _content[_content.Length - 1];
                    string _directoryName = _content[_content.Length - 2];
                    FileNames += _directoryName + '/' + _fileName + '\r';
                    //if (!(File.Exists(fileItem)))
                    //{
                    //    //MessageBox.Show($"不存在文件{_directoryName}/{_fileName}!", "Aitex", MessageBoxButton.OK, MessageBoxImage.Error);
                    //    MessageBox.Show($"不存在文件{fileItem}!", "Aitex", MessageBoxButton.OK, MessageBoxImage.Error);
                    //    return;
                    //}
                    _uiRecipeManager.DeleteRecipeByFullPath(fileItem);
                }
            }
            LoadData("");
        }
    }
}