using FLY.OBJComponents.IService;
using MultiLayout.UiModule; 
using Misc;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FLY.Thick.Base.UI;
using Unity;
using FLY.Thick.Base.Common;
using MultiLayout;
using System.Windows.Threading;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace FLY.Thick.Base.UI.OnInit
{
    public class OnInitWarnings : IOnInit
    {
        public int Level { get; private set; }


        WarningSystemManager warningSystemManager;
        IUnityContainer container;
        FlyLayoutManager flyLayoutManager;
        DispatcherTimer timer_error;
        int reason_list_index = -1;

        public OnInitWarnings(
            IUnityContainer container,
            FlyLayoutManager flyLayoutManager,
            WarningSystemManager warningSystemManager,
            int lv = 1) 
        {
            Level = lv;
            this.container = container;
            this.flyLayoutManager = flyLayoutManager;
            this.warningSystemManager = warningSystemManager;
            
            if (warningSystemManager.Warnings.Count() == 0)
                return;

            this.flyLayoutManager.ErrMsgClick = ErrMsg_OnClick;

        }
        public void OnInit()
        {
            if (warningSystemManager.Warnings.Count() == 0)
                return;

            warningSystemManager.PropertyChanged += WarningSystemManager_PropertyChanged;
            //报警原因轮流显示
            timer_error = new DispatcherTimer();
            timer_error.Interval = TimeSpan.FromSeconds(3);
            timer_error.Tick += (s, e) =>
            {
                reason_list_index--;
                if (reason_list_index < 0)
                    reason_list_index = warningSystemManager.Errors.Count();
                
                UpdateError();
            };
            UpdateError();
        }

        private void WarningSystemManager_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(warningSystemManager.Errors)) {
                reason_list_index = warningSystemManager.Errors.Count() - 1;
                UpdateError();
            }
        }
        void UpdateError() 
        {
            if (warningSystemManager.Errors.Count() == 0)
            {
                flyLayoutManager.ErrMsg = null;
                timer_error.Stop();
            }
            else {
                if (reason_list_index < 0)
                    reason_list_index = 0;
                else if (reason_list_index > warningSystemManager.Errors.Count() - 1) {
                    reason_list_index = warningSystemManager.Errors.Count() - 1;
                }

                var err = warningSystemManager.Errors[reason_list_index];
                flyLayoutManager.ErrMsg = $"{err.DevName} {err.Description}";
                timer_error.Start();
            }
        }
        private void ErrMsg_OnClick() {
            //打开管理页面
            var p = container.Resolve<PgErrorsTable>();
            FlyLayoutManager.NavigationService.Navigate(p);
        }
    }

    public class WarningSystemManager : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public List<WarningSystem2ServiceClientWithName> Warnings { get; private set; } = new List<WarningSystem2ServiceClientWithName>();

        public List<ErrorWithName> Errors { get; private set; } = new List<ErrorWithName>();


        [InjectionMethod]
        public void Init(IUnityContainer container)
        {
            //找到 warnings.service 容器
            if (!container.IsRegistered<IUnityContainer>("warnings.service"))
                return;

            var warning_container = container.Resolve<IUnityContainer>("warnings.service");

            //获取全部报警管理器
            Warnings = warning_container.ResolveAll<WarningSystem2ServiceClientWithName>().ToList();

            foreach (var warning in Warnings)
            {
                warning.PropertyChanged += WarningService_PropertyChanged;
            }
            updateErrors();
        }
        private void WarningService_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if ((e.PropertyName == nameof(WarningSystem2ServiceClientWithName.ReasonList))
                ||(e.PropertyName == nameof(WarningSystem2ServiceClientWithName.IsConnected)))
            {
                updateErrors();
            }
            
        }
        void updateErrors()
        {
            List<ErrorWithName> errors = new List<ErrorWithName>();
            foreach (var warning in Warnings)
            {
                if (!warning.IsConnected)
                {
                    errors.Add(new ErrorWithName()
                    {
                        DevName = warning.DevName,
                        Time = DateTime.Now,
                        ErrCode = 0,
                        Description = "服务器连接断开"
                    });
                }
                else if (warning.ReasonList != null && warning.ReasonList.Count() > 0) {
                    errors.AddRange(warning.ReasonList.Select(e =>
                    new ErrorWithName()
                    {
                        DevName = warning.DevName,
                        Time = e.Time,
                        ErrCode = e.ErrCode,
                        Description = e.Description
                    }));
                }
            }
            if (errors.Count > 0)
            {
                errors.Sort((e1, e2) =>
                {
                    return e1.Time.CompareTo(e2.Time);
                });
                Errors = errors;
            }
            else {
                Errors = new List<ErrorWithName>();
            }
        } 
    }
    public class ErrorWithName:INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// 设备名称
        /// </summary>
        public string DevName { get; set; }

        /// <summary>
        /// 时间
        /// </summary>
        public DateTime Time { get; set; }

        /// <summary>
        /// 出错码
        /// </summary>
        public int ErrCode { get; set; }

        /// <summary>
        /// 描述
        /// </summary>
        public string Description { get; set; }


    }
}

