using DocumentFormat.OpenXml.Bibliography;
using MECF.Framework.Common.Beckhoff.IOAxis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MECF.Framework.Common.TwinCat
{
    public class BeckhoffCounterValue
    {
        #region 常量
        private const string COUNTER_VALUE = "CounterValue";
        private const double MAX_COUNTS = 4294967296.0;
        #endregion
        #region 内部变量
        /// 
        /// counter对象
        /// 
        private BeckhoffCounter _counter;
        /// 
        /// 数值
        /// 
        private double _value;
        /// 
        /// 启动时间
        /// 
        private DateTime _startTime = DateTime.Now;
        /// 
        /// 时长
        /// 
        private TimeSpan _elapsedTime = TimeSpan.Zero;
        /// 
        /// 上一次计数
        /// 
        private int _previousCounts { get; set; } 
        /// 
        /// 首次
        /// 
        private bool first = true;
        private bool _resetCounter = false;
        /// 
        /// 上一次数值
        /// 
        private DateTime _lastTime= DateTime.Now;
        /// 
        /// 定时器
        /// 
        private System.Timers.Timer _timer;
        /// 
        /// 定时器记录的数值
        /// 
        private int _timerCounter = 0;
        #endregion
        #region 事件
        public event BeckhoffDelegate.OnUpdateVariableCounterValue OnUpdateVariableCounterValue;
        #endregion
        /// 
        /// 构造函数
        /// 
        /// 
        public BeckhoffCounterValue(BeckhoffCounter counter)
        {
            _counter = counter;
            if (counter.Mode != 0)
            {
                _timer = new System.Timers.Timer();
                _timer.Interval = 5000;
                _timer.Elapsed += Timer_Elapsed;
                _timer.Start();
            }
        }
        /// 
        /// 定时器
        /// 
        /// 
        /// 
        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (_timerCounter == _previousCounts)
            {
                if (OnUpdateVariableCounterValue != null)
                {
                    string key = _counter.Name;
                    string inputName = $"{key}.{COUNTER_VALUE}";
                    OnUpdateVariableCounterValue(inputName, 0);
                }
            }
            else
            {
                _timerCounter = _previousCounts;
            }
        }
        /// 
        /// 启动
        /// 
        public void Start()
        {
        }
        /// 
        /// 停止
        /// 
        public void Stop()
        {
        }
        /// 
        /// 重置
        /// 
        public void Reset()
        {
            _resetCounter = true;
            _value = 0;
            _previousCounts = 0;
            BeckhoffCounterManager.Instance.SetCounterValue($"{_counter.Name}.{COUNTER_VALUE}", 0);
        }
        /// 
        /// 设置数值
        /// 
        /// 
        public void SetValue(int value)
        {
            if (_counter.Mode == 0)
            {
                SetNormalValue(value);
            }
            else if (_counter.Mode == 1)
            {
                SetRateValue(value);
            }
            else if(_counter.Mode==2)
            {
                SetTotalValue(value);
            }
        }
        /// 
        /// 设置常规数值
        /// 
        /// 
        private void SetNormalValue(int value)
        {
            if (!string.IsNullOrEmpty(_counter.Scaling))
            {
                var result = ScalingManager.Instance.CalculateValueByTwincatVariable($"{_counter.Name}.{COUNTER_VALUE}", value);
                if (result.Item1)
                {
                    _value = result.Item2;
                }
                else
                {
                    _value = value;
                }
            }
            else
            {
                _value = value;
            }
        }
        /// 
        /// 设置比例数值
        /// 
        /// 
        private void SetRateValue(int value)
        {
            _lastTime = DateTime.Now;
            double scaledValue = 0.0;
            double currentCounts = 0.0;
            double tDelta = ElapsedTime();
            double currentCounter = _value;
            if(value==0)
            {
                _value = 0;
                _previousCounts = 0;
                return;
            }
            if (_previousCounts == 0)
            {
                _previousCounts = value;
                _value = 0;
                StartTimer();
                return;
            }
            if (tDelta*1000>_counter.Period)
            {
                if (value < _previousCounts)
                    currentCounts = (MAX_COUNTS - _previousCounts) + value;
                else
                    currentCounts = value - _previousCounts;
                if (!string.IsNullOrEmpty(_counter.Scaling))
                {
                    var result = ScalingManager.Instance.CalculateValueByTwincatVariable($"{_counter.Name}.{COUNTER_VALUE}", (currentCounts / tDelta));
                    if (result.Item1)
                    {
                        double rate = result.Item2;
                        if(first||rate!=scaledValue)
                        {
                            first = false;
                            scaledValue = rate;
                        }
                    }
                    else
                    {
                        scaledValue=currentCounter/tDelta;
                    }
                }
                else
                {
                    scaledValue = currentCounter / tDelta;
                }
                _previousCounts = value;
                StartTimer();
            }
            else
            {
                scaledValue = currentCounter;
            }
            _value = scaledValue;
        }
        /// 
        /// 设置统计数值
        /// 
        /// 
        private void SetTotalValue(int value)
        {
            double scaledValue = this._value;
            double deltaValue;
            if (!_resetCounter && !first)
            {
                int deltaCount = unchecked(value - _previousCounts);
                var result = ScalingManager.Instance.CalculateValueByTwincatVariable($"{_counter.Name}.{COUNTER_VALUE}", deltaCount);
                if (result.Item1)
                {
                    deltaValue= result.Item2;
                }
                else
                {
                    deltaValue = deltaCount;
                }
            }
            else
            {
                _resetCounter = false;
                first = false;
                deltaValue = 0.0;
            }
            _previousCounts = value;
            scaledValue += deltaValue;
            _value = scaledValue;
        }
        /// 
        /// 获取数值
        /// 
        /// 
        public double GetValue()
        {
            if(_counter.Mode==1)
            {
                if (DateTime.Now.Subtract(_lastTime).TotalMilliseconds > _counter.Period)
                {
                    _value = 0;
                }
            }
            return _value;
        }
        /// 
        /// 启动计时
        /// 
        private void StartTimer()
        {
            _startTime = DateTime.Now;
            _elapsedTime = TimeSpan.Zero;
        }
        /// 
        /// 计算时长
        /// 
        /// 
        private double ElapsedTime()
        {
            _elapsedTime = DateTime.Now - _startTime;
            return _elapsedTime.TotalSeconds;
        }
    }
}