using FLY.OBJComponents.Client;
using FLY.Thick.Base.Common;
using FLY.Thick.Base.IService;
using MultiLayout.UiModule;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using FLY.Thick.Base.UI;
using Unity;
using Unity.Resolution;
using MultiLayout;
using FLY.OBJComponents.IService;

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

        DynAreaIOViewModel viewModel;

        IUnityContainer container;

        public DynAreaIO()
        {
            InitializeComponent();
        }
        [InjectionMethod]
        public void Init(
            IUnityContainer container, 
            ITDGageService gageService,
            IWarningSystem2Service warningSystem)
        {
            this.container = container;
            viewModel = new DynAreaIOViewModel();
            viewModel.Init(gageService, gageService.DynArea, warningSystem);
            this.DataContext = viewModel;
        }

        protected virtual void Border_IO_Click(object sender, RoutedEventArgs e)
        {
            if (!WdPassword.Authorize("Warning"))
                return;
            var p = container.Resolve<PgErrorTable>();
            FlyLayoutManager.NavigationService.Navigate(p);

        }
    }

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

        public event PropertyChangedEventHandler PropertyChanged;

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

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

        /// <summary>
        /// 是永久使用
        /// </summary>
        public bool IsForever { get; set; } = false;
        public bool IsError { get; set; }
        /// <summary>
        /// 异常消息
        /// </summary>
        public string ErrMsg { get; set; }

        ITDGageService gageService;
        DynArea dynArea;
        IWarningSystem2Service warningSystem;
        DispatcherTimer timer_error;
        private int reason_list_index = -1;
        public void Init(ITDGageService gageService, DynArea dynArea, IWarningSystem2Service warningSystem)
        {
            //创建窗口观察 报警原因列表
            this.warningSystem = warningSystem;
            this.dynArea = dynArea;
            this.gageService = gageService;

            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));
            UpdateIsForever();


            //报警原因轮流显示
            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;

            if (this.gageService is FObjBase.FObjServiceClient) {
                var client = this.gageService as FObjBase.FObjServiceClient;
                client.PropertyChanged += (s, e) =>
                {
                    if (e.PropertyName == nameof(FObjBase.FObjServiceClient.IsConnected)) {
                        UpdateError();
                    }
                };
            }

            this.dynArea.PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == nameof(this.dynArea.Hrs))
                {
                    UpdateIsForever();
                }
            };

            UpdateError();
        }

        private void WarningSystem_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            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 UpdateIsForever()
        {
            if (dynArea.Hrs > 50000)
                IsForever = true;
            else
                IsForever = false;
        }


        void UpdateError()
        {
            if (this.warningSystem is FObjBase.FObjServiceClient)
            {
                var client = this.warningSystem as FObjBase.FObjServiceClient;
                if (!client.IsConnected)
                {
                    ErrMsg = "服务器连接断开";
                    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;


                ErrMsg = warningSystem.ReasonList[reason_list_index].Description;
                IsError = true;
                timer_error.Start();
            }
            else
            {
                IsError = false;
                ErrMsg = "";
                reason_list_index = -1;
                timer_error.Stop();
            }
        }

    }
    public class DynAreaIOViewModel_UnitTest : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public UInt16 IStatus { get; set; } = 0xff7f;
        public UInt16 OStatus { get; set; } = 0x0005;

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

        /// <summary>
        /// 是永久使用
        /// </summary>
        public bool IsForever { get; set; } = false;
        public bool IsError { get; set; }
        /// <summary>
        /// 异常消息
        /// </summary>
        public string ErrMsg { get; set; }
    }


    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)
        {

        }
    }
}
