using FLY.OBJComponents.Client;
using FLY.OBJComponents.Common;
using FLY.OBJComponents.IService;
using FLY.Thick.Base.UI;
using FLY.Weight2.Client;
using FLY.Weight2.IService;
using FObjBase;
using MultiLayout;
using MultiLayout.UiModule;
using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Windows.Threading;
using Unity;

namespace FLY.Weight2.UI.Client.UiModule
{
    /// <summary>
    /// DynAreaWeight.xaml 的交互逻辑
    /// </summary>
    public partial class DynAreaWeight : UserControl
    {

        #region 延时推送 MARKNO
        const int MARKNO_UPDATEERROR = 1;
        #endregion

        IUnityContainer container;
        IWeightSystemService weightSystemService;
        WarningReasonWindow warningReasonWindow;
        IWarningService warningService;

        DispatcherTimer timer_error;
        DynAreaViewModelParams props = new DynAreaViewModelParams();
        SetPLCUpdatePlan setPlan;

        public DynAreaWeight()
        {
            InitializeComponent();

        }

        [InjectionMethod]
        public void Init(
            IUnityContainer container,
            [Dependency("weighterWarningReasonWindow")] WarningReasonWindow warningReasonWindow,
            [Dependency("weighterWarningService")]IWarningService warningService,
            IWeightSystemService weightSystemService
            )
        {
            this.container = container;
            this.weightSystemService = weightSystemService;

            //创建窗口观察 报警原因列表
            this.warningReasonWindow = warningReasonWindow;
            this.warningService = warningService;


            //报警原因轮流显示
            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 = this.warningReasonWindow.Record.Count();
                updateError();
            };
            this.warningReasonWindow.Record.CollectionChanged += Record_CollectionChanged;


            grid_weighter.DataContext = this.weightSystemService;
            grid_error.DataContext = props;

            //注册属性更新计划
            setPlan = new SetPLCUpdatePlan(
                this.weightSystemService.PLCos,
                this.weightSystemService.Accessory,
                new string[] {
                    "Thickness",
                    "RimCharge"});

            this.weightSystemService.PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == "IsConnected")
                {
                    updateError();
                }
            };

            updateError();

        }




        private void Record_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            FObjBase.PollModule.Current.Poll_JustOnce(
                new FObjBase.PollModule.PollHandler(delegate ()
                {
                    reason_list_index = warningReasonWindow.Record.Count() - 1;

                    updateError();
                }), this, MARKNO_UPDATEERROR);
        }

        void updateError()
        {
            if (weightSystemService is FObjServiceClient) 
            {
                var objClient = weightSystemService as FObjServiceClient;
                if (!objClient.IsConnected) {
                    props.Error = "称重服务器连接断开";
                    props.IsError = true;
                    reason_list_index = -1;
                    timer_error.Stop();
                    return;
                }
            }

            if (warningReasonWindow.Record.Count == 0) {
                props.IsError = false;
                props.Error = "";
                reason_list_index = -1;
                timer_error.Stop();
                return;
            }

            if (reason_list_index >= warningReasonWindow.Record.Count)
                reason_list_index = warningReasonWindow.Record.Count - 1;
            else if (reason_list_index < 0)
                reason_list_index = 0;


            props.Error = warningReasonWindow.Record[reason_list_index].Description;
            props.IsError = true;
            timer_error.Start();
        }
        private int reason_list_index = -1;



        private void Button_Click(object sender, RoutedEventArgs e)
        {
            PgErrorTable2 p = new PgErrorTable2();
            p.Init(container, warningService, warningReasonWindow);
            FlyLayoutManager.NavigationService.Navigate(p);
        }
    }
    public class DynAreaViewModelParams : INotifyPropertyChanged
    {
        /// <summary>
        /// 有异常
        /// </summary>
        public bool IsError { get; set; }
        /// <summary>
        /// 异常消息
        /// </summary>
        public string Error { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;
    }

    public class UiModule2_DynAreaWeight : MultiLayout.UiModule.IUiModule2
    {
        /// <summary>
        /// 控件标题
        /// 它的值取决于culture
        /// </summary>
        public string Title=> "单组份称重状态";

        public ComponentType Type => ComponentType.DynArea;
        public bool IsUnique => true;
        /// <summary>
        /// 控件
        /// 创建时,需要给它唯一ID,让加载自己的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public FrameworkElement GetComponent(int id, IUnityContainer container)
        {
            DynAreaWeight graph = new DynAreaWeight();
            container.BuildUp(graph);
            return graph;
        }

        /// <summary>
        /// 控件缩略图,用于编辑界面时,大致看看
        /// 创建时,需要给它唯一ID,让加载自己的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public FrameworkElement GetThumbnail()
        {
            return new System.Windows.Controls.Grid();
        }


        /// <summary>
        /// 给出全部控件ID, 控件自行删除没有的参数
        /// </summary>
        /// <param name="IDs"></param>
        public void MatchParam(int[] IDs)
        {
        }
    }
}