using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OracleInternal.Sharding;
using ServiceStack;
using SlnMesnac.Business;
using SlnMesnac.Business.@base;
using SlnMesnac.Common;
using SlnMesnac.Config;
using SlnMesnac.Plc;
using SlnMesnac.TouchSocket;
using SlnMesnac.WPF.Page;
using SlnMesnac.WPF.Page.Generate;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Threading;

namespace SlnMesnac.WPF.ViewModel
{
    public class MainWindowViewModel : ViewModelBase
    {
        private readonly ILogger<MainWindowViewModel> _logger;
        private readonly DebugConfig debugConfig = DebugConfig.Instance;
        private readonly DevMonitorPage devMonitorPage = new DevMonitorPage();
        private readonly ProdMgmtPage prodMgmtPage = new ProdMgmtPage();
        private readonly LocationPage locationPage = new LocationPage();

        private readonly ProdStatisticsPage prodStatisticsPage = new ProdStatisticsPage();
        //代码生成
        private readonly GenerateControl generateControl = new GenerateControl();
        private readonly BaseConfigInfoPage configInfoPage = new BaseConfigInfoPage();
        private readonly RecipeManagePage recipeManagePage = new RecipeManagePage();
        private readonly AgvAndTaskMonitorPage agvAndTaskMonitorPage = new AgvAndTaskMonitorPage();
        private System.Timers.Timer timer = new System.Timers.Timer(1000 * 60);
        PlcAbsractFactory? plc = null;
        private PlcAbsractFactory? pressurePlc = null;
        private BaseBusiness? baseBusiness = null;
        #region 参数定义

      

        private string _Date;
        public string Date
        {
            get { return _Date; }
            set
            {
                _Date = value;
                RaisePropertyChanged(nameof(Date));
            }
        }

        private string _ModeName;
        public string ModeName
        {
            get { return _ModeName; }
            set
            {
                _ModeName = value;
                RaisePropertyChanged(nameof(ModeName));
            }
        }

        private string _PageName;
        public string PageName
        {
            get { return _PageName; }
            set
            {
                _PageName = value;
                RaisePropertyChanged(nameof(PageName));
            }
        }

        /// <summary>
        /// PLC设备状态
        /// </summary>
        private int _PlcStatus = 0;
        public int PlcStatus
        {
            get { return _PlcStatus; }
            set { _PlcStatus = value; RaisePropertyChanged(nameof(PlcStatus)); }
        }

        /// <summary>
        /// 压力PLC设备状态
        /// </summary>
        private int _PressurePlcStatus = 0;
        public int PressurePlcStatus
        {
            get { return _PressurePlcStatus; }
            set { _PressurePlcStatus = value; RaisePropertyChanged(nameof(PressurePlcStatus)); }
        }

        /// <summary>
        /// 喷码机状态
        /// </summary>
        private int _PmStatus = 0;
        public int PmStatus
        {
            get { return _PmStatus; }
            set { _PmStatus = value; RaisePropertyChanged(nameof(PmStatus)); }
        }

        /// <summary>
        /// RFID1状态
        /// </summary>
        private int _Out2FRfidStatus = 0;
        public int Out2FRfidStatus
        {
            get { return _Out2FRfidStatus; }
            set { _Out2FRfidStatus = value; RaisePropertyChanged(nameof(Out2FRfidStatus)); }
        }


        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<object> ControlOnClickCommand { get; set; }

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

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

        public MainWindowViewModel()
        {

            _logger = App.ServiceProvider.GetService<ILogger<MainWindowViewModel>>();

            UserContent = prodMgmtPage;
            PageName = "京源环保SCADA";
            debugConfig.ProductMode = "1";
            ControlOnClickCommand = new RelayCommand<object>(obj => ControlOnClick(obj));
            FormControlCommand = new RelayCommand<object>(x => FormControl(x));
            baseBusiness = App.ServiceProvider.GetService<BaseBusiness>();
            plc = baseBusiness.GetPlcByKey("plc");
            pressurePlc = baseBusiness.GetPlcByKey("pressurePlc");
            StartLiseningStatus();
            checkStatus();
            RefreshTime();
           
        }



