using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using MECF.Framework.Common.DataCenter;
using MECF.Framework.Common.Utilities;
using System.Windows.Threading;
using Prism.Commands;
using Prism.Mvvm;
using MECF.Framework.Common.RecipeCenter;
using CyberX8_Core;
using CyberX8_MainPages.PMs;
using MECF.Framework.Common.OperationCenter;
using System.Windows.Input;
using MECF.Framework.Common.Persistent.Reservoirs;
using MECF.Framework.Common.CommonData.Reservoir;
using CyberX8_MainPages.Model;
using System.Collections.ObjectModel;
using OpenSEMI.ClientBase.Command;

namespace CyberX8_MainPages.ViewModels
{
    internal class DosingSystemViewModel : BindableBase
    {
        #region 常量
        private const int MAX_REPLEN_NUM = 4;
        #endregion

        #region 内部变量

        #region system
        /// <summary>
        /// rt查询key
        /// </summary>
        private List<string> _rtDataKeys = new List<string>();
        /// <summary>
        /// 时钟
        /// </summary>
        DispatcherTimer _timer;
        /// <summary>
        /// rt查询数据
        /// </summary>
        private Dictionary<string, object> _rtDataValueDic = new Dictionary<string, object>();
        #endregion

        #region Common
        /// <summary>
        /// Module
        /// </summary>
        private string _module;
        /// <summary>
        /// Operation Mode
        /// </summary>
        private string _operatingMode;
        /// <summary>
        /// 状态
        /// </summary>
        private string _state;
        /// <summary>
        /// Reservoirs Persistent数据
        /// </summary>
        private ReservoirsPersistentValue _reservoirsPersistent;
        /// <summary>
        /// Replens Persistent数据
        /// </summary>
        private Dictionary<string, ReplenPersistentValue> _replensPersistent = new Dictionary<string, ReplenPersistentValue>();
        /// <summary>
        /// 页面功能启用
        /// </summary>
        private bool _isEnabled;
        /// <summary>
        /// AutoMode页面功能启用
        /// </summary>
        private bool _isAutoEnabled;
        /// <summary>
        /// IsManualorAuto
        /// </summary>
        private bool _isManualorAuto;
        /// <summary>
        /// Reservoir数据
        /// </summary>
        private StandardHotReservoirData _reservoirData;
        #endregion

        #region recipe
        /// <summary>
        /// 当前的recipe
        /// </summary>
        private ResRecipe _currentRecipe;
        /// <summary>
        /// Recipe Mode
        /// </summary>
        private string _recipeMode;
        /// <summary>
        /// Selected Recipe Node
        /// </summary>
        private RecipeNode _selectedRecipeNode;
        /// <summary>
        /// Recipe Type
        /// </summary>
        private string _recipeType;
        /// <summary>
        /// Recipe Manager
        /// </summary>
        private UiRecipeManager _uiRecipeManager = new UiRecipeManager();
        #endregion

        #region DosingSystem      
        /// <summary>
        /// Replen Datas
        /// </summary>
        private ReplenData[] _replenDatas;
        /// <summary>
        /// Replen Data Collection
        /// </summary>
        private ObservableCollection<ReplenData> _replenDataCollection;
        /// <summary>
        /// Replen Items
        /// </summary>
        private ObservableCollection<bool> _replenEnable = new ObservableCollection<bool>(new bool[MAX_REPLEN_NUM]);
        /// <summary>
        /// Replen数量
        /// </summary>
        private int _replenNum;
        /// <summary>
        /// Replen Persistent数据集合
        /// </summary>
        private ObservableCollection<ReplenPersistentValue> _replensPersistentCollection;
        #endregion
        #endregion

        #region 属性

