using MainShell.Hardware;
using MaxwellControl.Tools;
using MaxwellFramework.Core.Interfaces;
using MwFramework.Device;
using MwFramework.Controls.UIControl;
using MwFramework.ManagerService;
using Stylet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using static MainShell.ParaSetting.Model.SpeedSetting;
using MessageBox = MaxwellControl.Controls.MessageBox;

namespace MainShell.ParaSetting.ViewModel
{
    public class SpeedSettingViewModel:Screen,IPage
    {
        public string Name { get; set; } = "SpeedParaSys";

        private readonly IParamList _paramList;

        private ParameterHelper _parameterHelper = new ParameterHelper();
        public ParameterHelper ParameterHelper
        {
            get
            {
                return _parameterHelper;
            }
            set
            {
                _parameterHelper = value;
                OnPropertyChanged(nameof(ParameterHelper));
            }
        }
        private SpeedParaSysSetting _speedParaSysSetting;
        public SpeedParaSysSetting SpeedParaSysSetting
        {
            get
            {
                return _speedParaSysSetting;
            }
            set
            {
                _speedParaSysSetting = value;
                OnPropertyChanged(nameof(SpeedParaSysSetting));
            }
        }
        private double _speed = 10;
        public double Speed
        {
            get
            {
                return _speed;
            }
            set
            {
                _speed = value;
                OnPropertyChanged(nameof(Speed));
            }
        }

        private readonly HardwareManager _hardware;
        public SpeedSettingViewModel(IParameterManager parameterManager, HardwareManager hardware)
        {
            _paramList = parameterManager as IParamList;
            if (_paramList == null)
            {
                throw new ArgumentNullException(nameof(parameterManager));
            }

            _hardware = hardware ?? throw new ArgumentNullException(nameof(hardware));
        }

        protected override void OnViewLoaded()
        {
            base.OnViewLoaded();
            SpeedParaSysSetting = _paramList.GetParameter<SpeedParaSysSetting>();
            InitializeAxisSpeedItems();
        }

        private void InitializeAxisSpeedItems()
        {
            Dictionary<string, IAxis> axisNameDic = _hardware.AxesDic;
            if (SpeedParaSysSetting.SpeedTypeItemCollection.SpeedTypeItemList.Count != axisNameDic.Count)
            {
                SpeedParaSysSetting.SpeedTypeItemCollection.SpeedTypeItemList.Clear();
                foreach (var axisByIndex in axisNameDic)
                {
                    SpeedParaSysSetting.SpeedTypeItemCollection.SpeedTypeItemList.Add(new SpeedTypeItem
                    {
                        AxisName = axisByIndex.Key,
                    });
                }
            }
        }

        public void btnSet()
        {
            if (MessageBox.Show("是否保存", null, "确认保存", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
            {
                try
                {
                    SpeedParaSysSetting.Write();
                    LogWatchValueManager.Save(SpeedParaSysSetting.SpeedTypeItemCollection, "SpeedPara_速度规划");
                    ParameterHelper.RaiseValueAccept();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        public void btnRowData()
        {
            try
            {
                if (!Confirm("是否修改当前选中数据的速度")) return;

                IList<SpeedTypeItem> items = SpeedParaSysSetting?.SpeedTypeItemCollection?.SpeedTypeItemList;
                SpeedTypeItem selected = SpeedParaSysSetting?.SpeedTypeItemCollection?.CurrentSelectSpeedTypeItemList;
                if (items == null || selected == null)
                {
                    MessageBox.Show("未找到速度项或未选择项。");
                    return;
                }

                // 找到轴索引相同的项并更新
                SpeedTypeItem item = items.FirstOrDefault(x => x.AxisName == selected.AxisName);
                if (item != null)
                {
                    UpdateItem(item, Speed);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void btnPageData()
        {
            try
            {
                if (!Confirm("是否修改当前界面的速度")) return;

                var items = SpeedParaSysSetting?.SpeedTypeItemCollection?.SpeedTypeItemList;
                if (items == null)
                {
                    MessageBox.Show("未找到速度项。");
                    return;
                }

                ApplyTo(items, Speed);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
       
        /// <summary>
        /// 修改当前界面的龙门速度
        /// </summary>
        public void btnPageGantryData()
        {
            try
            {
                if (!Confirm("是否修改当前界面的龙门速度")) return;

                var items = SpeedParaSysSetting?.SpeedTypeItemCollection?.SpeedTypeItemList;
                if (items == null)
                {
                    MessageBox.Show("未找到速度项。");
                    return;
                }

                // 假设龙门轴号为 0..3（按 AxisIndex 判断，避免直接按列表索引）
                //var gantryItems = items.Where(x => x.AxisIndex >= 0 && x.AxisIndex <= 3);
                //ApplyTo(gantryItems, Speed);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
       
        /// <summary>
        /// 修改当前界面的Z和TH轴速度
        /// </summary>
        public void btnPageZAndTHData()
        {
            try
            {
                if (!Confirm("是否修改当前界面的Z和TH轴速度")) return;

                var items = SpeedParaSysSetting?.SpeedTypeItemCollection?.SpeedTypeItemList;
                if (items == null)
                {
                    MessageBox.Show("未找到速度项。");
                    return;
                }

               
                //var zthItems = items.Where(x => x.AxisIndex >= 4 && x.AxisIndex <= 6);
                //ApplyTo(zthItems, Speed);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #region Helpers
        private bool Confirm(string message)
        {
            return MessageBox.Show(message, null, "确认修改", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK;
        }

        private void ApplyTo(IEnumerable<SpeedTypeItem> items, double speed)
        {
            if (items == null) return;
            foreach (var it in items)
            {
                UpdateItem(it, speed);
            }
        }

        private void UpdateItem(SpeedTypeItem item, double speed)
        {
            if (item == null) return;
            item.Speed = speed;
            item.Acc = 10 * speed;
            item.Dec = 10 * speed;
            item.Jerk = 100 * speed;
        }
        #endregion
    }
}
