using Aitex.Core.UI.MVVM;
using CyberX8_Core;
using CyberX8_MainPages.Model;
using CyberX8_Themes.CustomControls;
using ExcelLibrary.BinaryFileFormat;
using MECF.Framework.Common.CommonData.Metal;
using MECF.Framework.Common.CommonData.Reservoir;
using MECF.Framework.Common.DataCenter;
using MECF.Framework.Common.Device.Safety;
using MECF.Framework.Common.OperationCenter;
using MECF.Framework.Common.Persistent.Reservoirs;
using MECF.Framework.Common.RecipeCenter;
using MECF.Framework.Common.Utilities;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Threading;

namespace CyberX8_MainPages.ViewModels
{
    public class ReservoirsViewModel : BindableBase
    {
        #region 常量
        private const string RESERVOIRS_DATA = "ReservoirsData";
        private const string RESERVOIRS = "reservoirs";
        private const string PERSISTENT_VALUE = "PersistentValue";
        #endregion

        #region 内部变量
        private string _module;
        private string _recipeContent;
        private string _state;
        private List<string> _rtDataKeys = new List<string>();
        DispatcherTimer _timer;
        private Dictionary<string, object> _rtDataValueDic = new Dictionary<string, object>();
        private ObservableCollection<RecipeNode> _recipeNodes;
        private string _currentRecipeFileName;
        private string _recipeType;
        private ResRecipe _currentRecipe;
        private SafetyData _safetyData;
        private double _aNFlow;

        private bool _isCAHighLevel;
        private bool _isCALowLevel;
        private bool _isANHighLevel;
        private bool _isANLowLevel;
        private bool _isCASafetyHighLevel;
        private bool _filterPurgeEnable;
        private double _avgANLevel;
        private double _avgCALevel;
        /// <summary>
        /// Persistent
        /// </summary>
        private ReservoirsPersistentValue _reservoirsPersistent;
        /// <summary>
        /// Reservoir数据
        /// </summary>
        private CompactMembranReservoirData _reservoirData;
        /// <summary>
        /// CellModuleName集合
        /// </summary>
        private ObservableCollection<string> _cellModuleNameCollection = new ObservableCollection<string>();
        /// <summary>
        /// Cell A面Flow集合
        /// </summary>
        private ObservableCollection<double> _cellModuleNameSideAFlowCollection = new ObservableCollection<double>();
        /// <summary>
        /// Cell B面Flow集合
        /// </summary>
        private ObservableCollection<double> _cellModuleNameSideBFlowCollection = new ObservableCollection<double>();
        /// <summary>
        /// MetalData
        /// </summary>
        private ObservableCollection<CompactMembranMetalDeviceData> _metalDatas = new ObservableCollection<CompactMembranMetalDeviceData>();
        /// <summary>
        /// 页面功能启用
        /// </summary>
        private bool _isEnabled;
        /// <summary>
        /// 是否error
        /// </summary>
        private bool _isError;
        /// <summary>
        /// AutoMode页面功能启用
        /// </summary>
        private bool _isAutoEnabled;
        /// <summary>
        /// Meatl UI数据
        /// </summary>
        private ObservableCollection<ReservoirsUIData> _reservoirsUIDatas = new ObservableCollection<ReservoirsUIData>();
        #endregion
        #region 属性
        public double AvgANLevel
        {
            get { return _avgANLevel; }
            set { SetProperty(ref _avgANLevel, value); }
        }
        public double AvgCALevel
        {
            get { return _avgCALevel; }
            set { SetProperty(ref _avgCALevel, value); }
        }

        public bool IsCAHighLevel
        {
            get { return _isCAHighLevel; }
            set { SetProperty(ref _isCAHighLevel, value); }
        }
        public bool IsCALowLevel
        {
            get { return _isCALowLevel; }
            set { SetProperty(ref _isCALowLevel, value); }
        }
        public bool IsANHighLevel
        {
            get { return _isANHighLevel; }
            set { SetProperty(ref _isANHighLevel, value); }
        }
        public bool IsANLowLevel
        {
            get { return _isANLowLevel; }
            set { SetProperty(ref _isANLowLevel, value); }
        }
        public string CurrentRecipeFileName
        {
            get { return _currentRecipeFileName; }
            set { SetProperty(ref _currentRecipeFileName, value); }
        }
        public ObservableCollection<RecipeNode> RecipeNodes
        {
            get { return _recipeNodes; }
            set { SetProperty(ref _recipeNodes, value); }
        }
        public string Module { get { return _module; } set { SetProperty(ref _module, value); } }
        public string ReservoirRecipeContent
        {
            get { return _recipeContent; }
            set { SetProperty(ref _recipeContent, value); }
        }
        public string State
        {
            get { return _state; }
            set { SetProperty(ref _state, value); }
        }

