using BOB.Models;
using BOB.Singleton;
using BOB.Views;
using CAN驱动;
using Common.PubEvent;
using Logger;
using MaterialDesignThemes.Wpf;
using Microsoft.Win32;
using Model;
using Newtonsoft.Json;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;

namespace BOB.ViewModels
{
    public class ShellViewModel : BindableBase
    {
        #region 属性
        private string _Title="";

        public string Title
        {
            get => _Title;
            set => SetProperty(ref _Title, value);
        }
        private bool _IsLeftDrawerOpen;

        public bool IsLeftDrawerOpen
        {
            get => _IsLeftDrawerOpen;
            set => SetProperty(ref _IsLeftDrawerOpen, value);
        }
        private bool _IsTerminate=false;

        public bool IsTerminate
        {
            get => _IsTerminate;
            set => SetProperty(ref _IsTerminate, value);
        }

        public String RunState
        {
            get => _globalVariables.RunState;
            set
            {
                if (_globalVariables.RunState != value)
                {
                    _globalVariables.RunState = value;
                    RaisePropertyChanged();
                }
            }
        }

        public bool SingleStep
        {
            get => _globalVariables.SingleStep;
            set
            {
                if (_globalVariables.SingleStep != value)
                {
                    _globalVariables.SingleStep = value;
                    RaisePropertyChanged();
                }
            }
        }

        public PackIconKind RunIcon
        {
            get => _globalVariables.RunIcon;
            set
            {
                if (_globalVariables.RunIcon != value)
                {
                    _globalVariables.RunIcon = value;
                    RaisePropertyChanged();
                }
            }
        }

        #endregion
        #region 命令
        public ICommand LeftDrawerOpenCommand { get; set; }
        public ICommand MinimizeCommand { get; set; }
        public ICommand MaximizeCommand { get; set; }
        public ICommand CloseCommand { get; set; }
        public ICommand RunningCommand { get; set; }
        public ICommand RunSingleCommand { get; set; }
        public ICommand ResotrationCommand { get; set; }
        public ICommand StopCommand { get; set; }
        public ICommand SaveAsCommand { get; set; }
        public ICommand SaveCommand { get; set; }
        public ICommand OpenCommand { get; set; }
        public ICommand NewCommand { get; set; }
        public ICommand SetDefaultCommand { get; set; }
        public ICommand LoadCommand { get; set; }
        public ICommand NavigateCommand { get; set; }
        public ICommand SettingChannelCommand { get; set; }
        public ICommand NavigateToCanPageCommand { get; set; }
        #endregion

        private IEventAggregator _eventAggregator;
        private GlobalVariables _globalVariables;
        private IContainerProvider _containerProvider;
        private IRegionManager _regionManager;
        private StepRunning _stepRunning;
        private IDialogService _dialogService;
        private Task? currentExecutionTask;
        public ShellViewModel(IContainerProvider containerProvider)
        {
            _eventAggregator = containerProvider.Resolve<IEventAggregator>(); ;
            _containerProvider = containerProvider;
            _globalVariables = containerProvider.Resolve<GlobalVariables>(); ;
            _regionManager = containerProvider.Resolve<IRegionManager>(); ;
            _dialogService= containerProvider.Resolve<IDialogService>();
            _stepRunning = containerProvider.Resolve<StepRunning>(); ;
            LeftDrawerOpenCommand = new DelegateCommand(LeftDrawerOpen);
            MinimizeCommand = new DelegateCommand<Window>(MinimizeWindow);
            MaximizeCommand = new DelegateCommand<Window>(MaximizeWindow);
            CloseCommand = new DelegateCommand<Window>(CloseWindow);
            RunningCommand = new DelegateCommand(Running);
            RunSingleCommand = new DelegateCommand(RunSingle);
            ResotrationCommand = new DelegateCommand(Resotration);
            StopCommand = new DelegateCommand(Stop);
            NewCommand = new DelegateCommand(New);
            OpenCommand = new DelegateCommand<string>(Open);
            SaveAsCommand = new DelegateCommand(SaveAs);
            SaveCommand = new DelegateCommand(Save);
            SetDefaultCommand = new DelegateCommand(SetDefault);
            LoadCommand = new DelegateCommand(Load);
            NavigateCommand = new DelegateCommand<string>(Navigate);
            SettingChannelCommand = new DelegateCommand(SettingChannel);
            NavigateToCanPageCommand = new DelegateCommand(NavigateToCanPage);
            _eventAggregator.GetEvent<UpdateIconEvent>().Subscribe(UpdateRunIcon);
        }

       

