using MainShell.Common;
using MainShell.Models;
using MainShell.Recipe.Models;
using MainShell.Recipe.View;
using MaxwellControl.Tools;
using MaxwellFramework.Core.Common.Command;
using MwFramework.ManagerService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace MainShell.Recipe.ViewModel
{
    public class RecipeButtonGroupViewModel  :BaseScreen
    {
        public ICommand CreateNewCmd { get;private set; }
        public ICommand DeleteCmd { get; private set; }
        public ICommand CopyCmd {  get; private set; }
        public ICommand ApplyCmd { get; private set; }
        public ICommand ImportCmd { get; private set; }
        public ICommand SaveCmd { get; private set; }
        public ICommand ExportCmd {  get; private set; }
        public ICommand ReNameCmd {  get; private set; }
        public ICommand ClearCmd {  get; private set; }

        // 新增事件 —— 发布者（按钮组）向外广播意图
        public event EventHandler CreateNewRequested;
        public event EventHandler DeleteRequested;
        public event EventHandler CopyRequested;
        public event EventHandler ApplyRequested;
        public event EventHandler ImportRequested;
        public event EventHandler SaveRequested;
        public event EventHandler ExportRequested;
        public event EventHandler ReNameRequested;
        public event EventHandler ClearRequested;

        public RecipeButtonGroupViewModel()
        {
            CreateNewCmd = new DelegateCommand(obj =>
            {
                if (obj != null && obj is IRecipeViewModel recipeViewModel)
                {
                    var existingNames = recipeViewModel.RecipeWraps.Select(r => r.RecipeName).ToList();
                    var recipeNameWindow = new RecipeNameWindowModel
                    {
                        ExistingRecipeNames = existingNames
                    };
                    ShowRecipeWindow<RecipeNameWindow,RecipeNameWindowModel>(recipeNameWindow, out bool? result);
                    if (result == true)
                    {
                        CreateNewRequested?.Invoke(this, new RecipeEventArgs
                        {
                            RecipeName = recipeNameWindow.RecipeName
                        });
                    }

                }
            });

            DeleteCmd = new DelegateCommand(obj =>
            {
                if (obj != null && obj is IRecipeViewModel recipeViewModel)
                {
                    bool flowControl = CheckOperate(recipeViewModel);
                    if (!flowControl)
                    {
                        return;
                    }
                    var result = MwMessageBox.Show($"确认删除当前选中配方：{recipeViewModel.SelectedRecipeWrap.RecipeName}?", "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                    if (result == MessageBoxResult.Yes)
                    {
                        DeleteRequested?.Invoke(this, new RecipeEventArgs
                        {
                            RecipeName = recipeViewModel.SelectedRecipeWrap.RecipeName
                        });
                    }
                }

            });

            CopyCmd = new DelegateCommand(obj =>
            {
                if (obj != null && obj is IRecipeViewModel recipeViewModel)
                {
                    if (!EnsureActionSupported(recipeViewModel.CanCopyRecipe, "复制"))
                    {
                        return;
                    }

                    bool flowControl = CheckOperate(recipeViewModel);
                    if (!flowControl)
                    {
                        return;
                    }
                    var existingNames = recipeViewModel.RecipeWraps.Select(r => r.RecipeName).ToList();
                    var recipeNameWindow = new RecipeNameWindowModel
                    {
                        ExistingRecipeNames = existingNames,
                        RecipeName = recipeViewModel.SelectedRecipeWrap.RecipeName + "_Copy"
                    };
                    ShowRecipeWindow<RecipeNameWindow, RecipeNameWindowModel>(recipeNameWindow, out bool? result);
                    if (result == true)
                    {
                        CopyRequested?.Invoke(this, new RecipeEventArgs
                        {
                            RecipeName = recipeNameWindow.RecipeName
                        });
                    }

                }
            });

            ApplyCmd = new DelegateCommand(obj =>
            {
                if (obj != null && obj is IRecipeViewModel recipeViewModel)
                {
                    bool flowControl = CheckOperate(recipeViewModel);
                    if (!flowControl)
                    {
                        return;
                    }
                    ApplyRequested?.Invoke(this, new RecipeEventArgs
                    {
                        RecipeName = recipeViewModel.SelectedRecipeWrap.RecipeName
                    });
                }
            });

            ImportCmd = new DelegateCommand(obj =>
            {
                if (obj != null && obj is IRecipeViewModel recipeViewModel)
                {
                    if (!EnsureActionSupported(recipeViewModel.CanImportRecipe, "导入"))
                    {
                        return;
                    }

                    bool flowControl = CheckOperate(recipeViewModel);
                    if (!flowControl)
                    {
                        return;
                    }
                    ImportRequested?.Invoke(this, new RecipeEventArgs
                    {
                        RecipeName = recipeViewModel.SelectedRecipeWrap.RecipeName
                    });
                }
            });

            SaveCmd = new DelegateCommand(obj =>
            {
                if (obj != null && obj is IRecipeViewModel recipeViewModel)
                {
                    bool flowControl = CheckOperate(recipeViewModel);
                    if (!flowControl)
                    {
                        return;
                    }
                    SaveRequested?.Invoke(this, new RecipeEventArgs
                    {
                        RecipeName = recipeViewModel.SelectedRecipeWrap.RecipeName
                    });
                }
            });

            ExportCmd = new DelegateCommand(obj =>
            {
                if (obj != null && obj is IRecipeViewModel recipeViewModel)
                {
                    if (!EnsureActionSupported(recipeViewModel.CanExportRecipe, "导出"))
                    {
                        return;
                    }

                    bool flowControl = CheckOperate(recipeViewModel);
                    if (!flowControl)
                    {
                        return;
                    }
                    ExportRequested?.Invoke(this, new RecipeEventArgs
                    {
                        RecipeName = recipeViewModel.SelectedRecipeWrap.RecipeName
                    });
                }
            });

            ReNameCmd = new DelegateCommand(obj =>
            {
                if (obj != null && obj is IRecipeViewModel recipeViewModel)
                {
                    bool flowControl = CheckOperate(recipeViewModel);
                    if (!flowControl)
                    {
                        return;
                    }
                    var existingNames = recipeViewModel.RecipeWraps.Select(r => r.RecipeName).ToList();
                    var recipeNameWindow = new RecipeReNameWindowModel
                    {
                        ExistingRecipeNames = existingNames,
                        OldRecipeName = recipeViewModel.SelectedRecipeWrap.RecipeName
                    };
                    ShowRecipeWindow<RecipeReNameWindow,RecipeReNameWindowModel>( recipeNameWindow, out bool? result);
                    if (result == true)
                    {
                        ReNameRequested?.Invoke(this, new RecipeRenameEventArgs
                        {
                            NewRecipeName = recipeNameWindow.RecipeName,
                            OldRecipeName = recipeNameWindow.OldRecipeName
                        });
                    }

                }
                
            });

            ClearCmd = new DelegateCommand(obj =>
            {
                ClearRequested?.Invoke(this, EventArgs.Empty);
            });
        }

        private static bool CheckOperate(IRecipeViewModel recipeViewModel)
        {
            if (recipeViewModel.RecipeWraps.Count == 0)
            {
                MwMessageBox.Show("当前无可操作的配方，请先创建或导入配方。", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return false;
            }
            else if (recipeViewModel.SelectedRecipeWrap == null)
            {
                MwMessageBox.Show("请先选择一个配方再进行操作。", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return false;
            }

            return true;
        }

        private static bool EnsureActionSupported(bool isSupported, string actionName)
        {
            if (isSupported)
                return true;

            MwMessageBox.Show($"当前版本暂不支持{actionName}功能。");
            return false;
        }

        private void ShowRecipeWindow<TWindow, TViewModel>(TViewModel viewModel, out bool? result)
     where TWindow : Window, new()
        {
            result = null;
            var owner = WindowHelper.GetActiveWindow();

            try
            {
                // 确保在 UI 线程创建/显示窗口
                if (Application.Current == null || Application.Current.Dispatcher.CheckAccess())
                {
                    var window = new TWindow
                    {
                        DataContext = viewModel,
                        Owner = owner,
                        ShowInTaskbar = owner == null,
                        WindowStartupLocation = owner != null ? WindowStartupLocation.CenterOwner : WindowStartupLocation.CenterScreen
                    };

                    // 如果确实需要置顶，可由调用方或窗口自身控制；这里不强制 Topmost
                    result = window.ShowDialog();
                }
                else
                {
                    var windowResult= default(bool?);
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        var window = new TWindow
                        {
                            DataContext = viewModel,
                            Owner = owner,
                            ShowInTaskbar = owner == null,
                            WindowStartupLocation = owner != null ? WindowStartupLocation.CenterOwner : WindowStartupLocation.CenterScreen
                        };
                        windowResult = window.ShowDialog();
                    });
                    result = windowResult;
                }
            }
            catch (Exception)
            {
                // 避免抛出异常到调用方（视需求可记录日志）
                result = null;
            }
        }

    }
}