        public ResRecipe CurrentRecipe
        {
            get { return _currentRecipe; }
            set { SetProperty(ref _currentRecipe, value); }
        }
        /// <summary>
        /// Safety数据
        /// </summary>
        public SafetyData CommonSafetyData
        {
            get { return _safetyData; }
            set { SetProperty(ref _safetyData, value); }
        }
        public string RecipeType
        {
            get { return _recipeType; }
            set { SetProperty(ref _recipeType, value); }
        }

        /// <summary>
        /// Threshold
        /// </summary>
        public ReservoirsPersistentValue ReservoirsPersistent
        {
            get { return _reservoirsPersistent; }
            set { SetProperty(ref _reservoirsPersistent, value); }
        }
        /// <summary>
        /// CellModuleName集合
        /// </summary>
        public ObservableCollection<string> CellModuleNameCollection
        {
            get { return _cellModuleNameCollection; }
            set { SetProperty(ref _cellModuleNameCollection, value); }
        }
        /// <summary>
        /// 模块A面Flow集合
        /// </summary>
        public ObservableCollection<double> CellModuleNameSideAFlowCollection
        {
            get { return _cellModuleNameSideAFlowCollection; }
            set { SetProperty(ref _cellModuleNameSideAFlowCollection, value); }
        }
        /// <summary>
        /// 模块B面Flow集合
        /// </summary>
        public ObservableCollection<double> CellModuleNameSideBFlowCollection
        {
            get { return _cellModuleNameSideBFlowCollection; }
            set { SetProperty(ref _cellModuleNameSideBFlowCollection, value); }
        }
        /// <summary>
        /// Reservoir 数据
        /// </summary>
        public CompactMembranReservoirData ReservoirData
        {
            get { return _reservoirData; }
            set { SetProperty(ref _reservoirData, value); }
        }
        public bool IsCASafetyHighLevel
        {
            get { return _isCASafetyHighLevel; }
            set { SetProperty(ref _isCASafetyHighLevel, value); }
        }
        /// <summary>
        /// MetalData
        /// </summary>
        public ObservableCollection<CompactMembranMetalDeviceData> MetalDatas
        {
            get { return _metalDatas; }
            set { SetProperty(ref _metalDatas, value); }
        }
        public double ANFlow
        {
            get { return _aNFlow; }
            set { SetProperty(ref _aNFlow, value); }
        }
        /// <summary>
        /// 页面功能启用
        /// </summary>
        public bool IsEnabled
        {
            get { return _isEnabled; }
            set { SetProperty(ref _isEnabled, value); }
        }
        /// <summary>
        /// 是否Error
        /// </summary>
        public bool IsError
        {
            get { return _isError; }
            set { SetProperty(ref _isError, value); }
        }
        /// <summary>
        /// AutoMode页面功能启用
        /// </summary>
        public bool IsAutoEnabled
        {
            get { return _isAutoEnabled; }
            set { SetProperty(ref _isAutoEnabled, value); }
        }
        /// <summary>
        /// FilterPurgeEnable
        /// </summary>
        public bool FilterPurgeEnable
        {
            get { return _filterPurgeEnable; }
            set { SetProperty(ref _filterPurgeEnable, value); }
        }
        /// <summary>
        /// metal ui数据
        /// </summary>
        public ObservableCollection<ReservoirsUIData> ReservoirsUIDatas
        {
            get { return _reservoirsUIDatas; }
            set { SetProperty(ref _reservoirsUIDatas, value); }
        }
        #endregion

        #region 命令
        public ICommand InitializeCommand { get; set; }
        public ICommand GotoPMCounterCommand { get; set; }
        public ICommand JumpAnolyteCommand { get; set; }
        public ICommand JumpCatholyteCommand { get; set; }
        public ICommand FilterPurgeEnableCommand { get; set; }
        #endregion

