using BDU.Models;
using BDU.Tools;
using BDU.Windows;
using PropertyChanged;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
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;
using Timer = System.Timers.Timer;

namespace BDU.Views
{
    /// <summary>
    /// StepsManager.xaml 的交互逻辑
    /// </summary>
    public partial class StepsManager : UserControl, INotifyPropertyChanged
    {
        public static StepsManager? Instance { get; private set; }

        private string _title = "主程序  NewProgram.ats";
        public string Title
        {
            get => _title;
            set
            {
                if (_title != value)
                {
                    _title = value;
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Title)));
                }
            }
        }

        /// <summary>
        /// 更新 Title 显示，根据当前状态自动判断显示主程序或子程序名称
        /// </summary>
        public void UpdateTitle(string? subProgramName = null)
        {
            if (!string.IsNullOrEmpty(subProgramName))
            {
                // 如果传入了子程序名称，显示子程序标题
                Title = $"子程序  {subProgramName}";
            }
            else
            {
                // 否则显示主程序标题
                var tmp = MainWindow.Instance?.CurrentFilePath?.Split("\\");
                if (tmp != null && tmp.Length > 1)
                {
                    Title = "主程序  " + tmp[^1];
                }
                else
                {
                    Title = "主程序  " + (tmp?.LastOrDefault() ?? "NewProgram.ats");
                }
            }
        }
        public ProgramModel Program => MainWindow.Instance.Program ?? new();

        public object SelectedItem => ProgramDataGrid.SelectedItem;

        public int SelectedIndex
        {
            get { return ProgramDataGrid.SelectedIndex; }
            set { ProgramDataGrid.SelectedIndex = value; }
        }

        public bool IsAdmin => MainWindow.Instance.User.Role > 0;

        private List<StepModel> tmpCopyList = [];

        #region 辅助方法

        private void ReOrderProgramList()
        {
            for (int i = 0; i < Program.StepCollection.Count; i++)
            {
                Program.StepCollection[i].Index = i + 1;
            }
        }

        #endregion

        public StepsManager()
        {
            Instance = this;
            InitializeComponent();
            DataContext = this;
            MainWindow.Instance.PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == nameof(MainWindow.Program))
                {
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Program)));
                }
                else if (e.PropertyName == nameof(MainWindow.CurrentFilePath))
                {
                    // 当主程序文件路径变化时，更新 Title
                    UpdateTitle();
                }
            };
            // 初始化 Title
            UpdateTitle();
        }

        private void StepEdit_Click(object sender, RoutedEventArgs e)
        {
            if (MainWindow.Instance.User.Role < 1)
            {
                MessageBox.Show("当前登录用户无权限");
                return;
            }

            if (MainWindow.Instance.SelectedStep != null)
            {
                MainWindow.Instance.SelectedStep = null;
            }

            if (ProgramDataGrid.SelectedItem is StepModel selectedStep)
            {
                // 如果是子程序类型，进入子程序编辑模式
                if (selectedStep.StepType == "子程序" && selectedStep.SubProgram != null)
                {
                    // 使用步骤的 Name 作为子程序的显示名称
                    string subProgramName = selectedStep.Name ?? "未命名子程序";

                    MainWindow.Instance.EnterSubProgramMode(
                        selectedStep.SubProgram, // 传递子程序模型
                        subProgramName,          // 传递子程序名称（来自步骤名称）
                        selectedStep             // 传递父步骤引用，用于保存时回写
                    );
                    
                    // 更新 StepsManager 的 Title 显示子程序名称
                    UpdateTitle(subProgramName);
                }
                else
                {
                    // 原有逻辑：编辑普通步骤
                    MainWindow.Instance.SelectedStep = new(selectedStep);
                    if (MainWindow.Instance.SelectedStep.Method != null)
                    {
                        if (MainWindow.Instance.SelectedStep.StepType == "循环开始")
                        {
                            MainWindow.Instance.SelectedStep.Method.Parameters[0].Value = MainWindow.Instance.SelectedStep.LoopCount;
                        }
                        else
                        {
                            foreach (var para in MainWindow.Instance.SelectedStep.Method.Parameters)
                            {
                                var tmppara = Program.Parameters.FirstOrDefault(x => x.ID == para.VariableID);
                                if (tmppara == null) continue;
                                para.VariableName = tmppara.Name;
                            }
                        }
                    }
                    else if (MainWindow.Instance.SelectedStep.SubProgram != null)
                    {
                        foreach (var para in MainWindow.Instance.SelectedStep.SubProgram.Parameters)
                        {
                            var tmppara = Program.Parameters.FirstOrDefault(x => x.ID == para.VariableID);
                            if (tmppara == null) continue;
                            para.VariableName = tmppara.Name;
                        }
                    }
                }
            }
        }

        private async void StepDelete_Click(object sender, RoutedEventArgs e)
        {
            if (MainWindow.Instance.User.Role < 1)
            {
                MessageBox.Show("当前登录用户无权限");
                return;
            }
            MessageBoxResult result = MessageBox.Show($"确定执行删除操作？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                List<StepModel> tmpList = [];
                foreach (var item in ProgramDataGrid.SelectedItems)
                {
                    if (item is StepModel selectedStep)
                    {
                        tmpList.Add(selectedStep);
                    }
                }
                List<int> deleteIndexList = [.. tmpList.OrderBy(x => x.Index).Select(x => x.Index)];
                foreach (var item in tmpList)
                {
                    Program.StepCollection.Remove(item);
                }
                await Task.Yield();
                if (tmpList.Count == 1)
                {
                    Log.Success($"用户 [ {MainWindow.Instance.User.UserName} ] 删除步骤 [ {tmpList[0].Index} ] ");
                }
                else if (tmpList.Count > 1)
                {
                    Log.Success($"用户 [ {MainWindow.Instance.User.UserName} ] 删除步骤 [ {string.Join("、", deleteIndexList)} ] ");
                }
                ReOrderProgramList();
            }
        }

        private void StepCopy_Click(object sender, RoutedEventArgs e)
        {
            tmpCopyList.Clear();
            foreach (var item in ProgramDataGrid.SelectedItems)
            {
                if (item is StepModel selectedStep)
                {
                    tmpCopyList.Add(selectedStep);
                }
            }
        }

        private void StepPaste_Click(object sender, RoutedEventArgs e)
        {
            if (MainWindow.Instance.User.Role < 1)
            {
                MessageBox.Show("当前登录用户无权限");
                return;
            }
            var insertIndex = SelectedIndex + 1;
            List<int> copyIndexList = [.. tmpCopyList.OrderBy(x => x.Index).Select(x => x.Index)];
            foreach (var item in tmpCopyList)
            {
                Program.StepCollection.Insert(insertIndex, new(item) { ID = Guid.NewGuid() });
                insertIndex++;
            }
            if (tmpCopyList.Count == 1)
            {
                Log.Success($"用户 [ {MainWindow.Instance.User.UserName} ] 粘贴步骤 [ {tmpCopyList[0].Index} ] 到 [ {insertIndex} ] ");
            }
            else if (tmpCopyList.Count > 1)
            {
                Log.Success($"用户 [ {MainWindow.Instance.User.UserName} ] 粘贴步骤 [ {string.Join("、", copyIndexList)} ] 到 [ {insertIndex + 1 - tmpCopyList.Count} - {insertIndex} ] ");
            }
            ReOrderProgramList();
        }
        private void SetOrCancelBroken_Click(object sender, RoutedEventArgs e)
        {
            foreach (var item in ProgramDataGrid.SelectedItems)
            {
                if (item is StepModel selectedStep)
                {
                    selectedStep.isBrokenpoint = selectedStep.isBrokenpoint == null|| selectedStep.isBrokenpoint == false ? true : false;
                }
            }
        }
        private void StepManager_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Delete:
                    StepDelete_Click(sender, e);
                    break;

                case Key.C:
                    if (Keyboard.Modifiers == ModifierKeys.Control)
                    {
                        StepCopy_Click(sender, e);
                    }
                    break;

                case Key.V:
                    if (Keyboard.Modifiers == ModifierKeys.Control)
                    {
                        StepPaste_Click(sender, e);
                    }
                    break;

            }
        }




        // 在 StepsManager 中添加
        public ProgramModel CurrentProgram
        {
            get => (ProgramModel)GetValue(CurrentProgramProperty);
            set => SetValue(CurrentProgramProperty, value);
        }

        public static readonly DependencyProperty CurrentProgramProperty =
            DependencyProperty.Register("CurrentProgram", typeof(ProgramModel), typeof(StepsManager),
                new PropertyMetadata(null, OnCurrentProgramChanged));

        private static void OnCurrentProgramChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var stepsManager = (StepsManager)d;
            // 更新绑定
            stepsManager.DataContext = e.NewValue;
        }

    }
}