        /// <summary>
        /// 检查版本--暂时不使用
        /// </summary>
        private void CheckVersion()
        {
            try
            {
                string version = HttpHelper.SendGetMessage("172.16.12.100", 5001, "wcs/RecieveRcs/version");
                var vs = new Version(version);
            //    SystemData.VerSion
                var lovs = new Version(debugConfig.Version);
                if (vs > lovs)
                {
                    var result = MessageBox.Show("有新版本是否更新？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Information);
                    if (result == MessageBoxResult.Yes)
                    {
                        Process.Start("AutoUpdate.exe", new List<string>
                                        {
                                            version,
                                            debugConfig.ProcessName,
                                           // SystemData.ProcessName,
                                            $"http://172.16.12.100:5001/wcs/RecieveRcs?fileName={debugConfig.ProcessName}.zip"
                                        });
                        debugConfig.Version = version;
                        Application.Current.Shutdown();
                        Process.GetCurrentProcess().Kill();
                    }
                }
            }
            catch
            {

            }
        }


        private void RefreshTime()
        {
            DispatcherTimer _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromSeconds(1);
            _timer.Tick += Timer_Tick;
            _timer.Start();
        }
        private void Timer_Tick(object sender, EventArgs e)
        {
            Date = DateTime.Now.ToString("yyyy年MM月dd日:HH:mm:ss");
          
            ModeName = debugConfig.ProductMode == "1" ? "投料模式 : 手动模式" : "投料模式 : 自动模式";
        }

        #region 监听外部设备状态:PLC、喷码机、RFID
        /// <summary>
        /// 监听外部设备状态:PLC、喷码机、RFID
        /// </summary>
        private void StartLiseningStatus()
        {
            timer.Elapsed += new System.Timers.ElapsedEventHandler(LiseningStatus);
            timer.AutoReset = true;
            timer.Enabled = true;
            timer.Start();

        }

        private void LiseningStatus(object? sender, ElapsedEventArgs e)
        {
            timer.Stop();
            checkStatus();
            timer.Start();
        }

        private void checkStatus()
        {
            try
            {
                #region PLC状态
                CheckPlcStatus(plc, "plc", status => PlcStatus = status);
                #endregion

                #region 压力PLC状态断线重连
                CheckPlcStatus(pressurePlc, "pressurePlc", status => PressurePlcStatus = status);
                #endregion

                #region 喷码机状态
                if (ProdCompletionBusiness.PmTryAmount == 0)
                {
                    PmStatus = 1;
                }
                else
                {
                    PmStatus = 2;
                }
                #endregion

                #region RFID状态
                var rfidEquip = baseBusiness.GetRfidByKey("secondFloorOut");
                if (rfidEquip != null && rfidEquip.IsConnected)
                {
                    rfidEquip.RefreshStatus();
                    Out2FRfidStatus = 1;
                }
                else 
                {
                   Out2FRfidStatus = 2;
                   bool result =  rfidEquip.Connect(rfidEquip.ip, rfidEquip.port);
                    rfidEquip.IsConnected = result;

                }
                #endregion

            }
            catch (Exception ex)
            {
                _logger.LogError($"监听设备状态异常:{ex.Message}");
            }

        }

        /// <summary>
        /// 检查设备状态
        /// </summary>
        private void CheckPlcStatus(PlcAbsractFactory plc, string plcKey, Action<int> setStatus)
        {
            if (plc != null && plc.IsConnected)
            {
                plc.IsConnected = plc.readHeartByAddress("M100");
                setStatus(1);
            }
            else
            {
                setStatus(2);
                PlcConfig? plcConfig = App.ServiceProvider.GetService<AppConfig>().plcConfig.FirstOrDefault(x => x.plcKey == plcKey);
                if (plcConfig != null)
                {
                    bool result = plc.Connect(plcConfig.plcIp, plcConfig.plcPort);
                    plc.IsConnected = result;
                }
            }
        }

        #endregion

        /// <summary>
        ///  窗体控制
        /// </summary>
        /// <param name="obj"></param>
        private void FormControl(object obj)
        {
            try
            {

                string controlType = obj as string;
                switch (controlType)
                {
                  
                    case "DevMonitor":
                        UserContent = devMonitorPage;
                        PageName = "设备监控";
                        break;
                    case "ProdMgmt":
                        UserContent = prodMgmtPage;
                        PageName = "京源环保SCADA";
                        break;
                    case "ManualDelivery":
                        //UserContent = manualDelivery;
                        ManualDeliveryWindow manualDelivery = new ManualDeliveryWindow();
                        manualDelivery.ShowDialog();
                        break;
                    case "ProdStatistics":
                        UserContent = prodStatisticsPage;
                        PageName = "生产统计";
                        break;
                    case "Exit":// 关闭当前窗口
                       var result =  MessageBox.Show("确定要关闭程序吗？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No, MessageBoxOptions.None);
                        if (result== MessageBoxResult.Yes)
                        {
                            _logger.LogWarning("用户手动关闭程序");
                            Application.Current.Shutdown();
                        }
                        break;
                    case "Generate":
                        UserContent = generateControl;
                        break;
                    case "ConfigInfo":
                        string password = Microsoft.VisualBasic.Interaction.InputBox("请输入密码：", "密码验证", "", -1, -1);
                        if (password == debugConfig.ConfigInfoPassWprd) // 检查密码是否正确
                        {
                            UserContent = configInfoPage;
                            PageName = "参数配置";
                        }
                        else if(!string.IsNullOrEmpty(password))
                        {
                            MessageBox.Show("密码错误，请重试！", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                        //UserContent = configInfoPage;
                        //PageName = "参数配置";
                        break;
                    case "RecipeManage":
                        UserContent = recipeManagePage;
                        PageName = "配方管理";
                        break;
                    case "AgvAndTaskPage":
                        UserContent = agvAndTaskMonitorPage;
                        PageName = "AGV监听";
                        break;
                    case "LocationPage":
                        UserContent = locationPage;
                        PageName = "库位信息";
                        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;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("窗体控制逻辑异常", ex);
            }
        }

        /// <summary>
        /// 界面跳转
        /// </summary>
        private void ControlOnClick(object obj)
        {
            try
            {
                string info = obj as string;
                PageName = "京源环保SCADA";
                UserContent = prodMgmtPage;
            }
            catch (Exception ex)
            {
                _logger.LogError("界面跳转逻辑异常", ex);
            }
        }

    }
}