        public ReservoirsViewModel()
        {
            InitializeCommand = new DelegateCommand<object>(InitializeAction);
            GotoPMCounterCommand = new DelegateCommand<object>(GotoPMCounterAction);
            JumpAnolyteCommand = new DelegateCommand<object>(JumpAnolyteAction);
            JumpCatholyteCommand = new DelegateCommand<object>(JumpCatholyteAction);
            FilterPurgeEnableCommand = new DelegateCommand<object>(FilterPurgeEnableAction);
        }

        public void LoadData(string systemName)
        {
            RecipeType = "res";
            Module = systemName;
            _rtDataKeys.Clear();
            _rtDataKeys.Add($"{Module}.Metals");
            MetalDatas.Clear();
            ReservoirsUIDatas.Clear();
            CellModuleNameSideAFlowCollection.Clear();
            CellModuleNameSideBFlowCollection.Clear();
            Dictionary<string, object> tmpMetals = QueryDataClient.Instance.Service.PollData(_rtDataKeys);
            if (tmpMetals != null)
            {
                List<string> strMetals = CommonFunction.GetValue<List<string>>(tmpMetals, $"{Module}.Metals");
                int cellsCount = strMetals.Count;
                if (strMetals != null)
                {
                    CellModuleNameCollection.Clear();
                    for (int i = 0; i < cellsCount; i++)
                    {
                        CellModuleNameCollection.Add(strMetals[i]);
                        MetalDatas.Add(null);
                        ReservoirsUIData reservoirsUIData = new ReservoirsUIData();
                        reservoirsUIData.Name = strMetals[i];
                        ReservoirsUIDatas.Add(reservoirsUIData);
                        CellModuleNameSideAFlowCollection.Add(0);
                        CellModuleNameSideBFlowCollection.Add(0);

                    }
                }
            }
            _rtDataKeys.Clear();
            if (_timer == null)
            {
                _timer = new DispatcherTimer();
                _timer.Interval = TimeSpan.FromMilliseconds(200);
                _timer.Tick += Timer_Tick;
            }
            _rtDataKeys.Clear();
            for (int i = 0; i < CellModuleNameCollection.Count; i++)
            {
                _rtDataKeys.Add($"{CellModuleNameCollection[i]}.MetalData");
                _rtDataKeys.Add($"{CellModuleNameCollection[i]}.SideAFlow");
                _rtDataKeys.Add($"{CellModuleNameCollection[i]}.SideAFlowStatus");
                _rtDataKeys.Add($"{CellModuleNameCollection[i]}.SideBFlow");
                _rtDataKeys.Add($"{CellModuleNameCollection[i]}.SideBFlowStatus");
            }
            _rtDataKeys.Add($"{Module}.{PERSISTENT_VALUE}");
            _rtDataKeys.Add($"{Module}.ReservoirData");
            _rtDataKeys.Add($"{Module}.CurrentRecipe");
            _rtDataKeys.Add($"{Module}.IsCAHighLevel");
            _rtDataKeys.Add($"{Module}.IsCALowLevel");
            _rtDataKeys.Add($"{Module}.IsANHighLevel");
            _rtDataKeys.Add($"{Module}.IsANLowLevel");
            _rtDataKeys.Add($"Safety.SafetyData");
            _rtDataKeys.Add($"{Module}.FsmState");
            _rtDataKeys.Add($"System.Facilities.FilterPurgeEnable");
            _rtDataKeys.Add($"{Module}.ReservoirAverageANLevel");
            _rtDataKeys.Add($"{Module}.ReservoirAverageCALevel");
            _timer.Start();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            ANFlow = 0.0;
            if (_rtDataKeys.Count != 0)
            {
                _rtDataValueDic = QueryDataClient.Instance.Service.PollData(_rtDataKeys);
                if (_rtDataValueDic != null)
                {
                    State = CommonFunction.GetValue<string>(_rtDataValueDic, $"{Module}.FsmState");
                    IsError = "Error".Equals(State) ? true : false;
                    ReservoirData = CommonFunction.GetValue<CompactMembranReservoirData>(_rtDataValueDic, $"{Module}.ReservoirData");
                    ReservoirsPersistent = CommonFunction.GetValue<ReservoirsPersistentValue>(_rtDataValueDic, $"{Module}.{PERSISTENT_VALUE}");
                    CurrentRecipe = CommonFunction.GetValue<ResRecipe>(_rtDataValueDic, $"{Module}.CurrentRecipe");
                    CommonSafetyData = CommonFunction.GetValue<SafetyData>(_rtDataValueDic, $"Safety.SafetyData");
                    FilterPurgeEnable = CommonFunction.GetValue<bool>(_rtDataValueDic, $"System.Facilities.FilterPurgeEnable");
                    IsCASafetyHighLevel = CommonSafetyData.ReservoirHighLevel;
                    //计算总的ANFlow
                    for (int i = 0; i < CellModuleNameCollection.Count; i++)
                    {
                        MetalDatas[i] = CommonFunction.GetValue<CompactMembranMetalDeviceData>(_rtDataValueDic, $"{CellModuleNameCollection[i]}.MetalData");
                        CellModuleNameSideAFlowCollection[i] = CommonFunction.GetValue<double>(_rtDataValueDic, $"{CellModuleNameCollection[i]}.SideAFlow");
                        CellModuleNameSideBFlowCollection[i] = CommonFunction.GetValue<double>(_rtDataValueDic, $"{CellModuleNameCollection[i]}.SideBFlow");
                        ANFlow += CellModuleNameSideAFlowCollection[i] + CellModuleNameSideBFlowCollection[i];

                    }
                    IsANHighLevel = CommonFunction.GetValue<bool>(_rtDataValueDic, $"{Module}.IsANHighLevel");
                    IsANLowLevel = CommonFunction.GetValue<bool>(_rtDataValueDic, $"{Module}.IsANLowLevel");
                    IsCAHighLevel = CommonFunction.GetValue<bool>(_rtDataValueDic, $"{Module}.IsCAHighLevel");
                    IsCALowLevel = CommonFunction.GetValue<bool>(_rtDataValueDic, $"{Module}.IsCALowLevel");
                    if ("Manual".Equals(ReservoirsPersistent.OperatingMode))
                    {
                        IsEnabled = true;
                        IsAutoEnabled = true;
                    }
                    else if ("Auto".Equals(ReservoirsPersistent.OperatingMode))
                    {
                        IsAutoEnabled = true;
                        IsEnabled = false;
                    }
                    else
                    {
                        State = "Stopped";
                        IsEnabled = false;
                        IsAutoEnabled = false;
                    }

                    AvgANLevel = CommonFunction.GetValue<double>(_rtDataValueDic, $"{Module}.ReservoirAverageANLevel");
                    AvgCALevel = CommonFunction.GetValue<double>(_rtDataValueDic, $"{Module}.ReservoirAverageCALevel");
                }

            }
        }

