using CommunityToolkit.Mvvm.Input;
using FLY.OBJComponents.IService;
using FLY.Thick.Base.Common;
using FLY.Thick.Base.IService;
using FObjBase.Reflect;
using MultiLayout;
using MultiLayout.UiModule;
using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Threading;
using Unity;

namespace FLY.Thick.Base.UI.UiModule
{
    /// <summary>
    /// DynAreaIO.xaml 的交互逻辑
    /// </summary>
    public partial class DynAreaIO : UserControl
    {
        DynAreaErrorVm2 errorVm;
        DynAreaIOVm ioVm;

        IUnityContainer container;

        public DynAreaIO()
        {
            InitializeComponent();
        }
        [InjectionMethod]
        public void Init(
            IUnityContainer container,
            IWarningSystem2Service warningSystem)
        {
            this.container = container;
            ioVm = container.Resolve<DynAreaIOVm>();

            errorVm = new DynAreaErrorVm2();

            var serverName = (string)Application.Current.FindResource("str.DynArea.TGauge");
            //TODO, 只能翻译 FLY.Base.Common.ERRNOs 定义的。  就算是它的子类，也需要提前调用 子类静态构造函数
            errorVm.Init(container, warningSystem, serverName, ERRNOs.GetDescription);

            this.DataContext = ioVm;
            grid_error.DataContext = errorVm;
        }
    }

    public class DynAreaIOVm : INotifyPropertyChanged
    {
        #region 延时推送 MARKNO
        const int MARKNO_UPDATEERROR = 1;
        #endregion

        public event PropertyChangedEventHandler PropertyChanged;

        public UInt16 IStatus { get; set; } = 0xffff;
        public UInt16 OStatus { get; set; } = 0x00ff;

        /// <summary>
        /// 16输入口 X0~X15
        /// </summary>
        public bool IsFlyAdHardwareVersion3 { get; set; }

        /// <summary>
        /// 12输入口 I1~I12
        /// </summary>
        public bool IsFlyAdHardwareVersion2 { get; set; }

        /// <summary>
        /// 12输入口 X0~X11
        /// </summary>
        public bool IsFlyAdHardwareVersion2p1 { get; set; }


        public int Hrs { get; set; } = 3;

        /// <summary>
        /// 是永久使用
        /// </summary>
        public bool IsForever { get; set; } = false;

        public RelayCommand OpenIoTipCmd { get; private set; }
        public RelayCommand OpenAccessCmd { get; private set; }

        DynArea dynArea;
        IFlyADService flyAdService;
        IUnityContainer container;
        public DynAreaIOVm()
        {
            OpenIoTipCmd = new RelayCommand(OpenIoTip);
            OpenAccessCmd = new RelayCommand(OpenAccess);
        }


