using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.DBCore;
using Aitex.Core.RT.Event;
using MECF.Framework.Common.DBCore;
using System;
using System.Data;

namespace MECF.Framework.Common.Aitex.Core.RT.EMS
{
    /// <summary>
    /// 监控工艺时间触发保养
    /// </summary>
    public class ProcessMaintainer : TimeMaintainer
    {
        #region Variables

        

        #endregion

        #region Constructors
        public ProcessMaintainer()
        {

        }

        public ProcessMaintainer(MaintainerItemCollection item, string name, string module, int index, string description, bool enabled, DateTime startdate, double threshold, TimeUnit timeexceedunit)
            : base(item, name, module, index, description, enabled, startdate, threshold, timeexceedunit)
        {
            _info.Type = nameof(ProcessMaintainer);
            if (_info.Module == "PM1" || _info.Module == "PM2")
            {
                _getProcessing = new Func<bool>(() => {
                    var r = DATA.Poll(_info.Module + ".IsProcessing");
                    if (r != null)
                    {
                        return (bool)r;
                    }
                    return false;
                }
                );
            }
        }

        public ProcessMaintainer(MaintainerItemCollection item, MaintainerInfo info, DateTime startdate, double threshold)
            : base(item, info, startdate, threshold)
        {
            _info.Type = nameof(ProcessMaintainer);
            if (_info.Module == "PM1" || _info.Module == "PM2")
            {
                _getProcessing = new Func<bool>(() => {
                    var r = DATA.Poll(_info.Module + ".IsProcessing");
                    if (r != null)
                    {
                        return (bool)r;
                    }
                    return false;
                }
                );
            }
        }
        
        #endregion

        #region Methods

        public override void Monitor()
        {
            DateTime now = DateTime.Now;
            _isProcessing = _getProcessing();

            ////①确认未使能;没有维护项也不进行计算
            if (!_info.Enable || _itemCollection.Count == 0)
            {
                _isTimeOut = false;
                _timeExceed = 0;
                _valueElapsed = 0;
                _value = 0;
            }
            else
            {
                UpdateValue();

                _itemCollection.CheckAllItemMaintained(_startDate);
                if (_unMaintainedCount == 0)
                {
                    Reset(); //所有项都维护，翻转沙漏
                }
                
                if (_valueElapsed == 0)
                {
                    if (!_isTimeOut && !_trigDate.HasValue)
                    {
                        _trigDate = now;
                    }
                    _isTimeOut = true;
                    if (_unMaintainedCount != 0)
                    {
                        if (_trigDate.HasValue)
                        {
                            _timeExceed = DateTimeHelper.DateTimeSubtraction(_trigDate.Value, now, TimeUnit.Seconds);
                        }
                    }
                }
            }
            
            ////④确认超时上升沿
            base.Monitor();
        }

        private void UpdateValue()
        {
            string sql = $"Select \"Process_Seconds\" from \"runtime_data2\" where \"Module\"='{_info.Module}';";
            DataSet dataSet = DB.ExecuteDataSet(sql);
            if (dataSet != null && dataSet.Tables != null && dataSet.Tables.Count == 1)
            {
                if (dataSet.Tables[0].Rows.Count == 1)
                {
                    _value = Convert.ToInt64(dataSet.Tables[0].Rows[0]["Process_Seconds"].ToString());
                    _valueElapsed = _threshold - _value;
                    if (_valueElapsed <= 0)
                    {
                        _valueExceed = -_valueElapsed;
                        _valueElapsed = 0;
                    }
                }
                else if (dataSet.Tables[0].Rows.Count == 0)
                {
                    sql = $"INSERT INTO \"runtime_data2\" ( \"Module\", \"Process_Seconds\")VALUES ('{_info.Module}',{_value});";
                    DB.ExecuteNonQuery(sql);
                }
            }
        }

        public override bool Reset()
        {
            if (!_info.Enable)
            {
                EV.PostWarningLog("Maintenance", $"Plan {_info.Name} is disable,can not be reset");
                return false;
            }
            if (!CanReset())
            {
                return false;
            }

            _isTimeOut = false;
            DateTime now = DateTime.Now;
            _startDate = now;
            _trigDate = null;
            _value = 0;

            RuntimeDataRecorder.ResetElapseTimePM(_info.Module);

            _timeExceed = 0;
            _valueElapsed = DateTimeHelper.SecondsTransform(_threshold, TimeUnit.Seconds);
            _valueExceed = 0;

            _itemCollection.CheckAllItemMaintained(_startDate);

            return base.Reset();
        }

        #endregion
    }
}