        #region ToolBar命令
        private bool isConnect = false;
        
        private void SettingChannel()
        {
            var re = 同星驱动类.ShowChannelMappingWindow(true);
            if (re != 0)
            {
                var msg = 同星驱动类.GetErrorDescription(re);
                LoggerHelper.ErrorWithNotify($"同星通道映射界面打开失败：{msg}");
            }
        }
        private void NavigateToCanPage()
        {
            _dialogService.Show("CAN");
        }
        private void Navigate(string content)
        {
            switch (content)
            {
                case "程序界面":
                    _regionManager.RequestNavigate("ShellViewManager", "MainView");
                    break;

                case "监控界面":
                    _regionManager.RequestNavigate("ShellViewManager", "MonitorView");
                    break;

                case "数据管理":
                    _regionManager.RequestNavigate("ShellViewManager", "DataView");
                    break;

                case "更新信息":
                    _regionManager.RequestNavigate("ShellViewManager", "UpdateInfoView");
                    break;

                default:
                    break;
            }
        }
        private void SetDefault()
        {
            if(_globalVariables.CurrentFilePath!=null)
            {
                SystemConfig.Instance.DefaultSubProgramFilePath = _globalVariables.CurrentFilePath;
                SystemConfig.Instance.SaveToFile();
            }
        }
        private void New()
        {
            _globalVariables.CurrentFilePath = null;
            _globalVariables.Program.Parameters.Clear();
            _globalVariables.Program.StepCollection.Clear();
        }

        private void Open(string filePath = null)
        {
            try
            {
                // 如果没有传路径，弹出文件选择对话框
                if (string.IsNullOrEmpty(filePath))
                {
                    var openFileDialog = new OpenFileDialog
                    {
                        Filter = "BOB程序文件|*.bob|所有文件|*.*",
                        Title = "打开程序",
                        InitialDirectory = @"D:\BOB\子程序"
                    };

                    if (openFileDialog.ShowDialog() != true)
                        return; // 用户取消选择

                    filePath = openFileDialog.FileName;
                }

                // 确认文件存在
                if (!File.Exists(filePath))
                {
                    LoggerHelper.ErrorWithNotify($"文件不存在: {filePath}");
                    return;
                }

                // 读取 JSON 文件
                string json = File.ReadAllText(filePath);

                // 反序列化为 ProgramModel
                var program = JsonConvert.DeserializeObject<ProgramModel>(json);

                if (program == null)
                {
                    LoggerHelper.WarnWithNotify($"文件格式不正确或为空: {filePath}");
                    return;
                }

                _globalVariables.Program.Parameters = program.Parameters;
                _globalVariables.Program.StepCollection = program.StepCollection;
                _globalVariables.CurrentFilePath = filePath;
                LoggerHelper.SuccessWithNotify($"成功打开文件: {filePath}");
            }
            catch (Exception ex)
            {
                LoggerHelper.ErrorWithNotify($"打开文件失败: {ex.Message}");
            }
        }
        private void SaveAs()
        {
            string defaultPath = @"D:\BOB\子程序";

            // 如果目录不存在，可以自动创建
            if (!Directory.Exists(defaultPath))
                Directory.CreateDirectory(defaultPath);

            var saveFileDialog = new SaveFileDialog
            {
                Filter = "BOB程序文件|*.bob|所有文件|*.*",
                Title = "另存为",
                FileName = "NewProgram.bob",
                InitialDirectory = defaultPath // ✅ 默认打开这个文件夹
            };
            if (saveFileDialog.ShowDialog() == true)
            {
                _globalVariables.CurrentFilePath = saveFileDialog.FileName;
                SaveProgramToFile(_globalVariables.CurrentFilePath);
                // 记录日志
                LoggerHelper.InfoWithNotify($"{_globalVariables.UserName} 另存为文件成功: {saveFileDialog.FileName}");
            }

        }
        private void SaveProgramToFile(string filePath)
        {
            try
            {
                var tmp = ClearDeviceParameterValue(_globalVariables.Program);
                string json = JsonConvert.SerializeObject(tmp, Formatting.Indented);
                File.WriteAllText(filePath, json);
                LoggerHelper.SuccessWithNotify($"程序已保存: {filePath}");
            }
            catch (Exception ex)
            {
                LoggerHelper.ErrorWithNotify($"保存文件失败: {ex.Message}");
            }
        }
        private ProgramModel ClearDeviceParameterValue(ProgramModel program)
        {
            var tmp = new ProgramModel(program);
            foreach (var step in tmp.StepCollection)
            {
                if (step.SubProgram != null)
                {
                    step.SubProgram = ClearDeviceParameterValue(step.SubProgram);
                }
            }
            return tmp;
        }

