using Aitex.Core.Util;
using Aitex.Core.Utilities;
using Caliburn.Micro;
using Caliburn.Micro.Core;
using ExcelLibrary.BinaryFileFormat;
using FurnaceUI.Models;
using FurnaceUI.Views.Scheduled;
using MECF.Framework.Common.CommonData.EnumData;
using MECF.Framework.Common.DataCenter;
using MECF.Framework.Common.OperationCenter;
using MECF.Framework.Common.Utilities;
using MECF.Framework.UI.Client.CenterViews.Configs.SystemConfig;
using MECF.Framework.UI.Client.CenterViews.Dialogs;
using MECF.Framework.UI.Client.CenterViews.Editors;
using MECF.Framework.UI.Client.CenterViews.Editors.Recipe;
using MECF.Framework.UI.Client.CenterViews.Editors.Sequence;
using OpenSEMI.ClientBase;
using SciChart.Core.Extensions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
namespace FurnaceUI.Views.Editors
{
    public class ScheduledMaintenanceMonitorViewModel : FurnaceUIViewModelBase
    {
        #region 构造函数
        /// 
        /// 构造函数
        /// 
        /// 
        public ScheduledMaintenanceMonitorViewModel(ScheduleMaintenanceDataItem dataItem)
        {
            EditModel = CloneUtil.CloneObject(dataItem) as ScheduleMaintenanceDataItem;
        }
        private bool _jobAutoStartCommandVisibility = false;
        public bool JobAutoStartCommandVisibility
        {
            get => _jobAutoStartCommandVisibility;
            set
            {
                _jobAutoStartCommandVisibility = value;
                NotifyOfPropertyChange("JobAutoStartCommandVisibility");
            }
        }
        private string _selectStepIdName = string.Empty;
        public string SelectStepIdName
        {
            get => _selectStepIdName;
            set
            {
                _selectStepIdName = value;
                NotifyOfPropertyChange("SelectStepIdName");
            }
        }
        private List _maintenanceProcessingList = new List();
        public List MaintenanceProcessingList
        {
            get => _maintenanceProcessingList;
            set
            {
                _maintenanceProcessingList = value;
                NotifyOfPropertyChange("MaintenanceProcessingList");
            }
        }
        #endregion
        #region 属性 EditModel
        /// 
        /// EditModel
        /// 
        public ScheduleMaintenanceDataItem EditModel { get; set; }
        public bool IsPermission { get => this.Permission == 3; }
        #endregion
        public bool IsEnable
        {
            get { return _isEnable; }
            set
            {
                _isEnable = value;
                NotifyOfPropertyChange("IsEnable");
            }
        }
        private bool _isEnable;
        public void TimeSelect(object cmdName, object value)
        {
            var windowManager = IoC.Get();
            RecipeStepTimeViewModel recipeStepTimeViewModel = new RecipeStepTimeViewModel("StepTime");
            bool isCurrentValue = value.ToString() == "CurrentValue";
            bool isStartValue = value.ToString() == "StartValue";
            bool isLimitValue = value.ToString() == "LimitValue";
            if (isCurrentValue)
            {
                recipeStepTimeViewModel.SelectValueTime = DateTimeUtil.SecondToHHmmss(EditModel.CurrentValue.ToString());
            }
            else if (isStartValue)
            {
                recipeStepTimeViewModel.SelectValueTime = DateTimeUtil.SecondToHHmmss(EditModel.StartValue.ToString());
            }
            else if (isLimitValue)
            {
                recipeStepTimeViewModel.SelectValueTime = DateTimeUtil.SecondToHHmmss(EditModel.LimitValue.ToString());
            }
            (windowManager as WindowManager)?.ShowDialogWithTitle(recipeStepTimeViewModel, null, "Standby Time Setting");
            if (recipeStepTimeViewModel.IsSave)
            {
                if (recipeStepTimeViewModel.SelectTime == "Value")
                {
                    var allSecond = DateTimeUtil.GetSecond(recipeStepTimeViewModel.SelectValueTime);
                    if (isCurrentValue)
                    {
                        EditModel.CurrentValue = allSecond;
                    }
                    else if (isStartValue)
                    {
                        EditModel.StartValue = allSecond;
                    }
                    else if (isLimitValue)
                    {
                        EditModel.LimitValue = allSecond;
                    }
                }
            }
        }
        #region 方法 CurrentValueChange
        /// 
        /// CurrentValueChange
        /// 
        public void SetCurrentValue(object obj, MouseButtonEventArgs e)
        {
            e.Handled = true;
            NumberKeyboard fullKeyboard = new NumberKeyboard("", "0");
            if ((bool)fullKeyboard.ShowDialog())
            {
                var data = fullKeyboard.ValueString;
                if (EditModel.Path == "Reactor.StepRunTime")
                {
                    var dataStrs = data.Split('.').ToList();
                    if (dataStrs.Count > 1)
                    {
                        EditModel.CurrentValue = float.Parse(dataStrs.FirstOrDefault()) * 3600 + float.Parse(dataStrs.LastOrDefault()) * 60;
                    }
                    else
                    {
                        EditModel.CurrentValue = float.Parse(dataStrs.FirstOrDefault()) * 3600;
                    }
                }
                else
                {
                    EditModel.CurrentValue = float.Parse(data);
                }
            }
            //if ((bool)fullKeyboard.ShowDialog())
            //{
            //    //InvokeClient.Instance.Service.DoOperation($"{SystemName}.SetConfig", path, fullKeyboard.ValueString);
            //    //currentValue = fullKeyboard.ValueString;
            //    //EditModel.CurrentValue = fullKeyboard.ValueString;
            //}
        }
        public void CurrentValueChange()
        {
            IsEnable = !IsEnable;
        }
        #endregion
        protected override void InvokeAfterUpdateProperty(Dictionary data)
        {
            if (EditModel != null && !string.IsNullOrEmpty(EditModel.MaintenanceProcessing) && EditModel.MaintenanceProcessing == MaintenanceProcessingCommandEnum.JobAutoStart.ToString())
            {
                JobAutoStartCommandVisibility = true;
            }
            else
            {
                EditModel.AssociationProcessRecipeName = "";
                JobAutoStartCommandVisibility = false;
            }
        }
        protected override void OnViewLoaded(object view)
        {
            base.OnViewLoaded(view);
            EnumLoop.ForEach((item) =>
            {
                MaintenanceProcessingList.Add(item.ToString());
            });
            var isReator = EditModel.DataItemType == DataItemEnum.Reactor;
            if (isReator && (EditModel.ReactorsType == ReactorsEnum.StepRunTime || EditModel.ReactorsType == ReactorsEnum.StepRunFreq))
            {
                if (!string.IsNullOrEmpty(EditModel.AdditionInformationDisplay))
                {
                    SelectStepIdName = $":{(string)QueryDataClient.Instance.Service.GetConfig($"PM1.RecipeEditParameter.StepName.{EditModel.AdditionInformationDisplay}")}";
                }
            }
            if (isReator && EditModel.ReactorsType == ReactorsEnum.StepThickness)
            {
                CompareConfigurations();
            }
        }
        public void SelectStepIDMethod()
        {
            var windowManager = IoC.Get();
            RecipeStepNameViewModel recipeStepNameViewModel = new RecipeStepNameViewModel() { CheckNumber = true, SelectedStepName = EditModel.AdditionInformationDisplay };
            if ((bool)(windowManager as WindowManager)?.ShowDialogWithTitle(recipeStepNameViewModel, null, "Select Step ID"))
            {
                var strs = recipeStepNameViewModel.SelectedStepName.Split(':');
                if (IsExist(strs.FirstOrDefault()))
                {
                    DialogBox.ShowWarning($"Step: {strs.FirstOrDefault()} repeated selection!");
                    return;
                }
                EditModel.AdditionInformationDisplay = strs.FirstOrDefault();
                if (strs.Length > 1)
                {
                    SelectStepIdName = $":{strs.LastOrDefault()}";
                }
            }
        }
        private bool IsExist(string stepId)
        {
            string sql = $"SELECT addition_information_display FROM \"schedule_maintenance\"  WHERE  path='{EditModel.DataItemType}.{EditModel.ReactorsType}' AND addition_information_display='{stepId}'";
            DataTable dt = QueryDataClient.Instance.Service.QueryData(sql);
            if (dt != null && dt.Rows != null)
            {
                return dt.Rows.Count >= 1;
            }
            return false;
        }
        private void CompareConfigurations()
        {
            var groupValue = (string)QueryDataClient.Instance.Service.GetConfig($"PM1.RecipeEditParameter.StepGroup.{EditModel.AdditionInformationDisplay}");
            if (!string.IsNullOrEmpty(EditModel.AdditionInformationDisplaySupplement))
            {
                if (string.IsNullOrEmpty(groupValue))
                {
                    DialogBox.ShowWarning($"The selected {EditModel.AdditionInformationDisplay} does not match the  Config {EditModel.AdditionInformationDisplay}. Please confirm!");
                }
                else
                {
                    var oldDatas = EditModel.AdditionInformationDisplaySupplement.Split(',').ToList();
                    var newDatas = groupValue.Split(',').ToList();
                    // 判断 oldDatas 中有但 newDatas 中没有的元素
                    var differenceOldToNew = oldDatas.Except(newDatas).ToList();
                    // 判断 newDatas 中有但 oldDatas 中没有的元素
                    var differenceNewToOld = newDatas.Except(oldDatas).ToList();
                    // 检查是否存在差集
                    bool hasDifference = differenceOldToNew.Any() || differenceNewToOld.Any();
                    if (hasDifference)
                    {
                        DialogBox.ShowWarning($"The selected {EditModel.AdditionInformationDisplay} does not match the  Config {EditModel.AdditionInformationDisplay}. Please confirm!");
                    }
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(groupValue))
                {
                    DialogBox.ShowWarning($"The selected {EditModel.AdditionInformationDisplay} does not match the  Config {EditModel.AdditionInformationDisplay}. Please confirm!");
                }
            }
        }
        public void SelectStepGroupMethod()
        {
            var windowManager = IoC.Get();
            StepGroupSelectViewModel recipeStepNameViewModel = new StepGroupSelectViewModel() { SelectedGroupName = EditModel.AdditionInformationDisplay };
            if ((bool)(windowManager as WindowManager)?.ShowDialogWithTitle(recipeStepNameViewModel, null, "Select Step Group"))
            {
                EditModel.AdditionInformationDisplay = recipeStepNameViewModel.SelectedGroupName;
                var gropuDataStr = (string)QueryDataClient.Instance.Service.GetConfig($"PM1.RecipeEditParameter.StepGroup.{recipeStepNameViewModel.SelectedGroupName}");
                if (!string.IsNullOrEmpty(gropuDataStr))
                {
                    var datas = QueryDataClient.Instance.Service.PollConfig(gropuDataStr.Split(',').ToList().Select(a => $"PM1.RecipeEditParameter.StepName.{a}"));
                    var recipeNames = datas.Select(a => $"{a.Key.Split('.').LastOrDefault()}");
                    EditModel.AdditionInformationDisplaySupplement = string.Join(",", recipeNames);
                }
                else
                {
                    EditModel.AdditionInformationDisplaySupplement = "";
                }
            }
        }
        public void SelectProcessRecipe(string value)
        {
            RecipeSelectDialogViewModel dialog = new RecipeSelectDialogViewModel();
            dialog.DisplayName = "Select Recipe";
            var recipeProvider = new RecipeProvider();
            var processType = QueryDataClient.Instance.Service.GetConfig($"System.Recipe.SupportedProcessType");
            if (processType == null)
            {
                processType = "Process";
            }
            var ProcessTypeFileList = new ObservableCollection();
            string[] recipeProcessType = ((string)processType).Split(',');
            var type = new ProcessTypeFileItem();
            type.ProcessType = recipeProcessType[0];
            var prefix = $"Furnace\\{recipeProcessType[0]}";
            var recipes = recipeProvider.GetXmlRecipeList(prefix);
            type.FileListByProcessType = RecipeSequenceTreeBuilder.BuildFileNode(prefix, "", false, recipes)[0].Files;
            ProcessTypeFileList.Add(type);
            dialog.ProcessTypeFileList = ProcessTypeFileList;
            WindowManager wm = new WindowManager();
            bool? bret = wm.ShowDialog(dialog);
            if ((bool)bret)
            {
                if (value == "AssociationProcessRecipeName")
                {
                    EditModel.AssociationProcessRecipeName = dialog.DialogResult;
                }
                if (value == "AdditionInformationDisplay")
                {
                    EditModel.AdditionInformationDisplay = dialog.DialogResult;
                }
            }
        }
        #region 方法 ClearCurrentValue
        /// 
        /// ClearCurrentValue
        /// 
        public void ClearCurrentValue()
        {
            if (EditModel != null)
            {
                EditModel.CurrentValue = 0;
            }
        }
        #endregion
        #region 方法 SetSave
        public void SetSave()
        {
            var judgeConditionA = EditModel.MaintenanceProcessing == MaintenanceProcessingCommandEnum.JobAutoStart.ToString();
            var judgeConditionB = string.IsNullOrEmpty(EditModel.AssociationProcessRecipeName);
            if (judgeConditionA && judgeConditionB)
            {
                DialogBox.ShowWarning($"Recipe cannot be empty");
                return;
            }
            var judgeConditionC = EditModel.MaintenanceProcessing == MaintenanceProcessingCommandEnum.AlarmReport.ToString();
            var judgeConditionD = EditModel.Path == DataItemEnum.CarrierWafer.ToString() || EditModel.Path == DataItemEnum.Reactor.ToString();
            var judgeConditionE = string.IsNullOrEmpty(EditModel.AdditionInformationDisplay);
            if ((judgeConditionC || judgeConditionA) && judgeConditionE && judgeConditionD)
            {
                DialogBox.ShowWarning($"AdditionInformation cannot be empty");
                return;
            }
            this.TryClose(true);
        }
        #endregion
        #region 方法 SetCancel
        public void SetCancel()
        {
            TryClose();
        }
        #endregion
    }
}