using BOB.Singleton;
using BOB.ViewModels.UserControls;
using Common.PubEvent;
using DeviceCommand.Device;
using Logger;
using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Legends;
using OxyPlot.Series;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using SqlSugar;
using System;
using System.Windows.Input;

namespace BOB.ViewModels.Dialogs
{
    public class BackfeedViewModel : BindableBase, IDialogAware
    {
        #region 属性

        private string _Title = "反灌电压";
        public string Title
        {
            get { return _Title; }
            set { SetProperty(ref _Title, value); }
        }

        private string _设备标识字符串;
        public string 设备标识字符串
        {
            get { return _设备标识字符串; }
            set { SetProperty(ref _设备标识字符串, value); }
        }

        private string _输出电压;
        public string 输出电压
        {
            get { return _输出电压; }
            set { SetProperty(ref _输出电压, value); }
        }

        private string _输出电流;
        public string 输出电流
        {
            get { return _输出电流; }
            set { SetProperty(ref _输出电流, value); }
        }

        private string _OCP电流;
        public string OCP电流
        {
            get { return _OCP电流; }
            set { SetProperty(ref _OCP电流, value); }
        }

        private string _OVP电压;
        public string OVP电压
        {
            get { return _OVP电压; }
            set { SetProperty(ref _OVP电压, value); }
        }

        private string _OPP功率;
        public string OPP功率
        {
            get { return _OPP功率; }
            set { SetProperty(ref _OPP功率, value); }
        }
        private LineSeries _电压_lineSeries = new LineSeries { Title = "电压(V)", StrokeThickness = 2 };
        public LineSeries 电压_lineSeries
        {
            get => _电压_lineSeries;
            set => SetProperty(ref _电压_lineSeries, value);
        }

        private LineSeries _电流_lineSeries = new LineSeries { Title = "电流(A)", StrokeThickness = 2 };
        public LineSeries 电流_lineSeries
        {
            get => _电流_lineSeries;
            set => SetProperty(ref _电流_lineSeries, value);
        }

        private LineSeries _功率_lineSeries = new LineSeries { Title = "功率(W)", StrokeThickness = 2 };
        public LineSeries 功率_lineSeries
        {
            get => _功率_lineSeries;
            set => SetProperty(ref _功率_lineSeries, value);
        }
        private NumericalDisplayViewModel _电压MV = new NumericalDisplayViewModel();
        public NumericalDisplayViewModel 电压MV
        {
            get => _电压MV;
            set => SetProperty(ref _电压MV, value);
        }

        private NumericalDisplayViewModel _电流MV = new NumericalDisplayViewModel();
        public NumericalDisplayViewModel 电流MV
        {
            get => _电流MV;
            set => SetProperty(ref _电流MV, value);
        }

        private NumericalDisplayViewModel _功率MV = new NumericalDisplayViewModel();
        public NumericalDisplayViewModel 功率MV
        {
            get => _功率MV;
            set => SetProperty(ref _功率MV, value);
        }
        private PlotModel _曲线Model = new PlotModel();
        public PlotModel 曲线Model
        {
            get => _曲线Model;
            set => SetProperty(ref _曲线Model, value);
        }
        public DateTimeAxis TimeAxis { get; private set; }
        public LinearAxis ValueAxis { get; private set; }
        #endregion

        #region 命令

        public ICommand ConnectCommand { get; private set; }
        public ICommand DisconnectCommand { get; private set; }
        public ICommand QueryDeviceCommand { get; private set; }
        public ICommand SetVoltageCommand { get; private set; }
        public ICommand SetCurrentCommand { get; private set; }
        public ICommand EnableOCPCommand { get; private set; }
        public ICommand DisableOCPCommand { get; private set; }
        public ICommand SetOCPCommand { get; private set; }
        public ICommand EnableOVPCommand { get; private set; }
        public ICommand DisableOVPCommand { get; private set; }
        public ICommand SetOVPCommand { get; private set; }
        public ICommand EnableOPPCommand { get; private set; }
        public ICommand DisableOPPCommand { get; private set; }
        public ICommand SetOPPCommand { get; private set; }
        public ICommand CloseCommand { get; private set; }
        public ICommand ResetViewCommand { get; private set; }

        #endregion


        private IEventAggregator _eventAggregator { get;set; }
        private Devices _devices { get; set; }
        private GlobalVariables _globalVariables { get; set; }
        private object device { get; set; }

