using Aitex.Core.RT.Log;
using Aitex.Core.Util;
using Caliburn.Micro;
using DocumentFormat.OpenXml.Bibliography;
using DocumentFormat.OpenXml.EMMA;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
using MECF.Framework.Common.Aitex.Core.RT.EMS;
using MECF.Framework.Common.DataCenter;
using MECF.Framework.Common.OperationCenter;
using MECF.Framework.RT.EquipmentLibrary.Core.Extensions;
using MECF.Framework.UI.Client.ClientBase;
using Microsoft.VisualBasic;
using OpenSEMI.ClientBase;
using SciChart.Charting.Common.Extensions;
using SciChart.Charting.Visuals.TradeChart.MultiPane;
using SciChart.Core.Extensions;
using Sicentury.Core.Collections;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace MECF.Framework.UI.Client.CenterViews.Maintain.ViewModels
{
    public class MaintainConfigViewModel : UiViewModelBase, ISupportMultipleSystem
    {
        #region Variables

        private readonly IWindowManager _windowmanager;

        private DateTime _handShake = DateTime.Now;

        private Dictionary<string, ObservableCollection<MaintainerInfo>> _maintainerInfoDic = new();

        private ObservableCollection<MaintainerItemConfigEnableInfo> _obMaintainerItemConfigEnableInfos = new();

        private Dictionary<string, List<MaintainerItemConfigEnableInfo>> _maintaineritemconfigenableinfodic = new();
        
        private MaintainerInfo _selectedValue = new();

        private KeyValuePair<string, ObservableCollection<MaintainerInfo>> _selectedKeyValue = new();

        private int _currentPage =1;

        private int _totalPage;

        private List<MaintainerItemConfigInfo> _maintainerItemConfigInfoList = new();

        private List<MaintainerItemConfigEnableInfo> _maintainerItemConfigEnableInfos = new();

        private readonly int MAXROW = 30;

        #endregion

        #region Properties 

        public List<string> GroupNameList => _maintainerInfoDic.Keys.ToList();

        public Dictionary<string, ObservableCollection<MaintainerInfo>> MaintainerInfoDic
        {
            get { return _maintainerInfoDic; }
            set
            {
                _maintainerInfoDic = value;
                NotifyOfPropertyChange(nameof(MaintainerInfoDic));
            }
        }

        public ObservableCollection<MaintainerItemConfigEnableInfo> ObMaintainerItemConfigEnableInfos
        {
            get { return _obMaintainerItemConfigEnableInfos; }
            set
            {
                _obMaintainerItemConfigEnableInfos = value;
                NotifyOfPropertyChange(nameof(ObMaintainerItemConfigEnableInfos));
            }
        }

        public MaintainerInfo SelectedValue
        {
            get { return _selectedValue; }
            set { _selectedValue = value; NotifyOfPropertyChange(nameof(SelectedValue)); }
        }

        public KeyValuePair<string, ObservableCollection<MaintainerInfo>> SelectedKeyValue
        {
            get { return _selectedKeyValue; }
            set { _selectedKeyValue = value; NotifyOfPropertyChange(nameof(SelectedKeyValue)); }
        }

        public int CurrentPage
        {
            get { return _currentPage; }
            set { _currentPage = value; NotifyOfPropertyChange(nameof(CurrentPage)); }
        }

        public int TotalPage
        {
            get { return _totalPage; }
            set { _totalPage = value; NotifyOfPropertyChange(nameof(TotalPage)); }
        }

        public List<MaintainerItemConfigEnableInfo> MaintainerItemConfigEnableInfos => _maintainerItemConfigEnableInfos;

        #endregion

        #region Constructors
        public MaintainConfigViewModel()
        {
            _windowmanager = new WindowManager();
        }

        #endregion

        #region Functions

        protected override void OnInitialize()
        {
            //初始化与RT Maintain参数同步， 在RT Maintain初始化完成后 初始化
            List<MaintainerInfo> maintainerlist = (List<MaintainerInfo>)QueryDataClient.Instance.Service.GetData("MaintainManager.MaintainerInfos");
            _maintainerItemConfigInfoList = ((List<MaintainerItemConfigInfo>)QueryDataClient.Instance.Service.GetData("MaintainManager.MaintainerConfigItems"));

            //生成dic
            foreach (var m in maintainerlist)
            { 
                if (!_maintainerInfoDic.ContainsKey(m.Name))
                {
                    _maintainerInfoDic.Add(m.Name, new());
                }
                _maintainerInfoDic[m.Name].Add(m);
            }

            OrderMaintainer();

            //configenableinfodic
            foreach (var item in _maintainerItemConfigInfoList)
            {
                MaintainerItemConfigEnableInfo ei = new();
                ei.Config = item;
                //配置enable
                foreach (var i in maintainerlist)
                {

                    var mi = i.MaintainerItemInfos.Find(j => j.UID == item.UID);
                    ei.ItemEnableBook.Add(new ItemEnablePage()
                    {
                        Type = i.Type,
                        Name = i.Name,
                        Module = i.Module,
                        Value = mi != null
                    });
                }
                _maintainerItemConfigEnableInfos.Add(ei);
            }

            //初始化maintainer选择器
            foreach (var item in _maintainerInfoDic.Values)
            {
                foreach (var item2 in item)
                {
                    item2.IsSelected = false;
                }
                if (item.Count>0)
                {
                    item[0].IsSelected = true;
                }
            }

            if (MaintainerInfoDic.Count > 0)
            {
                SelectedKeyValue = MaintainerInfoDic.First();
                if (SelectedKeyValue.Value.Count > 0)
                {
                    SelectedValue = SelectedKeyValue.Value.First();
                    //初始化enablepage选择器
                    foreach (var item in _maintainerItemConfigEnableInfos)
                    {
                        item.SelectPage(SelectedValue.Type,SelectedValue.Name,SelectedValue.Module);
                    }
                }
            }

            OrderMaintainItem();

            ReShapeEnableConfigTable();

        }

        private void OrderMaintainer()
        {
            _maintainerInfoDic.ForEachDo(i => {
                var temp = i.Value.OrderBy(i => i.Index).ToList();
                i.Value.Clear();
                foreach (var item in temp)
                {
                    i.Value.Add(item);
                }
            });
        }

        private void OrderMaintainItem()
        {
            _maintainerItemConfigInfoList.Sort((a, b) => a.Index.CompareTo(b.Index));
            _maintainerInfoDic.ForEachDo(i => {
                foreach (var item in i.Value)
                {
                    var temp = item.MaintainerItemInfos;
                    item.MaintainerItemInfos.Clear();
                    foreach (var sortitem in temp.OrderBy(i => i.Config.Index))
                    {
                        item.MaintainerItemInfos.Add(sortitem);
                    }
                }
            });

            _maintainerItemConfigEnableInfos.Sort((a, b) => a.Config.Index.CompareTo(b.Config.Index));
        }

        private void ReShapeEnableConfigTable()
        {
            if (string.IsNullOrEmpty(SelectedValue.Name))
            {
                return;
            }
            int location = (CurrentPage -1) * MAXROW;

            TotalPage = (_maintainerItemConfigEnableInfos.Count / MAXROW) + 1;

            ObMaintainerItemConfigEnableInfos.Clear();
            int c = 0;
            foreach (var item in _maintainerItemConfigEnableInfos)
            {
                if (c >= location && c < location + MAXROW)
                {
                    ObMaintainerItemConfigEnableInfos.Add(item);
                }
                c++;
            }
        }

        protected override void OnActivate()
        {

        }

        protected override void OnDeactivate(bool close)
        {
            EnableTimer(false);
        }

        protected override bool OnTimer()
        {
            base.OnTimer();

            return true;
        }

        public void SelectionChanged()
        {
            if (SelectedKeyValue.Value.Count == 0)
            {
                SelectedValue = null;

                foreach (var item2 in _maintainerItemConfigEnableInfos)
                {
                    item2.SelectedPage = null;
                }

                return;
            }
            SelectedValue = SelectedKeyValue.Value.ToList().Find(x => x.IsSelected);
            if (SelectedValue == null)
            {
                SelectedValue = SelectedKeyValue.Value.First();
            }

            foreach (var item2 in _maintainerItemConfigEnableInfos)
            {
                item2.SelectPage(SelectedValue.Type, SelectedValue.Name, SelectedValue.Module);
            }
                     
        }

        public void Previous()
        {
            if (CurrentPage == 1)
            {
                return;
            }
            CurrentPage--;
            ReShapeEnableConfigTable();
        }

        public void Next()
        {
            if (CurrentPage == TotalPage)
            {
                return;
            }
            CurrentPage++;
            ReShapeEnableConfigTable();
        }

        #region Item

        public void ItemCheckedChanged(ItemEnablePage page,string uid)
        {    
            if (page == null)
            {
                return;
            }
            page.Value = !page.Value;

            InvokeClient.Instance.Service.DoOperation("MaintainManager.SetMaintainItemEnable", page.Type, page.Name, page.Module, uid, page.Value);
        }

        public void ItemSetting(MaintainerItemConfigEnableInfo iteminfo)
        {
            if (iteminfo == null)
            {
                return;
            }
            var vm = new MaintainItemSettingViewModel(iteminfo, _maintainerItemConfigInfoList);
            _windowmanager.ShowDialog(vm);
            if (vm.DialogResult == ResultYesNo.YES)
            {
                MaintainerItemConfigInfo item = _maintainerItemConfigInfoList.Find(i => i.UID == vm.ItemInfo.UID);
                if (item != null)
                {
                    #region 更新本界面信息

                    item.ParentName = vm.ItemInfo.ParentName;
                    item.Name = vm.ItemInfo.Name;
                    item.Index = vm.ItemInfo.Index;
                    item.Description = vm.ItemInfo.Description;
                    item.DefaultRecord = vm.ItemInfo.DefaultRecord;
                    item.FilePath = vm.ItemInfo.FilePath;
                    item.InvokePropertyChanged();

                    #endregion

                    #region 通知RT变更

                    InvokeClient.Instance.Service.DoOperation("MaintainManager.SetMaintainItemParas",
                        vm.ItemInfo.ParentName,
                        vm.ItemInfo.Name,
                        vm.ItemInfo.UID,
                        vm.ItemInfo.Index,
                        vm.ItemInfo.Description,
                        vm.ItemInfo.DefaultRecord,
                        vm.ItemInfo.FilePath);

                    #endregion
                }
            }

        }

        public void MaintainItemDelete(MaintainerItemConfigEnableInfo info)
        {
            if (info == null)
            {
                return;
            }
            if (DialogBox.Confirm("Operation cannot be undone.Do you want to Remove the Item?"))
            {
                #region 更新本界面信息

                //删除config里的项
                var config = _maintainerItemConfigInfoList.Find(i => i.UID == info.Config.UID);
                if (config != null)
                {
                    _maintainerItemConfigInfoList.Remove(config);
                    _maintainerItemConfigInfoList.OrderBy(i => i.Index);
                }

                //删除enableconfig的项
                var econfig = _maintainerItemConfigEnableInfos.Find(i => i.Config.UID == info.Config.UID);
                if (econfig != null)
                {
                    _maintainerItemConfigEnableInfos.Remove(econfig);
                }

                //删除maintainer里的项
                foreach (var list in _maintainerInfoDic.Values)
                {
                    foreach (var item in list)
                    {
                        var mitem = item.MaintainerItemInfos.Find(i => i.UID == info.Config.UID);
                        if (mitem != null)
                        {
                            item.MaintainerItemInfos.Remove(mitem);
                            item.MaintainerItemInfos.OrderBy(i => i.Config.Index);
                        }
                    }
                }

                ReShapeEnableConfigTable();
                #endregion

                #region 通知RT变更

                InvokeClient.Instance.Service.DoOperation("MaintainManager.DeleteMaintainItem", info.Config.UID);

                #endregion
                
            }
        }

        public void MaintainItemUp(MaintainerItemConfigEnableInfo info)
        {
            var index = _maintainerItemConfigInfoList.FindIndex(i => i.UID == info.Config.UID);
            if (index != -1 && index != 0)
            {
                #region 更新本界面信息
                string u1 = _maintainerItemConfigInfoList[index].UID, u2 = _maintainerItemConfigInfoList[index - 1].UID;
                var temp = _maintainerItemConfigInfoList[index].Index;
                _maintainerItemConfigInfoList[index].Index = _maintainerItemConfigInfoList[index - 1].Index;
                _maintainerItemConfigInfoList[index - 1].Index = temp;

                OrderMaintainItem();
                ReShapeEnableConfigTable();

                #endregion

                #region 通知RT变更

                InvokeClient.Instance.Service.DoOperation("MaintainManager.ExchangeMaintainItemIndex", u1, u2);

                #endregion
            }


        }

        public void MaintainItemDown(MaintainerItemConfigEnableInfo info)
        {
            var index = _maintainerItemConfigInfoList.FindIndex(i => i.UID == info.Config.UID);
            if (index != -1 && index != _maintainerItemConfigInfoList.Count - 1)
            {
                #region 更新本界面信息

                string u1 = _maintainerItemConfigInfoList[index].UID, u2 = _maintainerItemConfigInfoList[index + 1].UID;
                var temp = _maintainerItemConfigInfoList[index].Index;
                _maintainerItemConfigInfoList[index].Index = _maintainerItemConfigInfoList[index + 1].Index;
                _maintainerItemConfigInfoList[index + 1].Index = temp;

                OrderMaintainItem();
                ReShapeEnableConfigTable();

                #endregion

                #region 通知RT变更

                InvokeClient.Instance.Service.DoOperation("MaintainManager.ExchangeMaintainItemIndex", u1, u2);

                #endregion
            }
        }

        public void AddNewItem()
        {
            var vm = new MaintainItemSettingViewModel(_maintainerItemConfigInfoList);
            _windowmanager.ShowDialog(vm);
            if (vm.DialogResult == ResultYesNo.YES)
            {
                #region 更新本界面信息

                _maintainerItemConfigInfoList.Add(vm.ItemInfo);

                var ceinfo = new MaintainerItemConfigEnableInfo();
                ceinfo.Config = vm.ItemInfo;
                foreach (var item in _maintainerInfoDic.Values)
                {
                    foreach (var item2 in item)
                    {
                        var page = new ItemEnablePage()
                        {
                            Name = item2.Name,
                            Module = item2.Module,
                            Type = item2.Type,
                        };
                        ceinfo.ItemEnableBook.Add(page);

                        if (item2.IsSelected)
                        {
                            ceinfo.SelectedPage = page;
                        }
                    }
                }
                _maintainerItemConfigEnableInfos.Add(ceinfo);

                OrderMaintainItem();
                ReShapeEnableConfigTable();

                #endregion

                #region 通知RT变更

                InvokeClient.Instance.Service.DoOperation("MaintainManager.AddMaintainItem",
                            vm.ItemInfo.Name,
                            vm.ItemInfo.ParentName,
                            vm.ItemInfo.UID,
                            vm.ItemInfo.Index,
                            vm.ItemInfo.Description,
                            vm.ItemInfo.DefaultRecord,
                            vm.ItemInfo.FilePath);

                #endregion

            }

        }

        #endregion

        #region Plan

        public void MaintainerSetting(MaintainerInfo info)
        {
            if (info == null || !_maintainerInfoDic.ContainsKey(info.Name))
            {
                return;
            }
            
            var vm = new MaintainerSettingViewModel(info, _maintainerInfoDic[info.Name].ToList());
            _windowmanager.ShowDialog(vm);
            if (vm.DialogResult == ResultYesNo.YES)
            {
                if (_maintainerInfoDic.ContainsKey(info.Name))
                {
                    #region 更新本界面信息

                    info.Module = vm.MaInfo.Module;
                    info.Index = vm.MaInfo.Index;
                    info.Enable = vm.MaInfo.Enable;
                    info.Description = vm.MaInfo.Description;
                    info.StartDate = vm.MaInfo.StartDate;
                    info.Threshold = vm.MaInfo.Threshold;
                    info.TimeDisplayUnit = vm.MaInfo.TimeDisplayUnit;
                    info.InvokePropertyChanged();

                    #endregion

                    #region 通知RT变更

                    InvokeClient.Instance.Service.DoOperation("MaintainManager.SetMaintainerParas",
                       vm.MaInfo.Type,
                        vm.MaInfo.Name,
                        info.Module,
                        vm.MaInfo.Module,
                        vm.MaInfo.Index,
                        vm.MaInfo.Enable,
                        vm.MaInfo.Description,
                        vm.MaInfo.StartDate,
                        vm.MaInfo.Threshold,
                        vm.MaInfo.TimeDisplayUnit);

                    #endregion
                }


            }
        }

        public void MaintainerDelete(MaintainerInfo info)
        {
            if (info == null)
            {
                return;
            }
            if (DialogBox.Confirm("Operation cannot be undone.Do you want to Remove the Plan?"))
            {
                #region 更新本界面信息

                _maintainerInfoDic[info.Name].RemoveIfContains(info);

                foreach (var i in _maintainerItemConfigEnableInfos)
                {
                    var item = i.ItemEnableBook.ToList().Find(i => i.EqualsTypeNameModule(info.Type, info.Name, info.Module));
                    if (item != null)
                    {
                        i.ItemEnableBook.Remove(item);
                    }
                }

                SelectionChanged();

                #endregion

                #region 通知RT变更

                InvokeClient.Instance.Service.DoOperation("MaintainManager.DeleteMaintainer", info.Type, info.Name, info.Module);

                #endregion

            }
        }

        public void AddNewPlan()
        {
            var vm = new MaintainerSettingViewModel(_maintainerInfoDic);
            _windowmanager.ShowDialog(vm);
            if (vm.DialogResult == ResultYesNo.YES)
            {
                #region 更新本界面信息

                if (_maintainerInfoDic.ContainsKey(vm.MaInfo.Name))
                {
                    _maintainerInfoDic[vm.MaInfo.Name].Add(vm.MaInfo);
                }

                OrderMaintainer();

                foreach (var item in _maintainerItemConfigEnableInfos)
                {
                    item.ItemEnableBook.Add(new ItemEnablePage
                    {
                        Type = vm.MaInfo.Type,
                        Name = vm.MaInfo.Name,
                        Module = vm.MaInfo.Module,
                        Value = false
                    });
                }

                SelectionChanged();

                #endregion

                #region 通知RT变更

                InvokeClient.Instance.Service.DoOperation("MaintainManager.AddMaintainer",
                            vm.MaInfo.Type,
                            vm.MaInfo.Name,
                            vm.MaInfo.Module,
                            vm.MaInfo.Index,
                            vm.MaInfo.Enable,
                            vm.MaInfo.Description,
                            vm.MaInfo.StartDate,
                            vm.MaInfo.Threshold,
                            vm.MaInfo.TimeDisplayUnit);

                #endregion
            }
        }

        #endregion

        #endregion
    }
}