        #region Common
        /// <summary>
        /// Module
        /// </summary>
        public string Module
        {
            get { return _module; }
            set { SetProperty(ref _module, value); }
        }
        /// <summary>
        /// Operation Mode
        /// </summary>
        public string OperatingMode
        {
            get { return _operatingMode; }
            set { SetProperty(ref _operatingMode, value); }
        }
        /// <summary>
        /// 状态
        /// </summary>
        public string State
        {
            get { return _state; }
            set { SetProperty(ref _state, value); }
        }
        /// <summary>
        /// Reservoirs Persistent数据
        /// </summary>
        public ReservoirsPersistentValue ReservoirsPersistent
        {
            get { return _reservoirsPersistent; }
            set { SetProperty(ref _reservoirsPersistent, value); }
        }
        /// <summary>
        /// Replen Persistent数据集合
        /// </summary>
        public ObservableCollection<ReplenPersistentValue> ReplensPersistentCollection
        {
            get { return _replensPersistentCollection; }
            set { SetProperty(ref _replensPersistentCollection, value); }
        }
        /// <summary>
        /// 页面功能启用
        /// </summary>
        public bool IsEnabled
        {
            get { return _isEnabled; }
            set { SetProperty(ref _isEnabled, value); }
        }
        /// <summary>
        /// AutoMode页面功能启用
        /// </summary>
        public bool IsAutoEnabled
        {
            get { return _isAutoEnabled; }
            set { SetProperty(ref _isAutoEnabled, value); }
        }
        /// <summary>
        /// IsManualorAuto
        /// </summary>
        public bool IsManualorAuto
        {
            get { return _isManualorAuto; }
            set { SetProperty(ref _isManualorAuto, value); }
        }
        /// <summary>
        /// Reservoir数据
        /// </summary>
        public StandardHotReservoirData ReservoirData
        {
            get { return _reservoirData; }
            set { SetProperty(ref _reservoirData, value); }
        }
        #endregion

        #region recipe
        /// <summary>
        /// Recipe内容
        /// </summary>
        public ResRecipe CurrentRecipe
        {
            get { return _currentRecipe; }
            set { SetProperty(ref _currentRecipe, value); }
        }
        /// <summary>
        /// Selected Recipe Node
        /// </summary>
        public RecipeNode SelectedRecipeNode
        {
            get { return _selectedRecipeNode; }
            set { SetProperty(ref _selectedRecipeNode, value); }
        }
        /// <summary>
        /// Recipe Mode
        /// </summary>
        public string RecipeMode
        {
            get { return _recipeMode; }
            set { SetProperty(ref _recipeMode, value); }
        }
        /// <summary>
        /// Recipe Type
        /// </summary>
        public string RecipeType
        {
            get { return _recipeType; }
            set { SetProperty(ref _recipeType, value); }
        }
        #endregion

        #region DosingSystem               
        /// <summary>
        /// Replen 数据
        /// </summary>
        public ReplenData[] ReplenDatas
        {
            get { return _replenDatas; }
            set { SetProperty(ref _replenDatas, value); }
        }
        /// <summary>
        /// Replen Data集合
        /// </summary>
        public ObservableCollection<ReplenData> ReplenDataCollection
        {
            get { return _replenDataCollection; }
            set { SetProperty(ref _replenDataCollection, value); }
        }
        /// <summary>
        /// Replen Enable列表
        /// </summary>
        public ObservableCollection<bool> ReplenEnable
        {
            get { return _replenEnable; }
            set { SetProperty(ref _replenEnable, value); }
        }
        /// <summary>
        /// Replen 数量
        /// </summary>
        public int ReplenNum
        {
            get { return _replenNum; }
            set { SetProperty(ref _replenNum, value); }
        }
        #endregion
        #endregion

        #region 命令
        public ICommand InitializeCommand { get; set; }

        public ICommand BackCommand { get; set; }
        #endregion