        public BackfeedViewModel(IContainerProvider containerProvider)
        {
            _devices = containerProvider.Resolve<Devices>();
            _globalVariables = containerProvider.Resolve<GlobalVariables>();
            _eventAggregator = containerProvider.Resolve<IEventAggregator>();

            // Initialize commands
            ConnectCommand = new AsyncDelegateCommand(OnConnect);
            DisconnectCommand = new DelegateCommand(OnDisconnect);
            QueryDeviceCommand = new AsyncDelegateCommand(OnQueryDevice);
            SetVoltageCommand = new AsyncDelegateCommand(OnSetVoltage);
            SetCurrentCommand = new AsyncDelegateCommand(OnSetCurrent);
            EnableOCPCommand = new AsyncDelegateCommand(OnEnableOCP);
            DisableOCPCommand = new AsyncDelegateCommand(OnDisableOCP);
            SetOCPCommand = new AsyncDelegateCommand(OnSetOCP);
            EnableOVPCommand = new AsyncDelegateCommand(OnEnableOVP);
            DisableOVPCommand = new AsyncDelegateCommand(OnDisableOVP);
            SetOVPCommand = new AsyncDelegateCommand(OnSetOVP);
            EnableOPPCommand = new AsyncDelegateCommand(OnEnableOPP);
            DisableOPPCommand = new AsyncDelegateCommand(OnDisableOPP);
            SetOPPCommand = new AsyncDelegateCommand(OnSetOPP);
            CloseCommand = new DelegateCommand(OnClose);
            ResetViewCommand = new DelegateCommand(ResetView);
            _eventAggregator.GetEvent<CurveDataEvent>().Subscribe(UpdateCurve);
            InitCurve();
        }
        private void ResetView()
        {
            曲线Model.ResetAllAxes();
            曲线Model.InvalidatePlot(true);
        }
        private void InitCurve()
        {
            TimeAxis = new DateTimeAxis
            {
                Position = AxisPosition.Bottom,
                StringFormat = "HH:mm:ss",
                IntervalType = DateTimeIntervalType.Seconds,
            };
            ValueAxis = new LinearAxis
            {
                Position = AxisPosition.Left,
            };
            曲线Model.Axes.Add(TimeAxis);
            曲线Model.Axes.Add(ValueAxis);
            曲线Model.Series.Add(电压_lineSeries);
            曲线Model.Series.Add(电流_lineSeries);
            曲线Model.Series.Add(功率_lineSeries);
            曲线Model.Legends.Add(new Legend()
            {
                LegendPosition = LegendPosition.TopRight,
                LegendOrientation = LegendOrientation.Vertical,
                LegendPlacement = LegendPlacement.Inside
            });

            曲线Model.InvalidatePlot(true);
        }

        private void UpdateCurve((string device, Dictionary<string, double> data )tuple)
        {
            var (device, data) = tuple;
            if (device != "IT6724C") return;
            电流MV.MonitorValue = data["实时电流"];
            电压MV.MonitorValue = data["实时电压"];
            功率MV.MonitorValue = data["实时功率"];

            var now = DateTimeAxis.ToDouble(DateTime.Now);
            电流_lineSeries.Points.Add(new DataPoint(now, data["实时电流"]));
            电压_lineSeries.Points.Add(new DataPoint(now, data["实时电压"]));
            功率_lineSeries.Points.Add(new DataPoint(now, data["实时功率"]));
            曲线Model.InvalidatePlot(true);
        }


        #region Command Handlers

        private async Task OnConnect()
        {
            if (device is E36233A e36233A)
            {
                await e36233A.ConnectAsync();
            }
            else if (device is IT6724CReverse it6724CReverse)
            {
                await it6724CReverse.ConnectAsync();
            }
        }

        private void OnDisconnect()
        {
            if (device is E36233A e36233A)
            {
                e36233A.Close();
            }
            else if (device is IT6724CReverse it6724CReverse)
            {
                it6724CReverse.Close();
            }
        }

        private async Task OnQueryDevice()
        {
            if (device is E36233A e36233A)
            {
                设备标识字符串 = await e36233A.查询设备信息();
            }
            else if (device is IT6724CReverse it6724CReverse)
            {
                设备标识字符串 = await it6724CReverse.查询设备信息();
            }
        }

