using CCDCount.DLL;
using CCDCount.DLL.Tools;
using CCDCount.MODEL.CameraClass;
using CCDCount.MODEL.ConfigModel;
using CCDCount.MODEL.SqlDataModel;
using LogClass;
using MvCameraControl;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using System.Xml.Serialization;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;

namespace CCDCountWpf
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        #region 变量与实例
        Uri ShowUri = null;
        List<SaveConfigModel> Configs = null;
        bool IsShow = false;
        SystemMonitor monitor = new SystemMonitor();
        Stopwatch SystemRunTime = new Stopwatch();
        long InitRunTime;
        #endregion

        #region 窗体事件
        /// <summary>
        /// 主窗体构造函数
        /// </summary>
        public MainWindow()
        {
            LOG.log("程序正在加载主界面", 6);
            InitializeComponent();
            LOG.log("正在开启系统运行时间程序", 6);
            //StartSystemRunTime();
            SetupFullScreen();
            LOG.log("绑定界面数据中", 6);
            DataContext = ShowMessageBus.ShowBinding;
            LOG.log("加载配置参数中", 6);
            if (File.Exists(".\\Config\\CCDCountConfig.xml"))
            {
                Configs = XmlStorage.DeserializeFromXml<List<SaveConfigModel>>(".\\Config\\CCDCountConfig.xml");
            }
            LOG.log("初始化引用库", 6);
            SDKSystem.Initialize();
            FaultLog.FaultError += ShowErrorMesPage;
            LOG.log("初始化相机中", 6);
            InitCameraIdentify();
            LOG.log("启动界面更新线程中", 6);
            StartUpdataShowDataThread();
            LOG.log("相机列表显示", 6);
            InitCamComboboxValue();
            LOG.log("初始化PLC参数管理功能", 6);
            InitPlcManger();
            LOG.log("更新数据界面参数展示", 6);
            UpdatePlcPara();
        }


        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            MainPageBtn_Click(null, null);
        }

        /// <summary>
        /// 退出按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExitBtn_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("是否退出程序？", "退出确认", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                this.Close();
            }
            else
            {
                return;
            }
        }

        /// <summary>
        /// 主界面按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainPageBtn_Click(object sender, RoutedEventArgs e)
        {
            ShowUri = new Uri("WpfPage\\MainPage.xaml", UriKind.Relative);
            ShowFrame.Navigate(ShowUri);
        }

        private void SettingBtn_Click(object sender, RoutedEventArgs e)
        {
            ShowUri = new Uri("WpfPage\\SettingPage.xaml", UriKind.Relative);
            ShowFrame.Navigate(ShowUri);
        }

        private void ErrorMessageShowBtn_Click(object sender, RoutedEventArgs e)
        {
            ShowUri = new Uri("WpfPage\\MessagePage.xaml", UriKind.Relative);
            ShowFrame.Navigate(ShowUri);
        }

        private void PlcSettingBtn_Click(object sender, RoutedEventArgs e)
        {
            if(PlcSettingMessageBus.pLCManagement.IsConnect)
            {
                ShowUri = new Uri("WpfPage\\PlcSettingPage.xaml", UriKind.Relative);
                ShowFrame.Navigate(ShowUri);
            }
            else
            {
                var MessageResult = MessageBox.Show("尚未连接PLC，是否重连","重连确认",MessageBoxButton.YesNo);
                if(MessageResult == MessageBoxResult.Yes)
                {
                    InitPlcManger();
                    if (PlcSettingMessageBus.pLCManagement.IsConnect)
                    {
                        UpdatePlcPara(); 
                        ShowUri = new Uri("WpfPage\\PlcSettingPage.xaml", UriKind.Relative);
                        ShowFrame.Navigate(ShowUri);
                    }
                    else
                    {
                        MessageBox.Show("连接PLC失败,请检查PLC状态");
                    }
                }
            }
        }

        private void HistoryDataBtn_Click(object sender, RoutedEventArgs e)
        {
            ShowUri = new Uri("WpfPage\\HistoryDataPage.xaml", UriKind.Relative);
            ShowFrame.Navigate(ShowUri);
        }

        private void UserMessageBtn_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBus.NowLoginUserMessage != null)
            {
                if (!MessageBus.NowLoginUserMessage.IsAdmin)
                {
                    MessageBox.Show("权限不足");
                }
                else
                {
                    ShowUri = new Uri("WpfPage\\UserManagementPage.xaml", UriKind.Relative);
                    ShowFrame.Navigate(ShowUri);
                }
            }
            else
            {
                MessageBox.Show("请先登录");
            }
        }

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            StopSystemRunTime();
            SaveConfig();
            SDKSystem.Finalize();
            if (MessageBus.NowSettingLoadMainThread != null)
            {
                MessageBus.NowSettingLoadMainThread.DisposeCamera();
            }
            StopUpdataShowDataThread();
            FaultLog.FaultError -= ShowErrorMesPage;
            Environment.Exit(0);
        }
        #endregion

        #region 私有方法
        private void InitCameraIdentify()
        {
            if (Configs.Count == 0)
            {
                MessageBox.Show("尚未添加相机，请前往配置页面配置相机");
                return;
            }
            if (MessageBus.NowSettingLoadMainThread != null)
            {
                MessageBus.NowSettingLoadMainThread.StopMianThread();
            }

            MessageBus.NowSettingLoadMainThread = (new MainThreadClass(Configs[0].ShuLiConfigClass, Configs[0].CameraConfig));

            MessageBus.NowSettingLoadMainThread.FormulationName = Configs[0].ConfigName;
            MessageBus.NowSettingLoadMainThread.IsLoadFormulation = Configs[0].IsFormulation;
            //MessageBus.MainThreadS[i].ConnectModbus("127.0.0.1");
            MessageBus.NowSettingLoadMainThread.ConnectModbus("192.168.0.88");
            MessageBus.NowSettingLoadMainThread.LoadCamera();
        }

        /// <summary>
        ///  启动更新显示数据线程
        /// </summary>
        private  void StartUpdataShowDataThread()
        {
            IsShow = true;
            BitmapImage ThumbnailImage1 = null;
            const int targetMsPerFrame = 100; // 20FPS=50ms
            Stopwatch renderSW = new Stopwatch();
            Stopwatch HeartSW = new Stopwatch();
            Task.Run(async () =>
            {
                while (IsShow)
                {
                    renderSW.Restart();
                    await Task.Run(() =>
                    {
                        UpdataShuLiShowData();
                        UpdateMonitorMessage();
                        UpdateFaultLogMessage();
                    });
                    await Application.Current.Dispatcher.InvokeAsync(() =>
                    {
                        if (MessageBus.NowSettingLoadMainThread == null)
                        {
                            LOG.log(string.Format("{0}：当前未加载识别流程", "IdentifyCameraForm-StartShowImageThread"));
                            Thread.Sleep(100);
                            return;
                        }
                        else
                        {
                            MessageBus.NowSettingLoadMainThread.GetShowImage(1000, out Bitmap image1);
                            if (image1 == null)
                            {
                                LOG.log(string.Format("{0}：相机一获取图片为空", "IdentifyCameraForm-StartShowImageThread"));
                                return;
                            }
                            ThumbnailImage1 = ConvertToBitmapImage(image1);
                            ShowMessageBus.ShowBinding.BitmapImage = ThumbnailImage1;
                        }

                        if (MessageBus.NowSettingLoadMainThread != null)
                        {
                            if (MessageBus.NowSettingLoadMainThread.IsDebug)
                            {
                                Bitmap Splicebitmap = MessageBus.NowSettingLoadMainThread.GetCamImageOnce();
                                if (Splicebitmap != null)
                                {
                                    ShowMessageBus.ShowBinding.DebugImage = ConvertToBitmapImage(Splicebitmap);
                                }
                            }
                            else
                            {
                                if (ThumbnailImage1 != null)
                                {
                                    ShowMessageBus.ShowBinding.DebugImage = ThumbnailImage1;
                                }
                            }
                        }
                    });
                    //进行精准20帧控制
                    int elapsed = (int)renderSW.ElapsedMilliseconds;
                    //Console.WriteLine(elapsed);
                    if (elapsed < targetMsPerFrame)
                    {
                        //Console.WriteLine($"主显示线程休眠，休眠时间：{targetMsPerFrame - elapsed}");
                        Thread.Sleep(targetMsPerFrame - elapsed);
                    }
                    //Thread.Sleep(50);
                }
            });
            Task.Run(async () =>
            {
                while (true)
                {
                    HeartSW.Restart();
                    //if (MessageBus.NowSettingLoadMainThread == null) continue;
                    //    if (MessageBus.NowSettingLoadMainThread.CameraRunStatic && MessageBus.NowSettingLoadMainThread.CameraSendMessageStatic)
                    //    {
                    //        PlcSettingMessageBus.pLCManagement.HeartMessage();
                    //    }
                    if(PlcSettingMessageBus.pLCManagement!=null)
                    {
                        PlcSettingMessageBus.pLCManagement.HeartMessage();
                    }
                    HeartSW.Stop();
                    int elapsed = (int)HeartSW.ElapsedMilliseconds;
                    if (elapsed < targetMsPerFrame)
                    {
                        await Task.Delay(500 - elapsed);
                    }
                }
            });
        }

        /// <summary>
        ///  停止更新显示数据线程
        /// </summary>
        private void StopUpdataShowDataThread()
        {
            IsShow = false;
        }

        /// <summary>
        /// 更新数粒显示数据
        /// </summary>
        private void UpdataShuLiShowData()
        {
            if (MessageBus.NowSettingLoadMainThread == null) return;
            if (MessageBus.NowSettingLoadMainThread.ShuLiState)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    ShowMessageBus.ShowBinding.CameraStaticColor = MessageBus.NowSettingLoadMainThread.CameraRunStatic == true
                        ? System.Windows.Media.Brushes.Green : System.Windows.Media.Brushes.Red;
                    ShowMessageBus.ShowBinding.CamRunStatic = MessageBus.NowSettingLoadMainThread.CameraRunStatic == true 
                        ? "运行中" : "未运行";
                });
            }
            else
            {
                Application.Current.Dispatcher.Invoke(() =>
                {

                    ShowMessageBus.ShowBinding.CameraStaticColor = System.Windows.Media.Brushes.Yellow;
                    ShowMessageBus.ShowBinding.CamRunStatic = "视野遮挡";
                });
            }
            ShowMessageBus.ShowBinding.AllActiveNum = MessageBus.NowSettingLoadMainThread.HistoryActiveNum.ToString();
            ShowMessageBus.ShowBinding.AllOkNum = MessageBus.NowSettingLoadMainThread.OkHistoryNum.ToString();
            ShowMessageBus.ShowBinding.AllNgNum = MessageBus.NowSettingLoadMainThread.NgHistoryNum.ToString();
            ShowMessageBus.ShowBinding.ShuLiSpeed = MessageBus.NowSettingLoadMainThread.GetOneSecondActiveNum().ToString();
            PlcSettingMessageBus.pLCManagement.ReadBottingCount(out ushort BottingCount);
            ShowMessageBus.ShowBinding.BottingCountSpeed = PlcSettingMessageBus.pLCManagement.BottingSpeed.ToString();
            ShowMessageBus.ShowBinding.BottingCount = BottingCount;
        }

        /// <summary>
        /// 更新监控信息
        /// </summary>
        private void UpdateMonitorMessage()
        {
            ShowMessageBus.ShowBinding.RamMonitor = monitor.GetAvailableMemory() > 1024 ? $"可用内存: {monitor.GetAvailableMemory() / 1024:0.00}GB" : $"可用内存: {monitor.GetAvailableMemory()}MB";
            ShowMessageBus.ShowBinding.CPUMonitor = $"CPU: {monitor.GetCpuUsage():0.00}%";
        }

        /// <summary>
        /// 更新故障日志信息
        /// </summary>
        private void UpdateFaultLogMessage()
        {
            ShowMessageBus.ShowBinding.ErrMessageShowList = FaultLog.GetAllErrMessage();
        }

        // Bitmap 转 BitmapImage 的辅助方法
        private BitmapImage ConvertToBitmapImage(Bitmap bitmap)
        {
            using (MemoryStream memory = new MemoryStream())
            {
                bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
                memory.Position = 0;
                var bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.DecodePixelWidth = 1200; // 设置目标分辨率宽度
                bitmapImage.DecodePixelHeight = 600; // 保持宽高比
                bitmapImage.StreamSource = memory;
                bitmapImage.EndInit();
                return bitmapImage;
            }
        }

        /// <summary>
        /// 初始化相机选择框
        /// </summary>
        private void InitCamComboboxValue()
        {
            MessageBus.CameraClass.GetCameraList(out List<CameraInfoClass> CameraInfoList);
            if (CameraInfoList.Count > 0)
            {
                ShowMessageBus.ShowBinding.CameraItems.Clear();
                ShowMessageBus.ShowBinding.CameraItems.Add(new CameraCoboxItem() { Name = "请选择相机", SNValue = "" });
                foreach (var item in CameraInfoList)
                {
                    ShowMessageBus.ShowBinding.CameraItems.Add(new CameraCoboxItem()
                    {
                        Name = item.DeviceName + "_" + item.DeviceSN,
                        SNValue = item.DeviceSN
                    });
                }
            }
        }

        /// <summary>
        /// FaultLog的报警回调方法
        /// </summary>
        /// <param name="e"></param>
        private void ShowErrorMesPage(ErrorMesDataEventModelClass e)
        {
            ShowMessageBus.ShowBinding.ShowErrMessage = e.ErrorMesData.Message;
            //MessageBox.Show(e.ErrorMesData.Message);
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        private void SaveConfig()
        {
            List<SaveConfigModel> SaveConfig = new List<SaveConfigModel>();
            if (MessageBus.NowSettingLoadMainThread == null)
            {
                return;
            }
            SaveConfig.Add(new SaveConfigModel()
            {
                CameraConfig = MessageBus.NowSettingLoadMainThread.cameraConfig,
                ShuLiConfigClass = MessageBus.NowSettingLoadMainThread.shuLiConfig,
                IsFormulation = MessageBus.NowSettingLoadMainThread.IsLoadFormulation,
                ConfigName = MessageBus.NowSettingLoadMainThread.FormulationName
            });
            if (!Directory.Exists(".\\Config\\")) Directory.CreateDirectory(".\\Config\\");
            {
                XmlStorage.SerializeToXml(SaveConfig, ".\\Config\\CCDCountConfig.xml");
            }
        }

        /// <summary>
        /// 初始化PLC管理(包括PLC的数据信息更新线程)
        /// </summary>
        public void InitPlcManger()
        {
            //PlcSettingMessageBus.pLCManagement = new PLCManagementClass("127.0.0.1");
            PlcSettingMessageBus.pLCManagement = new PLCManagementClass("192.168.0.88");
        }

        private void UpdatePlcPara()
        {
            var ParaValue = PlcSettingMessageBus.pLCManagement.ReadAllPara();
            if (ParaValue == null) return;
            PlcSettingMessageBus.PlcMessageShowBindage.FillingModel =
                ParaValue.FillingMode;
            PlcSettingMessageBus.PlcMessageShowBindage.BeltsSpeed =
                ParaValue.BeltsSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable1H_FillingSpeed =
                ParaValue.ShakeTable1H_FillingSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable2H_FillingSpeed =
                ParaValue.ShakeTable2H_FillingSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable3H_FillingSpeed =
                ParaValue.ShakeTable3H_FillingSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable1M_FillingSpeed =
                ParaValue.ShakeTable1M_FillingSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable2M_FillingSpeed =
                ParaValue.ShakeTable2M_FillingSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable3M_FillingSpeed =
                ParaValue.ShakeTable3M_FillingSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable1L_FillingSpeed =
                ParaValue.ShakeTable1L_FillingSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable2L_FillingSpeed =
                ParaValue.ShakeTable2L_FillingSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable3L_FillingSpeed =
                ParaValue.ShakeTable3L_FillingSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable1H_CacheSpeed =
                ParaValue.ShakeTable1H_CacheSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable2H_CacheSpeed =
                ParaValue.ShakeTable2H_CacheSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable3H_CacheSpeed =
                ParaValue.ShakeTable3H_CacheSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable1M_CacheSpeed =
                ParaValue.ShakeTable1M_CacheSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable2M_CacheSpeed =
                ParaValue.ShakeTable2M_CacheSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable3M_CacheSpeed =
                ParaValue.ShakeTable3M_CacheSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable1L_CacheSpeed =
                ParaValue.ShakeTable1L_CacheSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable2L_CacheSpeed =
                ParaValue.ShakeTable2L_CacheSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable3L_CacheSpeed =
                ParaValue.ShakeTable3L_CacheSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.FillingH_SpeedRatio =
                ParaValue.FillingH_SpeedRatio;
            PlcSettingMessageBus.PlcMessageShowBindage.FillingM_SpeedRatio =
                ParaValue.FillingM_SpeedRatio;
            PlcSettingMessageBus.PlcMessageShowBindage.FillingL_SpeedRatio =
                ParaValue.FillingL_SpeedRatio;
            PlcSettingMessageBus.PlcMessageShowBindage.CacheH_SpeedRatio =
                ParaValue.CacheH_SpeedRatio;
            PlcSettingMessageBus.PlcMessageShowBindage.CacheM_SpeedRatio =
                ParaValue.CacheM_SpeedRatio;
            PlcSettingMessageBus.PlcMessageShowBindage.CacheL_SpeedRatio =
                ParaValue.CacheL_SpeedRatio;
            PlcSettingMessageBus.PlcMessageShowBindage.ScrewJogSpeed =
                ParaValue.ScrewJogSpeed.ToString();
            PlcSettingMessageBus.PlcMessageShowBindage.InBottleSpeed =
                ParaValue.InBottleSpeed.ToString();
            PlcSettingMessageBus.PlcMessageShowBindage.BottlePosSpeed =
                ParaValue.BottlePosSpeed.ToString();
            PlcSettingMessageBus.PlcMessageShowBindage.BottlePosPosition = 
                ParaValue.BottlePosPosition.ToString();
            PlcSettingMessageBus.PlcMessageShowBindage.FillingValveOpenSpeed =
                ParaValue.FillingValveOpenSpeed.ToString();
            PlcSettingMessageBus.PlcMessageShowBindage.FillingValveOpenPosition =
                ParaValue.FillingValveOpenPosition.ToString();
            PlcSettingMessageBus.PlcMessageShowBindage.FillingValveCloseSpeed =
                ParaValue.FillingValveCloseSpeed.ToString();
            PlcSettingMessageBus.PlcMessageShowBindage.FillingValveClosePosition =
                ParaValue.FillingValveClosePosition.ToString();
            PlcSettingMessageBus.PlcMessageShowBindage.FillingValveCacheSpeed =
                ParaValue.FillingValveCacheSpeed.ToString();
            PlcSettingMessageBus.PlcMessageShowBindage.FillingValveCachePosition =
                ParaValue.FillingValueCachePosition.ToString();
            PlcSettingMessageBus.PlcMessageShowBindage.FillingValveJogSpeed =
                ParaValue.FillingValueJogSpeed.ToString();
            PlcSettingMessageBus.PlcMessageShowBindage.MachineDelayFunneDownTime =
                ParaValue.MachineDelayFunneDownTime;
            PlcSettingMessageBus.PlcMessageShowBindage.MachineDelayFunneUpTime =
                ParaValue.MachineDelayFunneUpTime;
            PlcSettingMessageBus.PlcMessageShowBindage.MachineDelayFillingValveOpenTime =
                ParaValue.MachineDelayFillingValveOpenTime;
            PlcSettingMessageBus.PlcMessageShowBindage.MachineDelayFillingValveCloseTime =
                ParaValue.MachineDelayFillingValveCloseTime;
            PlcSettingMessageBus.PlcMessageShowBindage.MachineDelayInBottleTime =
                ParaValue.MachineDelayInBottleTime;
            PlcSettingMessageBus.PlcMessageShowBindage.BottValueSet =
                ParaValue.BottValueSet;
            PlcSettingMessageBus.PlcMessageShowBindage.ValveDelytime = 
                ParaValue.ValveDelytime;
            PlcSettingMessageBus.PlcMessageShowBindage.CacheShutdownValue =
                ParaValue.CacheShutdownValue;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable1_TestSpeed =
                ParaValue.ShakeTable1_TestSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable2_TestSpeed =
                ParaValue.ShakeTable2_TestSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.ShakeTable3_TestSpeed =
                ParaValue.ShakeTable3_TestSpeed;
            PlcSettingMessageBus.PlcMessageShowBindage.MissingDelaytime =
                ParaValue.MissingDelaytime;
            PlcSettingMessageBus.PlcMessageShowBindage.BottleJamDelaytime =
                ParaValue.BottleJamDelaytime;
            PlcSettingMessageBus.PlcMessageShowBindage.EliminateCylinderDelayTime =
                ParaValue.EliminateCylinderDelayTime;
            PlcSettingMessageBus.PlcMessageShowBindage.EliminateCylinderHoldingTime =
                ParaValue.EliminateCylinderHoldingTime;
        }

        private void StartSystemRunTime()
        {
            string localDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            string systemRunTimePath = Path.Combine(localDataPath, "CCDCount\\SystemRunTime.XML");
            if (File.Exists(systemRunTimePath))
            {
                var systemMessage = XmlStorage.DeserializeFromXml<SystemMessageConfigModel>(systemRunTimePath);
                InitRunTime = systemMessage.SystemRunTime;
                TimeSpan timeSpan = TimeSpan.FromTicks(InitRunTime);
            }
            SystemRunTime.Start();
        }

        private void StopSystemRunTime()
        {
            string localDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            string systemruntimefoundPath = Path.Combine(localDataPath, "CCDCount");
            if (!Directory.Exists(systemruntimefoundPath))
            {
                Directory.CreateDirectory(systemruntimefoundPath);
            }
            string systemRunTimePath = Path.Combine(systemruntimefoundPath, "SystemRunTime.XML");
            SystemRunTime.Stop();
            long ticks = SystemRunTime.ElapsedTicks;
            XmlStorage.SerializeToXml(new SystemMessageConfigModel()
            {
                SystemRunTime = ticks + InitRunTime
            }, systemRunTimePath);
        }

        private void SetupFullScreen()
        {
            // 隐藏标题栏和边框
            this.WindowStyle = WindowStyle.None;

            // 禁止调整大小
            this.ResizeMode = ResizeMode.NoResize;

            // 设置为最顶层窗口
            //this.Topmost = true;

            // 最大化窗口
            this.WindowState = WindowState.Maximized;

            // 隐藏任务栏（可选）
            this.Top = 0;
            this.Left = 0;
            this.Width = SystemParameters.PrimaryScreenWidth;
            this.Height = SystemParameters.PrimaryScreenHeight;
        }

        #endregion

        private void MenuBtn_Click(object sender, RoutedEventArgs e)
        {
            HeardPanel.Visibility = HeardPanel.Visibility == Visibility.Visible?Visibility.Hidden:Visibility.Visible;
        }

        private void KeyBoardBtn_Click(object sender, RoutedEventArgs e)
        {
            OnScreenKeyboard.KeyBoardShow();
        }

        private void PlcOperationBtn_Click(object sender, RoutedEventArgs e)
        {
            if (PlcSettingMessageBus.pLCManagement.IsConnect)
            {
                ShowUri = new Uri("WpfPage\\PlcOperationPage.xaml", UriKind.Relative);
                ShowFrame.Navigate(ShowUri);
            }
            else
            {
                var MessageResult = MessageBox.Show("尚未连接PLC，是否重连", "重连确认", MessageBoxButton.YesNo);
                if (MessageResult == MessageBoxResult.Yes)
                {
                    InitPlcManger();
                    if (PlcSettingMessageBus.pLCManagement.IsConnect)
                    {
                        UpdatePlcPara();
                        ShowUri = new Uri("WpfPage\\PlcOperationPage.xaml", UriKind.Relative);
                        ShowFrame.Navigate(ShowUri);
                    }
                    else
                    {
                        MessageBox.Show("连接PLC失败,请检查PLC状态");
                    }
                }
            }
        }

        private void AuditTrailShowBtn_Click(object sender, RoutedEventArgs e)
        {
            ShowUri = new Uri("WpfPage\\AuditTrailPage.xaml", UriKind.Relative);
            ShowFrame.Navigate(ShowUri);
        }
    }
}