        /// <summary>
        /// 构造函数
        /// </summary>
        public DosingSystemViewModel()
        {
            InitializeCommand = new DelegateCommand<object>(InitializeAction);
            BackCommand = new DelegateCommand<object>(BackAction);
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        public void LoadData(string systemName)
        {
            RecipeType = "rds";
            Module = systemName;

            _rtDataKeys.Clear();
            _rtDataKeys.Add($"{Module}.ReservoirData");
            _rtDataKeys.Add($"{Module}.PersistentValue");
            _rtDataKeys.Add($"{Module}.ReplenPersistentValue");
            _rtDataKeys.Add($"{Module}.ReplenNum");         
            _rtDataKeys.Add($"{Module}.ReplenDatas");
            _rtDataKeys.Add($"{Module}.DosingSystemState");

            
            if (_rtDataKeys.Count != 0)
            {
                _rtDataValueDic = QueryDataClient.Instance.Service.PollData(_rtDataKeys);
                if (_rtDataValueDic != null)
                {
                    ReplenNum = CommonFunction.GetValue<int>(_rtDataValueDic, $"{Module}.ReplenNum");
                    for (int i = 0; i < ReplenNum; i++)
                    {
                        ReplenEnable[i] = true;
                    }
                }
            }

            if (ReplenDataCollection == null) ReplenDataCollection = new ObservableCollection<ReplenData>(new ReplenData[ReplenNum]);
            if (ReplensPersistentCollection == null) ReplensPersistentCollection = new ObservableCollection<ReplenPersistentValue>(new ReplenPersistentValue[ReplenNum]);
            if (_timer == null)
            {
                _timer = new DispatcherTimer();
                _timer.Interval = TimeSpan.FromMilliseconds(200);
                _timer.Tick += Timer_Tick;
            }
            _timer.Start();
        }

        #region 命令方法
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="param"></param>
        private void InitializeAction(object param)
        {
            InvokeClient.Instance.Service.DoOperation($"{Module}.DosingInitialize");
        }
        /// <summary>
        /// 回到Reservoir主页面
        /// </summary>
        /// <param name="param"></param>
        private void BackAction(object param)
        {
            GlobalEvents.OnSwitchFixedChildSubItem(Module, Module);
           
        }
        #endregion
        /// <summary>
        /// 时钟
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer_Tick(object sender, EventArgs e)
        {
            if (_rtDataKeys.Count != 0)
            {
                _rtDataValueDic = QueryDataClient.Instance.Service.PollData(_rtDataKeys);
                if (_rtDataValueDic != null)
                {
                    State = CommonFunction.GetValue<string>(_rtDataValueDic, $"{Module}.DosingSystemState");
                    ReservoirsPersistent = CommonFunction.GetValue<ReservoirsPersistentValue>(_rtDataValueDic, $"{Module}.PersistentValue");
                    _replensPersistent = CommonFunction.GetValue<Dictionary<string, ReplenPersistentValue>>(_rtDataValueDic, $"{Module}.ReplenPersistentValue");
                    _replenDatas = CommonFunction.GetValue<ReplenData[]>(_rtDataValueDic, $"{Module}.ReplenDatas");
                    if(_replenDatas != null)
                    {
                        for(int i = 0; i < _replenNum;i++)
                        {
                            ReplensPersistentCollection[i] = _replensPersistent[_replenDatas[i].ReplenName];
                            if (_replenDatas[i].IsAutoDosingError)
                            {
                                State = "Error";
                            }
                        }
                                                   
                    }
                    
                    ReservoirData = CommonFunction.GetValue<StandardHotReservoirData>(_rtDataValueDic, $"{Module}.ReservoirData");
                    if ("Manual".Equals(ReplensPersistentCollection[0].OperatingMode))
                    {
                        IsEnabled = true;
                        IsAutoEnabled = true;
                        IsManualorAuto = false;
                    }
                    else if ("Auto".Equals(ReplensPersistentCollection[0].OperatingMode))
                    {
                        IsAutoEnabled = true;
                        IsEnabled = false;
                        IsManualorAuto = true;
                    }
                    else
                    {
                        State = "Stopped";
                        IsEnabled = false;
                        IsAutoEnabled = false;
                        IsManualorAuto = false;
                    }
                    if(ReplenDataCollection != null)
                    {
                        ReplenDataCollection.Clear();
                        for (int i = 0; i < ReplenNum; i++)
                        {
                            ReplenDataCollection.Add(_replenDatas[i]);
                        }
                    }
                    
                }
            }
        }
        /// <summary>
        /// 隐藏
        /// </summary>
        public void Hide()
        {
            if (_timer != null)
            {
                _timer.Stop();
            }
        }
        
    }
}