        [InjectionMethod]
        public void Init(
            IUnityContainer container,
            ITDGageService gageService,
            IFlyADService flyADService)
        {
            this.dynArea = gageService.DynArea;
            this.flyAdService = flyADService;
            this.container = container;

            Misc.BindingOperations.SetBinding(this.dynArea, nameof(this.dynArea.IStatus), this, nameof(IStatus));
            Misc.BindingOperations.SetBinding(this.dynArea, nameof(this.dynArea.OStatus), this, nameof(OStatus));
            
            Misc.BindingOperations.SetBinding(this.dynArea, nameof(this.dynArea.Hrs), this, nameof(Hrs));

            Misc.BindingOperations.SetBinding(flyAdService,
                new string[] { nameof(flyAdService.HardwareVersion), nameof(flyAdService.HardwareVersionMinor) }, this, () => {
                    if (flyAdService.HardwareVersion == 3)
                    {
                        IsFlyAdHardwareVersion3 = true;
                        IsFlyAdHardwareVersion2 = false;
                        IsFlyAdHardwareVersion2p1 = false;
                    }
                    else// if(flyAdService.HardwareVersion==2)
                                {
                        if (flyAdService.HardwareVersionMinor == 1)
                        {
                            IsFlyAdHardwareVersion3 = false;
                            IsFlyAdHardwareVersion2 = false;
                            IsFlyAdHardwareVersion2p1 = true;
                        }
                        else
                        {
                            IsFlyAdHardwareVersion3 = false;
                            IsFlyAdHardwareVersion2 = true;
                            IsFlyAdHardwareVersion2p1 = false;
                        }
                    }

                });

            UpdateIsForever();

            this.dynArea.PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == nameof(this.dynArea.Hrs))
                {
                    UpdateIsForever();
                }
            };
        }
        void UpdateIsForever()
        {
            if (dynArea.Hrs > 50000)
                IsForever = true;
            else
                IsForever = false;
        }

        private void OpenAccess()
        {
            WdFlyADAccess w = new WdFlyADAccess();
            var flyAdService = container.Resolve<FLY.Thick.Base.IService.IFlyADService>();
            w.Init(flyAdService);
            w.Owner = App.Current.MainWindow;
            w.ShowDialog();
        }

        private void OpenIoTip()
        {
            var w = new WdIOTip();
            container.BuildUp(w);

            w.Owner = App.Current.MainWindow;
            w.ShowDialog();
        }
    }
    public class DynAreaIOVmUt : DynAreaIOVm
    {
        public DynAreaIOVmUt()
        {
            IStatus = 0xff7f;
            OStatus = 0x0005;
            Hrs = 2000;
            IsForever = false;
        }
    }


    public class DynAreaErrorVm2 : INotifyPropertyChanged
    {
        /// <summary>
        /// 有异常
        /// </summary>
        public bool IsError { get; set; }
        /// <summary>
        /// 异常消息
        /// </summary>
        public string ErrMsg { get; set; }

        public RelayCommand OpenWarningCmd { get; }

        public event PropertyChangedEventHandler PropertyChanged;


        IWarningSystem2Service warningSystem;
        IUnityContainer container;

        /// <summary>
        /// 服务名称，用于显示 XXX服务器连接断开
        /// </summary>
        string serverName;

        DispatcherTimer timer_error;
        private int reason_list_index = -1;

        bool isTGauge;

        ToDescriptionHandler toDescription;

        public DynAreaErrorVm2()
        {
            OpenWarningCmd = new RelayCommand(OpenWarning);
        }


        public void Init(
            IUnityContainer container,
            IWarningSystem2Service warningSystem,
            string serverName,
            ToDescriptionHandler toDescription)
        {
            this.container = container;
            this.warningSystem = warningSystem;
            this.serverName = serverName;
            this.toDescription = toDescription;

            //报警原因轮流显示
            timer_error = new DispatcherTimer();
            timer_error.Interval = TimeSpan.FromSeconds(3);
            timer_error.Tick += (s, e) =>
            {
                reason_list_index--;
                if (reason_list_index < 0)
                    if (warningSystem.ReasonList != null && warningSystem.ReasonList.Count() > 0)
                        reason_list_index = warningSystem.ReasonList.Count();
                    else
                        reason_list_index = -1;
                UpdateError();
            };
            warningSystem.PropertyChanged += WarningSystem_PropertyChanged;

            UpdateError();
        }

        private void WarningSystem_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(Reflect_SeviceClient.IsConnected))
            {
                UpdateError();
            }
            else if (e.PropertyName == nameof(warningSystem.ReasonList))
            {
                if (warningSystem.ReasonList != null && warningSystem.ReasonList.Count() > 0)
                    reason_list_index = warningSystem.ReasonList.Count() - 1;
                else
                    reason_list_index = -1;

                UpdateError();
            }
        }
        void UpdateError()
        {
            if (this.warningSystem is FObjBase.FObjServiceClient)
            {
                var client = this.warningSystem as FObjBase.FObjServiceClient;

                string state_msg = (string)Application.Current.TryFindResource("str.DynArea.ServerDC");
                if (!client.IsConnected)
                {
                    ErrMsg = $"{serverName}{state_msg}";
                    IsError = true;
                    reason_list_index = -1;
                    timer_error.Stop();
                    return;
                }
            }

            if (warningSystem.ReasonList != null && warningSystem.ReasonList.Count() > 0)
            {
                if (reason_list_index >= warningSystem.ReasonList.Count())
                    reason_list_index = warningSystem.ReasonList.Count() - 1;
                else if (reason_list_index < 0)
                    reason_list_index = 0;

                //通过资源翻译报警信息
                if (toDescription != null)
                {
                    ErrMsg = toDescription(warningSystem.ReasonList[reason_list_index].ErrCode);
                }
                else
                {
                    ErrMsg = warningSystem.ReasonList[reason_list_index].Description;
                }
                IsError = true;
                timer_error.Start();
            }
            else
            {
                IsError = false;
                ErrMsg = "";
                reason_list_index = -1;
                timer_error.Stop();
            }
        }

        private void OpenWarning()
        {
            if (!WdPassword.Authorize("Warning"))
                return;

            if (isTGauge)
            {
                //测厚仪的
                var p = new PgErrorTable();
                p.Init(container, warningSystem, toDescription);
                FlyLayoutManager.NavigationService.Navigate(p);
            }
            else
            {
                var p = new PgErrorTable2();
                p.Init(container, warningSystem, toDescription);
                FlyLayoutManager.NavigationService.Navigate(p);
            }
        }

    }
    public class UiModule2_DynAreaIO : IUiModule2
    {
        public string Title => "测厚.IO状态(报警)";

        public ComponentType Type => ComponentType.DynArea;

        public bool IsUnique => true;

        public FrameworkElement GetComponent(int id, IUnityContainer container)
        {
            DynAreaIO graph = container.Resolve<DynAreaIO>();
            return graph;
        }

        public FrameworkElement GetThumbnail()
        {
            return new System.Windows.Controls.Grid();
        }

        public void MatchParam(int[] IDs)
        {

        }
    }
}