        #region 命令方法
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="param"></param>
        private void InitializeAction(object param)
        {
            InvokeClient.Instance.Service.DoOperation($"{Module}.InitializeAll");
        }
        /// <summary>
        /// 进入PMCounter页面
        /// </summary>
        /// <param name="param"></param>
        private void GotoPMCounterAction(object param)
        {
            GlobalEvents.OnSwitchFixedChildSubItem(Module, $"PMCounter{Module.Substring(9, 1)}");
        }
        private void JumpAnolyteAction(object param)
        {
            GlobalEvents.OnSwitchFixedChildSubItem(Module, $"Anolyte{Module.Substring(9, 1)}");

        }
        private void JumpCatholyteAction(object param)
        {

            GlobalEvents.OnSwitchFixedChildSubItem(Module, $"Catholyte{Module.Substring(9, 1)}");
        }
        private void FilterPurgeEnableAction(object param)
        {
            CommonValveControl commonValveControl = (CommonValveControl)param;
            if (commonValveControl.IsCanEdit == true)
            {
          
                if (!commonValveControl.Status)
                {
                    commonValveControl.Status = !commonValveControl.Status;
                    InvokeClient.Instance.Service.DoOperation($"System.Facilities.FilterPurgeEnable");
                }
                else
                {
                    commonValveControl.Status = !commonValveControl.Status;
                    InvokeClient.Instance.Service.DoOperation($"System.Facilities.FilterPurgeDisable");
                }

            }

        }
        #endregion
    }
}