using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SlnMesnac.Config;
using SlnMesnac.Model.domain;
using SlnMesnac.Plc;
using SlnMesnac.Serilog;
using SlnMesnac.WPF.Page;
using SlnMesnac.WPF.Page.Generate;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace SlnMesnac.WPF.ViewModel
{
    public class MainWindowViewModel : ViewModelBase
    {
        public readonly SerilogHelper _logger;
        public List<PlcAbsractFactory> plcList;

        // private readonly GenerateControl generateControl = new GenerateControl();
        private readonly IndexControl indexControl = new IndexControl();

        private readonly DeviceMonitorControl deviceMonitorPage = new DeviceMonitorControl();
        private readonly TaskHistoryControl taskHistoryControl = new TaskHistoryControl();

        private readonly TonerBoxingControl tonerBoxingControl = new TonerBoxingControl();

        private readonly LocationAndStockControl locationAndStockControl = new LocationAndStockControl();
        private DispatcherTimer _timer;

        #region 参数定义

        /// <summary>
        /// 当前时间
        /// </summary>
        private string _CurrentTime = "";

        public string CurrentTime
        {
            get { return _CurrentTime; }
            set { _CurrentTime = value; RaisePropertyChanged(nameof(CurrentTime)); }
        }

        /// <summary>
        /// PLC设备状态
        /// </summary>
        private int _PlcStatus = 0;

        public int PlcStatus
        {
            get { return _PlcStatus; }
            set { _PlcStatus = value; RaisePropertyChanged(nameof(PlcStatus)); }
        }

        /// <summary>
        /// 箱壳扫码器状态
        /// </summary>
        private int _ShellScannerStatus = 0;

        public int ShellScannerStatus
        {
            get { return _ShellScannerStatus; }
            set { _ShellScannerStatus = value; RaisePropertyChanged(nameof(ShellScannerStatus)); }
        }

        /// <summary>
        /// 内胆扫码器状态
        /// </summary>
        private int _BoldScannerStatus = 0;

        public int BoldScannerStatus
        {
            get { return _BoldScannerStatus; }
            set { _BoldScannerStatus = value; RaisePropertyChanged(nameof(BoldScannerStatus)); }
        }

        public System.Windows.Controls.UserControl _content;

        public System.Windows.Controls.UserControl UserContent
        {
            get { return _content; }

            set
            {
                _content = value;
                RaisePropertyChanged(nameof(UserContent));
            }
        }

        #endregion 参数定义

        #region 事件定义

        /// <summary>
        /// 打开系统键盘
        /// </summary>
        public RelayCommand OpenSystemKeyboardCommand { get; set; }

        /// <summary>
        /// 窗体控制
        /// </summary>
        public RelayCommand<object> FormControlCommand { get; set; }

        #endregion 事件定义

        public MainWindowViewModel()
        {
            _logger = App.ServiceProvider.GetService<SerilogHelper>();
            plcList = App.ServiceProvider.GetRequiredService<List<PlcAbsractFactory>>();
            FormControlCommand = new RelayCommand<object>(x => FormControl(x));
            UserContent = indexControl;
            Init();
        }

        private void Init()
        {
            StartCheckStatus();

            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromSeconds(1);
            _timer.Tick += Timer_Tick;
            _timer.Start();
        }

        #region

        /// <summary>
        /// 检查设备状态自动重连
        /// </summary>
        private void StartCheckStatus()
        {
            Task.Run(async () =>
            {
                while (true)
                {
                    try
                    {
                        #region PLC状态
                        foreach (var plc in plcList)
                        {
                            PlcConfig? plcConfig = App.ServiceProvider.GetService<AppConfig>().plcConfig.FirstOrDefault(x => x.plcKey == plc.ConfigKey);
                            if (plc != null && plc.IsConnected)
                            {
                                plc.IsConnected = plc.readHeartByAddress("M100");  //DB100.DBX0.0
                                if (!plc.IsConnected)
                                {
                                    plc.IsConnected = await plc.ConnectAsync(plcConfig.plcIp, plcConfig.plcPort);
                                }
                            }
                            else
                            {
                                if (plcConfig != null)
                                {
                                    bool result = await plc.ConnectAsync(plcConfig.plcIp, plcConfig.plcPort);
                                    plc.IsConnected = result;
                                }
                            }
                            PlcStatus = plc.IsConnected ? 1 : 2;
                        }

                        #endregion PLC状态
                    }
                    catch (Exception ex)
                    {
                        _logger.Error($"监听设备状态异常:{ex.Message}");
                    }
                    await Task.Delay(1000 * 10);
                }
            });
        }

        #endregion

        /// <summary>
        /// 更新系统时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer_Tick(object sender, EventArgs e)
        {
            CurrentTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        /// <summary>
        ///  窗体控制
        /// </summary>
        /// <param name="obj"></param>
        private void FormControl(object obj)
        {
            try
            {
                string controlType = obj as string;
                switch (controlType)
                {
                    case "Index":
                        UserContent = indexControl;
                        break;

                    case "DeviceMonitor":
                        UserContent = deviceMonitorPage;
                        break;

                    case "LocationAndStock":
                        UserContent = locationAndStockControl;
                        break;

                    case "TaskHistory":
                        UserContent = taskHistoryControl;
                        break;

                    case "TonerBoxing":
                        UserContent = tonerBoxingControl;
                        break;

                    // 还原 或者 最大化当前窗口
                    case "Normal":
                        if (Application.Current.MainWindow.WindowState == WindowState.Normal)
                        {
                            Application.Current.MainWindow.WindowState = WindowState.Maximized;
                            break;
                        }
                        if (Application.Current.MainWindow.WindowState == WindowState.Maximized)
                        {
                            Application.Current.MainWindow.WindowState = WindowState.Normal;
                            break;
                        }
                        break;

                    case "Minimized":
                        Application.Current.MainWindow.WindowState = WindowState.Minimized;
                        break;

                    case "Exit":
                        Application.Current.Shutdown();
                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                _logger.Error("窗体控制逻辑异常", ex);
            }
        }
    }
}