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 System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace BOB.ViewModels.Dialogs
{
    public class PSB11000ViewModel : 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 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 PowerOnCommand { get; private set; }
        public ICommand PowerOffCommand { get; private set; }
        public ICommand SetRemoteModeCommand { get; private set; }
        public ICommand QueryDeviceInfoCommand { get; private set; }
        public ICommand SwitchWorkingModeCommand { get; private set; }
        public ICommand SwitchDCSourceModeCommand { get; private set; }
        public ICommand SwitchLoadModeCommand { get; private set; }
        public ICommand SetCCVoltageCommand { get; private set; }
        public ICommand SetCCCurrentCommand { get; private set; }
        public ICommand SetOCPCurrentCommand { 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 PSB11000 device;
        public PSB11000ViewModel(IContainerProvider containerProvider)
        {
            _devices = containerProvider.Resolve<Devices>();
            _globalVariables = containerProvider.Resolve<GlobalVariables>();
            _eventAggregator = containerProvider.Resolve<IEventAggregator>();
            ConnectCommand = new AsyncDelegateCommand(OnConnect);
            DisconnectCommand = new DelegateCommand(OnDisconnect);
            PowerOnCommand = new AsyncDelegateCommand(OnPowerOn);
            PowerOffCommand = new AsyncDelegateCommand(OnPowerOff);
            SetRemoteModeCommand = new AsyncDelegateCommand(OnSetRemoteMode);
            QueryDeviceInfoCommand = new AsyncDelegateCommand(OnQueryDeviceInfo);
            SwitchWorkingModeCommand = new AsyncDelegateCommand(OnSwitchWorkingMode);
            SwitchDCSourceModeCommand = new AsyncDelegateCommand(OnSwitchDCSourceMode);
            SwitchLoadModeCommand = new AsyncDelegateCommand(OnSwitchLoadMode);
            SetCCVoltageCommand = new AsyncDelegateCommand(OnSetCCVoltage);
            SetCCCurrentCommand = new AsyncDelegateCommand(OnSetCCCurrent);
            SetOCPCurrentCommand = new AsyncDelegateCommand(OnSetOCPCurrent);
            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 void OnClose()
        {
            RequestClose.Invoke();
        }
        private async Task OnConnect()
        {
            await device.ConnectAsync();
        }

        private void OnDisconnect()
        {
            device.Close();
        }

        private async Task OnPowerOn()
        {
            await device.打开输出();
        }

        private async Task OnPowerOff()
        {
            await device.关闭输出();
        }

        private async Task OnSetRemoteMode()
        {
            await device.设置远程控制(true);
        }

        private async Task OnQueryDeviceInfo()
        {
            设备标识字符串=await device.查询设备信息();   
        }

        private async Task OnSwitchWorkingMode()
        {
           
        }

        private async Task OnSwitchDCSourceMode()
        {
            // Logic for switching DC source mode
        }

        private async Task OnSwitchLoadMode()
        {
            // Logic for switching load mode
        }

        private async Task  OnSetCCVoltage()
        {
            // Logic for setting CC voltage
        }

        private async Task OnSetCCCurrent()
        {
            // Logic for setting CC current
        }

        private async Task OnSetOCPCurrent()
        {

        }
        #endregion
        #region dialog规范
        public DialogCloseListener RequestClose { get; set; }

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {

        }

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

        }
        #endregion
    }
}