        private void Save()
        {
            if(_globalVariables.CurrentFilePath == null)
            {
                SaveAs();
                return;
            }
            SaveProgramToFile(_globalVariables.CurrentFilePath);
            
        }
        private void Stop()
        {
            if (_globalVariables.IsStop == false)
            {
                LoggerHelper.InfoWithNotify(_globalVariables.UserName + "执行停止命令");
                IsTerminate = true;
                _globalVariables.IsStop = null;
                RunState = "运行";
                RunIcon = PackIconKind.Play;
                _stepRunning.stepCTS.Cancel();
            }
        }

        private void Resotration()
        {
            LoggerHelper.InfoWithNotify(_globalVariables.UserName + "执行复位命令");
            IsTerminate = false;
            currentExecutionTask = null;
            _stepRunning.stepCTS = new();
            _globalVariables.IsStop = null;
            _stepRunning.ResetAllStepStatus(_globalVariables.Program);
        }

        private async void RunSingle()
        {
            if (RunState == "运行")
            {
                SingleStep = true;
                LoggerHelper.InfoWithNotify(_globalVariables.UserName + "执行单步执行命令");
                RunState = "暂停";
                RunIcon = PackIconKind.Pause;
                if (_globalVariables.IsStop == null)
                {
                    _globalVariables.IsStop = false;
                    if(currentExecutionTask==null)currentExecutionTask = _stepRunning.ExecuteSteps(_globalVariables.Program, cancellationToken: _stepRunning.stepCTS.Token);
                    await currentExecutionTask;
                    RunState = "运行";
                    RunIcon = PackIconKind.Play;
                    _globalVariables.IsStop = null;
                    IsTerminate = true;
                }
                else if (_globalVariables.IsStop == true)
                {
                    _globalVariables.IsStop = false;
                }
            }
        }

        private async void Running()
        {

            if (RunState == "运行")
            {
                SingleStep = false;
                LoggerHelper.InfoWithNotify(_globalVariables.UserName + "执行运行命令");
                RunState = "暂停";
                RunIcon = PackIconKind.Pause;
                if (_globalVariables.IsStop == null)
                {
                    _globalVariables.IsStop = false;
                    if (currentExecutionTask == null) currentExecutionTask = _stepRunning.ExecuteSteps(_globalVariables.Program, cancellationToken: _stepRunning.stepCTS.Token);
                    await currentExecutionTask;
                    RunState = "运行";
                    RunIcon = PackIconKind.Play;
                    _globalVariables.IsStop = null;
                    IsTerminate = true;
                }
                else if (_globalVariables.IsStop == true)
                {
                    _globalVariables.IsStop = false;
                }
            }
            else
            {
                LoggerHelper.InfoWithNotify(_globalVariables.UserName + "点击暂停命令");
                _globalVariables.IsStop = true;
                RunState = "运行";
                RunIcon = PackIconKind.Play;
            }
        }

        private void LeftDrawerOpen()
        {
            IsLeftDrawerOpen = true;
        }
        private void MinimizeWindow(Window window)
        {
            if (window != null)
                window.WindowState = WindowState.Minimized;
        }

        private void MaximizeWindow(Window window)
        {
            if (window != null)
            {
                window.WindowState = window.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
            }
        }

        private void CloseWindow(Window window)
        {
            window?.Close();
        }
        #endregion

        private void UpdateRunIcon(string obj)
        {
            RunIcon = obj switch
            {
                "Play" => PackIconKind.Play,
                "Pause" => PackIconKind.Pause,
                _ => RunIcon
            };
        }
        private void Load()
        {
            SystemConfig.Instance.LoadFromFile();
            if (SystemConfig.Instance.DefaultSubProgramFilePath != null)
            {
                if (File.Exists(SystemConfig.Instance.DefaultSubProgramFilePath))
                {
                    Open(SystemConfig.Instance.DefaultSubProgramFilePath);
                }
            }
            Title = SystemConfig.Instance.Title;
        }
    }
}