        private async Task OnSetVoltage()
        {
            if (device is E36233A e36233A)
            {
                await e36233A.设置电压(Convert.ToDouble(输出电压));
            }
            else if (device is IT6724CReverse it6724CReverse)
            {
                await it6724CReverse.设置电压(Convert.ToDouble(输出电压));
            }
        }

        private async Task OnSetCurrent()
        {
            if (device is E36233A e36233A)
            {
                await e36233A.设置电流(Convert.ToDouble(输出电流));
            }
            else if (device is IT6724CReverse it6724CReverse)
            {
                await it6724CReverse.设置电流(Convert.ToDouble(输出电流));
            }
        }

        private async Task OnEnableOCP()
        {
            if (device is E36233A e36233A)
            {
                await e36233A.设置OCP开关(true);
            }
            else if (device is IT6724CReverse it6724CReverse)
            {
                await it6724CReverse.设置OCP开关(true);
            }
        }

        private async Task OnDisableOCP()
        {
            if (device is E36233A e36233A)
            {
                await e36233A.设置OCP开关(false);
            }
            else if (device is IT6724CReverse it6724CReverse)
            {
                await it6724CReverse.设置OCP开关(false);
            }
        }

        private async Task OnSetOCP()
        {
            if (device is E36233A e36233A)
            {
                await e36233A.设置电流保护OCP电流(Convert.ToDouble(OCP电流));
            }
            else if (device is IT6724CReverse it6724CReverse)
            {
                await it6724CReverse.设置电流保护OCP电流(Convert.ToDouble(OCP电流));
            }
        }

        private async Task OnEnableOVP()
        {
            if (device is E36233A e36233A)
            {
                await e36233A.设置OVP开关(true);
            }
            else if (device is IT6724CReverse it6724CReverse)
            {
                await it6724CReverse.设置OVP开关(true);
            }
        }

        private async Task OnDisableOVP()
        {
            if (device is E36233A e36233A)
            {
                await e36233A.设置OVP开关(false);
            }
            else if (device is IT6724CReverse it6724CReverse)
            {
                await it6724CReverse.设置OVP开关(false);
            }
        }

        private async Task OnSetOVP()
        {
            if (device is E36233A e36233A)
            {
                await e36233A.设置电压保护OVP电压(Convert.ToDouble(OVP电压));
            }
            else if (device is IT6724CReverse it6724CReverse)
            {
                await it6724CReverse.设置电压保护OVP电压(Convert.ToDouble(OVP电压));
            }
        }

        private async Task OnEnableOPP()
        {
            if (device is E36233A e36233A)
            {
                await e36233A.设置OVP开关(true);
            }
            else if (device is IT6724CReverse it6724CReverse)
            {
                await it6724CReverse.设置OVP开关(true);
            }
        }

        private async Task OnDisableOPP()
        {
            if (device is E36233A e36233A)
            {
                await e36233A.设置OVP开关(false);
            }
            else if (device is IT6724CReverse it6724CReverse)
            {
                await it6724CReverse.设置OVP开关(false);
            }
        }

        private async Task OnSetOPP()
        {
            if (device is E36233A e36233A)
            {
                await e36233A.设置功率保护功率(Convert.ToDouble(OPP功率));
            }
            else if (device is IT6724CReverse it6724CReverse)
            {
                await it6724CReverse.设置功率保护功率(Convert.ToDouble(OPP功率));
            }
        }

        private void OnClose()
        {
            RequestClose.Invoke();
        }


        #endregion

        #region Dialog规范

        public DialogCloseListener RequestClose { get; set; }

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            // Implement cleanup logic here if needed
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            try
            {
                if (_devices.DeviceDic.ContainsKey("E36233A"))
                {
                    var a = _devices.DeviceDic["E36233A"] as E36233A;
                    if (a != null)
                    {
                        device = a;
                    }
                    else
                    {
                        LoggerHelper.ErrorWithNotify("设备没有初始化无法打开测试界面");
                        RequestClose.Invoke();
                    }
                }
                else if (_devices.DeviceDic.ContainsKey("IT6724CReverse"))
                {
                    var a = _devices.DeviceDic["IT6724CReverse"] as IT6724CReverse;
                    if (a != null)
                    {
                        device = a;
                    }
                    else
                    {
                        LoggerHelper.ErrorWithNotify("设备没有初始化无法打开测试界面");
                        RequestClose.Invoke();
                    }

                }
            }
            catch (Exception)
    {
                LoggerHelper.ErrorWithNotify("找不到设备无法打开测试界面");
            }

        }
        #endregion
    }
}
