using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using SlnMesnac.Business;
using SlnMesnac.Business.@base;
using SlnMesnac.Model.domain;
using SlnMesnac.Plc;
using SlnMesnac.WPF.Model;
using SlnMesnac.WPF.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TouchSocket.Core;

namespace SlnMesnac.WPF.Page
{
    /// <summary>
    /// DevMonitorPage.xaml 的交互逻辑
    /// </summary>
    public partial class DevMonitorPage : UserControl
    {
        private BaseBusiness baseBusiness = null;
        private readonly ConfigInfoBusiness _configInfoBusiness;
        PlcAbsractFactory plc = null;
        int MachineSleep = 1000;
        private readonly ILogger<DevMonitorPage> _logger;

        System.Timers.Timer systemRunTimer = new System.Timers.Timer(1000 * 60);
        //系统频率配方
        private RecipeManageCache recipeManageCache = RecipeManageCache.Instance;


        public DevMonitorPage()
        {
            RecipeModeSetWindow.ManualChangeRecipeEvent +=  ManualChangeRecipe;
            _logger = App.ServiceProvider.GetService<ILogger<DevMonitorPage>>();
            _configInfoBusiness = App.ServiceProvider.GetService<ConfigInfoBusiness>();

            baseBusiness = App.ServiceProvider.GetService<BaseBusiness>();
            MachineSleep = Convert.ToInt32(baseBusiness.GetPlcAddressByConfigKey("设备启动间隔"));
            plc = baseBusiness.GetPlcByKey("plc");
            InitializeComponent();
            this.DataContext = new DevMonitorViewModel();
            Init();
            StartMachineLisening();
            StartAdjustRecipe();
        }



        private void Init()
        {
            systemRunTimer.Elapsed += new System.Timers.ElapsedEventHandler(CalculateSystemRunTime);
            systemRunTimer.AutoReset = true;
            systemRunTimer.Enabled = true;
            systemRunTimer.Start();

            List<BaseConfigInfo> configInfos = _configInfoBusiness.GetConfigInfos();

            BagsAmountTxt.Text = configInfos.Where(x => x.ConfigKey == "包装袋余量").FirstOrDefault().ConfigValue;
            // UnpackSet1Txt.Text = configInfos.Where(x => x.ConfigKey == "拆包机翻转机频率设定值").FirstOrDefault().ConfigValue;
            // UnpackSet2Txt.Text = configInfos.Where(x => x.ConfigKey == "拆包机滚筒筛频率设定值").FirstOrDefault().ConfigValue;
            //UnpackSet3Txt.Text = configInfos.Where(x => x.ConfigKey == "拆包机螺旋1频率设定值").FirstOrDefault().ConfigValue;
            //UnpackSet4Txt.Text = configInfos.Where(x => x.ConfigKey == "拆包机螺旋2频率设定值").FirstOrDefault().ConfigValue;
            //  UnpackSet5Txt.Text = configInfos.Where(x => x.ConfigKey == "拆包机废袋机频率设定值").FirstOrDefault().ConfigValue;

            //Speed1Txt.Text = configInfos.Where(x => x.ConfigKey == "螺旋1速度设定值").FirstOrDefault().ConfigValue;
            //Speed2Txt.Text = configInfos.Where(x => x.ConfigKey == "螺旋2速度设定值").FirstOrDefault().ConfigValue;
            // HotSpiralSpeedTxt.Text = configInfos.Where(x => x.ConfigKey == "烘干机螺旋频率设定值").FirstOrDefault().ConfigValue;

            //HotTempTxt.Text = configInfos.Where(x => x.ConfigKey == "烘干机温度设定值").FirstOrDefault().ConfigValue;
        }

        /// <summary>
        /// 计算系统投料后运行时长
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CalculateSystemRunTime(object? sender, ElapsedEventArgs e)
        {
            try
            {
                if (plc != null)
                {
                    bool unPackStatus1 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机系统运行状态"));
                    if (unPackStatus1)
                    {
                        BaseConfigInfo configInfo = _configInfoBusiness.GetConfigInfos().Where(x => x.ConfigKey == "系统运行时长").FirstOrDefault();
                        configInfo.ConfigValue  = (int.Parse(configInfo.ConfigValue) + 1).ToString();
                        _configInfoBusiness.UpdateConfigInfo(configInfo);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"计算系统运行时长异常:{ex.Message}");
            }
        }
        /// <summary>
        /// 设备参数监听
        /// </summary>
        private void StartMachineLisening()
        {
            Task.Run(() =>
            {
                while (true)
                {
                    try
                    {
                        Thread.Sleep(2000);
                        if (plc != null)
                        {
                            RefreshMagNet();
                            RefreshSpiral();
                            RefreshHot();
                            RefreshUnPack();

                            App.Current.Dispatcher.BeginInvoke((Action)(() =>
                           {
                               BagsAmountTxt.Text = _configInfoBusiness.GetConfigInfos().FirstOrDefault(x => x.ConfigKey == "包装袋余量").ConfigValue;
                           }));
                        }
                        else
                        {
                            _logger.LogError($"设备监听启动失败；PLC连接失败!");
                            Thread.Sleep(1000 * 30);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError($"设备参数监听StartMachineLisening()异常:{ex.Message}");
                    }

                }
            });
        }

        #region 监测缓存区重量，动态调整配方频率
        /// <summary>
        /// 开始启动监测缓存区重量，动态调整配方频率
        /// </summary>
        private void StartAdjustRecipe()
        {
            Task.Run(() =>
            {
                Thread.Sleep(1000 * 10);
                while (true)
                {
                    try
                    {
                        float cacheWeigh = plc.readFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("缓存区重量"));
                        recipeManageCache.BufferWeight = cacheWeigh;
                        if (recipeManageCache.RecipeMode == "自动模式")
                        {
                            bool unPackStatus1 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机系统运行状态"));
                            bool signal2 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1状态"));
                            bool signal3 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2状态"));
                            int signal1_1 = plc.readByteByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机螺旋状态"));
                            
                            if (signal1_1 == 1 && signal2 && signal3 && unPackStatus1) // 1.设备都已经启动
                            {
                                // 1.判断缓存区重量是否满足配方要求
                                RecipeManage targetRecipe = null;
                                int result = JudgeCacheWeighIsOk(cacheWeigh, out targetRecipe);
                                switch (result)
                                {
                                    case -1:
                                        // TODO添加报警记录推送 
                                        break;
                                    case 0: break;

                                    case 1:
                                        // 高切低
                                        HighToLowSpeed(targetRecipe);
                                        break;
                                    case 2:
                                        // 低切高
                                        LowToHighSpeed(targetRecipe);
                                        break;
                                    default: break;
                                }


                            }
                        }
                        Thread.Sleep(1000 * 10);

                    }
                    catch (Exception ex)
                    {
                        _logger.LogError($"监测缓存区重量，动态调整配方频率StartAdjustRecipe异常:{ex.Message}");
                    }
                }
            });
        }

        /// <summary>
        /// 判断缓存区重量是否满足配方要求
        /// </summary>
        /// <returns>-1,重量未匹配到目标配方，报警</returns>
        /// <returns>0,无需更改配方</returns>
        /// <returns>1,从高速模版切换到低速模版</returns>
        /// <returns>2,从低速模版切换到高速模版</returns>
        private int JudgeCacheWeighIsOk(float weight,out RecipeManage targetRecipe)
        {
            int result = -1;
            targetRecipe = null;
            try
            {
                foreach (var item in recipeManageCache.recipeManageList)
                {
                    if (item.LowWeight <= weight && weight < item.HightWeight)
                    {
                        // 找到重量对应的配方
                        if (recipeManageCache.useRecipeManage == item)
                        {
                            // 不需要更改配方
                            result = 0;
                        }
                        else if (recipeManageCache.useRecipeManage.LowWeight < item.LowWeight)
                        {
                            //重量变大 从高速模版切换到低速模版
                            result = 1;
                            targetRecipe = item;
                        }
                        else if (recipeManageCache.useRecipeManage.LowWeight > item.LowWeight)
                        {
                            //重量变小 从低速模版切换到高速模版
                            result = 2;
                            targetRecipe = item;
                        }
                    }
                }
              
              return result;
            }catch (Exception ex)
            {
                _logger.LogError("JudgeCacheWeighIsOk异常:" + ex.Message);
                return  result;
            }
        }

        /// <summary>
        /// 螺旋配方从高速切到低速：从前往后：拆包机、烘干、螺旋1，螺旋2
        /// </summary>
        private bool HighToLowSpeed(RecipeManage targetRecipe)
        {

            try
            {
                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机螺旋1频率设定"), targetRecipe.UnpackSpiral1);
                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机螺旋2频率设定"), targetRecipe.UnpackSpiral2);
                Thread.Sleep(int.Parse(recipeManageCache.UnpackToHotTime));
                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机螺旋频率设定"), targetRecipe.DryerSpiral);
                Thread.Sleep(int.Parse(recipeManageCache.HotToSpiralTime));
                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1速度设置"), targetRecipe.Spiral1);
                Thread.Sleep(int.Parse(recipeManageCache.SpiralTwoTime));
                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2速度设置"), targetRecipe.Spiral2);
                //更新配方缓存里的当前使用模版
                recipeManageCache.RecipeName = targetRecipe.RecipeName;
                return true;
            }catch (Exception ex)
            {
                _logger.LogError("HighToLowSpeed异常:" + ex.Message);
                return false;
            }
        }


        /// <summary>
        /// 螺旋配方从低速切到高速：从后往前：螺旋2、螺旋1、烘干、拆包机
        /// </summary>
        private bool LowToHighSpeed(RecipeManage targetRecipe)
        {

            try
            {
                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2速度设置"), targetRecipe.Spiral2);
                Thread.Sleep(int.Parse(recipeManageCache.SpiralTwoTime));
                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1速度设置"), targetRecipe.Spiral1);
                Thread.Sleep(int.Parse(recipeManageCache.HotToSpiralTime));
                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机螺旋频率设定"), targetRecipe.DryerSpiral);
                Thread.Sleep(int.Parse(recipeManageCache.UnpackToHotTime));
                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机螺旋1频率设定"), targetRecipe.UnpackSpiral1);
                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机螺旋2频率设定"), targetRecipe.UnpackSpiral2); 
                //更新配方缓存里的当前使用模版
                recipeManageCache.RecipeName = targetRecipe.RecipeName;
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError("LowToHighSpeed异常:" + ex.Message);
                return false;
            }
        }


        private async Task<bool> ManualChangeRecipe(RecipeManage targetRecipet)
        {
            bool unPackStatus1 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机系统运行状态"));
            bool signal2 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1状态"));
            bool signal3 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2状态"));
            int signal1_1 = plc.readByteByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机螺旋状态"));

            if (signal1_1 == 1 && signal2 && signal3 && unPackStatus1) // 1.设备都已经启动
            {
                if(recipeManageCache.useRecipeManage.RecipeName == targetRecipet.RecipeName)
                {
                    recipeManageCache.RecipeMode = "手动模式";
                    return true;
                }else if (recipeManageCache.useRecipeManage.LowWeight < targetRecipet.LowWeight)
                {//高速切低速
                    bool result = await Task.Run(() =>
                    {
                        return HighToLowSpeed(targetRecipet);
                    });
                    if (result)
                    {
                        recipeManageCache.RecipeMode = "手动模式";
                    }
                    return result;
                }
                else if (recipeManageCache.useRecipeManage.LowWeight > targetRecipet.LowWeight)
                {
                    bool result = await Task.Run(() =>
                    {
                        return LowToHighSpeed(targetRecipet);
                    });
                    if (result)
                    {
                        recipeManageCache.RecipeMode = "手动模式";
                    }
                    return result;
                }
                else
                {
                    return false;
                }

            }
            else
            {
                return false;
            }
        }

        #endregion




        #region 设备启动、停止

        /// <summary>
        /// 发送脉冲信号方法封装
        /// </summary>
        /// <param name="addressKey">plc地址对应的key</param>

        private void SendPulseSignal(string addressKey)
        {
            int PulseSleep = Convert.ToInt32(baseBusiness.GetPlcAddressByConfigKey("脉冲间隔"));
            plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey($"{addressKey}"), true);
            Thread.Sleep(PulseSleep);
            plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey($"{addressKey}"), false);
        }

        /// <summary>
        /// 一键启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartButton_Click(object sender, RoutedEventArgs e)
        {

            var result = MessageBox.Show("是否确认启动？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Information);
            if (result == MessageBoxResult.Yes)
            {
                try
                {

                    if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机MES允许远程")) == false)
                    {
                        MessageBox.Show("拆包机MES允许远程，未切换远程");
                        return;
                    }
                    if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机MES允许远程")) == false)
                    {
                        MessageBox.Show("磁选机MES允许远程，未切换远程");
                        return;
                    }
                    if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1MES允许远程")) == false)
                    {
                        MessageBox.Show("螺旋1MES允许远程，未切换远程");
                        return;
                    }
                    if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2MES允许远程")) == false)
                    {
                        MessageBox.Show("螺旋2MES允许远程，未切换远程");
                        return;
                    }

                    //StartButton.IsEnabled = false;
                    //StopButton.IsEnabled = true;
                    //StopUrgentButton.IsEnabled = true;
                    Task.Run(() =>
                    {
                        plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机远程急停"), false);
                        plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机远程停止"), false);

                        #region 按顺序依次启动设备

                        //1.螺旋2
                        bool Spiral2Status = StartSpiral2();
                        if (!Spiral2Status) return;

                        //2.磁选机
                        bool MagNetStatus = StartMagNet();
                        if (!MagNetStatus) return;

                        //3.螺旋1
                        bool Spiral1Status = StartSpiral1();
                        if (!MagNetStatus) return;

                        //4.烘干机:烘干螺旋、烘干风机、烘干燃烧

                        bool DryerStatus1 = StartDryerMagNet();
                        if (!DryerStatus1) return;
                        bool DryerStatus2 = StartDryerFan();
                        if (!DryerStatus2) return;
                        bool DryerStatus3 = StartDryerHot();
                        if (!DryerStatus3) return;

                        //5.拆包机
                        bool unpackStatus = StartUnPack();
                        #endregion
                        if (unpackStatus)
                        {
                            MessageBoxAndLog("一键启动所有机器成功!");
                        }

                    });
                }
                catch (Exception ex)
                {
                    _logger.LogError($"一键启动异常:{ex.Message}");
                }
                finally
                {

                }
            }

        }


        /// <summary>
        /// 一键停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StopButton_Click(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show("是否确认停止？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    String address = baseBusiness.GetPlcAddressByConfigKey("拆包机MES允许远程");

                    #region 依次按序停止
                    Task.Run(() =>
                    {
                        plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机远程启动"), false);
                        SendPulseSignal("拆包机远程停止");
                        Thread.Sleep(MachineSleep);
                        bool unPackStatus1 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机系统运行状态"));
                        if (unPackStatus1)
                        {
                            MessageBox.Show("一键停止失败,拆包机未停止，请先检查原因");
                            return;
                        }

                        #region 烘干机
                        SendPulseSignal("烘干机螺旋停止");
                        Thread.Sleep(MachineSleep);
                        SendPulseSignal("烘干机燃烧停止");
                        Thread.Sleep(MachineSleep);
                        SendPulseSignal("烘干机风机停止");
                        #endregion
                        plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1启动"), false);
                        Thread.Sleep(MachineSleep);
                        SendPulseSignal("磁选机一键停止");
                        Thread.Sleep(MachineSleep);
                        plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2启动"), false);

                        MessageBoxAndLog("一键停止所有机器成功!");
                    });
                    #endregion
                    //StopButton.IsEnabled = false;
                    //StopUrgentButton.IsEnabled = false;
                    //StartButton.IsEnabled = true;
                }
                catch (Exception ex)
                {
                    _logger.LogError($"一键停止:{ex.Message}");
                }
            }
        }

        /// <summary>
        /// 急停
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StopUrgentButton_Click(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show("是否确认急停？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    if (StopUrgentButton.Content.ToString() == "急停")
                    {
                        //StopButton.IsEnabled = false;
                        //StopUrgentButton.Content = "复位";

                        SendPulseSignal("拆包机远程急停");

                    }
                    else if (StopUrgentButton.Content.ToString() == "复位")
                    {
                        //StopButton.IsEnabled = true;
                        //StopUrgentButton.Content = "急停";
                        plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机远程急停"), false);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError($"拆包机远程急停:{ex.Message}");
                }
            }
        }

        #region 拆包机
        /// <summary>
        /// 拆包机启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartUnPackButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机MES允许远程")) == false)
                {
                    MessageBox.Show("拆包机MES允许远程，未切换远程");
                    return;
                }

                Task.Run(() =>
                {
                    plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机远程急停"), false);
                    plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机远程停止"), false);

                    SendPulseSignal("拆包机远程启动");

                    //频率设定
                    // plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机翻转机频率设定"), int.Parse(baseBusiness.GetPlcAddressByConfigKey("拆包机翻转机频率设定值")));
                    //   plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机滚筒筛频率设定"), int.Parse(baseBusiness.GetPlcAddressByConfigKey("拆包机滚筒筛频率设定值")));
                    plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机螺旋1频率设定"), recipeManageCache.useRecipeManage.UnpackSpiral1);
                    plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机螺旋2频率设定"), recipeManageCache.useRecipeManage.UnpackSpiral2);
                    //      plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机废袋机频率设定"), int.Parse(baseBusiness.GetPlcAddressByConfigKey("拆包机废袋机频率设定值")));


                });
                //StartUnPackButton.IsEnabled = false;
                //StopUnPackButton.IsEnabled = true;
            }
            catch (Exception ex)
            {
                _logger.LogError($"拆包机远程启动:{ex.Message}");
            }

        }

        /// <summary>
        /// 拆包机停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StopUnPackButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机MES允许远程")) == false)
                {
                    MessageBox.Show("拆包机MES允许远程，未切换远程");
                    return;
                }

                Task.Run(() =>
                {

                    plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机远程启动"), false);

                    SendPulseSignal("拆包机远程停止");

                });
                //StartUnPackButton.IsEnabled = true;
                //StopUnPackButton.IsEnabled = false;
            }
            catch (Exception ex)
            {
                _logger.LogError($"拆包机停止:{ex.Message}");
            }
        }
        #endregion


        #region 磁选机
        /// <summary>
        /// 磁选启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartMagNetButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机MES允许远程")) == false)
                {
                    MessageBox.Show("磁选机MES允许远程，未切换远程");
                    return;
                }
                Task.Run(() =>
                {
                    SendPulseSignal("磁选机一键启动");
                });
            }
            catch (Exception ex)
            {
                _logger.LogError($"磁选启动:{ex.Message}");
            }

        }

        /// <summary>
        /// 磁选停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StopMagNetButton_Click(object sender, RoutedEventArgs e)
        {
            StartMagNet();
        }

        #endregion

        #region 螺旋机
        /// <summary>
        /// 螺旋1启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartSpiral1Button_Click(object sender, RoutedEventArgs e)
        {
            StartSpiral1();

        }


        /// <summary>
        /// 螺旋2启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartSpiral2Button_Click(object sender, RoutedEventArgs e)
        {
            StartSpiral2();
        }

        /// <summary>
        /// 螺旋1停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StopSpiral1Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1MES允许远程")) == false)
                {
                    MessageBox.Show("螺旋1MES允许远程，未切换远程");
                    return;
                }
                plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1启动"), false);
            }
            catch (Exception ex)
            {
                _logger.LogError($"螺旋1停止:{ex.Message}");
            }
        }

        /// <summary>
        /// 螺旋2停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StopSpiral2Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2MES允许远程")) == false)
                {
                    MessageBox.Show("螺旋2MES允许远程，未切换远程");
                    return;
                }
                plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2启动"), false);
            }
            catch (Exception ex)
            {
                _logger.LogError($"螺旋2停止:{ex.Message}");
            }
        }

        #endregion


        /// <summary>
        /// 启动烘干机螺旋1
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartDryerSpiralButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StartDryerMagNet();
            }
            catch (Exception ex)
            {
                _logger.LogError($"烘干机螺旋启动异常:{ex.Message}");
            }
        }

        /// <summary>
        /// 启动烘干机风机2
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartDryerFanButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Task.Run(() =>
                {
                    SendPulseSignal("烘干机风机启动");
                });

            }
            catch (Exception ex)
            {
                _logger.LogError($"烘干机风机启动:{ex.Message}");
            }

        }

        /// <summary>
        /// 启动烘干机燃烧3
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartDryerHotButton_Click(object sender, RoutedEventArgs e)
        {
            StartDryerHot();
        }

        /// <summary>
        /// 停止烘干机螺旋
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StopDryerSpiralButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Task.Run(() =>
                {
                    SendPulseSignal("烘干机螺旋停止");
                });

            }
            catch (Exception ex)
            {
                _logger.LogError($"烘干机螺旋停止:{ex.Message}");
            }
        }


        /// <summary>
        /// 停止烘干机燃烧
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StopDryerHotButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Task.Run(() =>
                {
                    SendPulseSignal("烘干机燃烧停止");
                });

            }
            catch (Exception ex)
            {
                _logger.LogError($"烘干机燃烧停止:{ex.Message}");
            }
        }

        /// <summary>
        /// 停止烘干机风机
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StopDryerFanButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Task.Run(() =>
                {
                    SendPulseSignal("烘干机风机停止");
                });

            }
            catch (Exception ex)
            {
                _logger.LogError($"烘干机风机停止:{ex.Message}");
            }
        }


        /// <summary>
        /// 启动螺旋2
        /// </summary>
        private bool StartSpiral2()
        {
            bool result = false;
            try
            {

                if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2MES允许远程")) == false)
                {
                    MessageBox.Show("螺旋2MES允许远程，未切换远程");
                    result = false;
                }
                else
                {

                    plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2启动"), true);
                    plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2速度设置"), recipeManageCache.useRecipeManage.Spiral2);
                    Thread.Sleep(MachineSleep);
                    result = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2启动"));
                }

            }
            catch (Exception ex)
            {
                MessageBoxAndLog($"螺旋2启动异常:{ex.Message}", true);
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 启动磁选
        /// </summary>
        private bool StartMagNet()
        {

            try
            {
                if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机MES允许远程")) == false)
                {
                    MessageBox.Show("磁选机MES允许远程，未切换远程");
                    return false;
                }
                #region 启动磁选机 / 前提:check螺旋2启动及速度是否达标
                int value2 = recipeManageCache.useRecipeManage.Spiral2;
                bool startFlag = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2启动"));
                int speed2 = plc.readInt16ByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2速度反馈"));
                if (!startFlag)
                {
                    MessageBox.Show($"前提条件螺旋2未成功启动,请检查后重新启动");
                    return false;
                }
                if (speed2 < value2 * 100 * 0.8)
                {
                    plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2启动"), false);
                    MessageBox.Show($"前提条件螺旋2速度{speed2}未达到设定值{value2}的下限阈值80%,请检查后重新启动");
                    return false;
                }
                SendPulseSignal("磁选机一键启动");
                Thread.Sleep(MachineSleep);
                #endregion
                bool flag1 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机磁选启动"));
                bool flag2 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机震动启动"));
                if (flag1 && flag2)
                {
                    return true;
                }
                else
                {
                    MessageBoxAndLog("磁选机启动失败，请检查后设备状态后重新尝试", true);
                    return false;
                }

            }
            catch (Exception ex)
            {
                MessageBoxAndLog($"磁选机启动异常:{ex.Message}", true);
                return false;
            }
        }

        /// <summary>
        /// 启动螺旋1
        /// </summary>
        private bool StartSpiral1()
        {
            bool result = false;
            try
            {
                if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1MES允许远程")) == false)
                {
                    MessageBox.Show("螺旋1MES允许远程，未切换远程");
                    return false;
                }
                bool flag1 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机磁选启动"));
                bool flag2 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机震动启动"));
                if (!flag1 || !flag2)
                {
                    MessageBoxAndLog("前提条件磁选机未启动，请先检查设备状态再启动", true);
                    return false;
                }


                plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1启动"), true);
                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1速度设置"), recipeManageCache.useRecipeManage.Spiral1);
                Thread.Sleep(MachineSleep);
                result = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1启动"));

            }
            catch (Exception ex)
            {
                MessageBoxAndLog($"螺旋1启动异常:{ex.Message}", true);
                result = false;
            }
            return result;
        }


        #region 烘干机
        /// <summary>
        /// 烘干机螺旋启动/前提：check:螺旋1启动且速度达到值
        /// </summary>
        private bool StartDryerMagNet()
        {
            bool result = false;
            try
            {
                int value1 = recipeManageCache.useRecipeManage.Spiral1;
                bool startFlag = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1启动"));
                int speed1 = plc.readInt16ByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1速度反馈"));
                if (!startFlag)
                {
                    MessageBox.Show($"烘干机螺旋启动失败:前提条件螺旋1未成功启动,请检查后重新启动");
                    return false;
                }
                if (speed1 < value1 * 100 * 0.8)
                {
                    // plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2启动"), false);
                    MessageBox.Show($"烘干机螺旋启动失败:前提条件螺旋1速度{speed1}未达到设定值{value1}的下限阈值80%,请检查后重新启动");
                    return false;
                }
                int value = int.Parse(baseBusiness.GetPlcAddressByConfigKey("烘干机螺旋频率设定值"));
                SendPulseSignal("烘干机螺旋启动");
                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机螺旋频率设定"), recipeManageCache.useRecipeManage.DryerSpiral);
                Thread.Sleep(MachineSleep / 2);
                return true;
            }
            catch (Exception ex)
            {
                MessageBoxAndLog($"烘干机螺旋启动异常:{ex.Message}", true);
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 烘干机风机启动/前提：check:烘干机螺旋启动
        /// </summary>
        private bool StartDryerFan()
        {
            bool result = false;
            try
            {

                bool startFlag = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机反馈传动启动"));
                if (!startFlag)
                {
                    MessageBox.Show($"烘干机风机启动失败:前提条件烘干机螺旋未成功启动,请检查后重新启动");
                    return false;
                }
                SendPulseSignal("烘干机风机启动");
                Thread.Sleep(MachineSleep);
                return true;
            }
            catch (Exception ex)
            {
                MessageBoxAndLog($"烘干机风机启动异常:{ex.Message}", true);
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 烘干机燃烧启动/前提：check:烘干机风机启动
        /// </summary>
        private bool StartDryerHot()
        {
            bool result = false;
            try
            {
                bool startFlag = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机反馈风机启动"));
                if (!startFlag)
                {
                    MessageBox.Show($"烘干机燃烧启动失败:前提条件烘干机风机未成功启动,请检查后重新启动");
                    return false;
                }
                int value = int.Parse(baseBusiness.GetPlcAddressByConfigKey("烘干机温度设定值"));
                SendPulseSignal("烘干机燃烧启动");
                //   plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机温度设定"), value);
                Thread.Sleep(MachineSleep);
                return true;
            }
            catch (Exception ex)
            {
                MessageBoxAndLog($"烘干机燃烧启动异常:{ex.Message}", true);
                result = false;
            }
            return result;
        }

        #endregion


        /// <summary>
        /// 拆包机启动/前提：check:燃烧机启动
        /// </summary>
        private bool StartUnPack()
        {
            bool result = false;
            try
            {
                bool startFlag = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机反馈燃烧启动"));
                if (!startFlag)
                {
                    MessageBox.Show($"拆包机启动失败:前提条件烘干机燃烧未成功启动,请检查后重新启动");
                    return false;
                }

                plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机远程急停"), false);
                plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机远程停止"), false);
                SendPulseSignal("拆包机远程启动");

                //频率设定
                // plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机翻转机频率设定"), int.Parse(baseBusiness.GetPlcAddressByConfigKey("拆包机翻转机频率设定值")));
                // plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机滚筒筛频率设定"), int.Parse(baseBusiness.GetPlcAddressByConfigKey("拆包机滚筒筛频率设定值")));
                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机螺旋1频率设定"), recipeManageCache.useRecipeManage.UnpackSpiral1);
                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机螺旋2频率设定"), recipeManageCache.useRecipeManage.UnpackSpiral2);
                //   plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机废袋机频率设定"), int.Parse(baseBusiness.GetPlcAddressByConfigKey("拆包机废袋机频率设定值")));


                Thread.Sleep(MachineSleep);
                // return plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机运行状态系统"));
                return true;

            }
            catch (Exception ex)
            {
                MessageBoxAndLog($"拆包机启动异常:{ex.Message}", true);
                result = false;
            }
            return result;
        }


        #endregion


        #region 设备参数监控

        /// <summary>
        /// 拆包机参数监控
        /// </summary>
        private async void RefreshUnPack()
        {
            try
            {
                bool unPackStatus0 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机MES允许远程"));
                bool unPackStatus1 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机系统运行状态"));

                bool unPackStatus2 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("设备叫料"));
                bool unPackStatus3 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("物料到位"));
                bool unPackStatus4 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("设备投料"));
                bool unPackStatus5 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机请求移走空托盘"));

                bool unPackStatus7 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机连接状态"));
                bool unPackStatus8 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机堵料停螺旋"));

                float unPackStatus9 = plc.readFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机翻转机频率反馈"));
                float unPackStatus10 = plc.readFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机滚筒筛频率反馈"));
                float unPackStatus11 = plc.readFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机螺旋1频率反馈"));
                float unPackStatus12 = plc.readFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机螺旋2频率反馈"));
                float unPackStatus13 = plc.readFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机废袋机频率反馈"));


                await App.Current.Dispatcher.BeginInvoke((Action)(() =>
                {
                    UnpackStatus0.Fill = unPackStatus0 ? Brushes.Green : Brushes.Red;
                    UnpackStatus1.Fill = unPackStatus1 ? Brushes.Green : Brushes.Red;

                    UnpackStatus2.Text = unPackStatus2.ToString();
                    UnpackStatus3.Text = unPackStatus3.ToString();
                    UnpackStatus4.Text = unPackStatus4.ToString();
                    UnpackStatus5.Text = unPackStatus5.ToString();

                    UnpackStatus7.Fill = unPackStatus7 ? Brushes.Green : Brushes.Red;
                    UnpackStatus8.Fill = unPackStatus8 ? Brushes.Red : Brushes.Green;

                    UnpackStatus9.Text = unPackStatus9.ToString("F2");
                    UnpackStatus10.Text = unPackStatus10.ToString("F2");
                    UnpackStatus11.Text = unPackStatus11.ToString("F2");
                    UnpackStatus12.Text = unPackStatus12.ToString("F2");
                    UnpackStatus13.Text = unPackStatus13.ToString("F2");


                }));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }

        }



        /// <summary>
        /// 磁选机参数监控
        /// </summary>
        private async void RefreshMagNet()
        {
            try
            {
                bool signal0 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机震动启动"));
                bool signal1 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机磁选启动"));
                bool signal2 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机MES允许远程"));
                bool signal3 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机设备故障反馈"));
                await App.Current.Dispatcher.BeginInvoke((Action)(() =>
                {
                    MagNetStatus1.Fill = signal0 ? Brushes.Green : Brushes.Red;
                    MagNetStatus2.Fill = signal1 ? Brushes.Green : Brushes.Red;
                    MagNetStatus3.Fill = signal2 ? Brushes.Green : Brushes.Red;
                    MagNetStatus4.Fill = signal3 ? Brushes.Red : Brushes.Green;

                }));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }

        }

        /// <summary>
        /// 螺旋机参数监控
        /// </summary>
        private async void RefreshSpiral()
        {
            try
            {
                bool signal0 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1MES允许远程"));
                bool signal1 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2MES允许远程"));
                bool signal2 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1状态"));
                bool signal3 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2状态"));

                bool signal4 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1变频器状态"));
                bool signal5 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2变频器状态"));

                double speed1 = plc.readInt16ByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1速度反馈")) / 100;
                double speed2 = plc.readInt16ByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2速度反馈")) / 100;

                // 螺旋速度预设值
                int speed1Set = int.Parse(baseBusiness.GetPlcAddressByConfigKey("螺旋1速度设定值"));
                int speed2Set = int.Parse(baseBusiness.GetPlcAddressByConfigKey("螺旋2速度设定值"));

                await App.Current.Dispatcher.BeginInvoke((Action)(() =>
                {
                    SpiralSignal0.Fill = signal0 ? Brushes.Green : Brushes.Red;
                    SpiralSignal1.Fill = signal1 ? Brushes.Green : Brushes.Red;
                    SpiralSignal2.Fill = signal2 ? Brushes.Green : Brushes.Red;
                    SpiralSignal3.Fill = signal3 ? Brushes.Green : Brushes.Red;
                    //变频器状态  0正常1故障
                    SpiralSignal4.Fill = signal4 ? Brushes.Red : Brushes.Green;
                    SpiralSignal5.Fill = signal5 ? Brushes.Red : Brushes.Green;
                    //螺旋1 速度低于80%预警
                    SpiralSignal6.Fill = speed1 < speed1Set * 0.8 ? Brushes.Red : Brushes.Green;
                    SpiralSignal6_Value.Text = speed1.ToString();
                    //螺旋2 速度低于80%预警
                    SpiralSignal7.Fill = speed2 < speed2Set * 0.8 ? Brushes.Red : Brushes.Green;
                    SpiralSignal7_Value.Text = speed2.ToString();

                }));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }

        }



        #region 螺旋机参数监控
        /// <summary>
        /// 烘干机参数监控
        /// </summary>
        private async void RefreshHot()
        {
            try
            {
                int signal1_1 = plc.readByteByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机螺旋状态"));
                int signal2_1 = plc.readByteByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机风机状态"));
                int signal3_1 = plc.readByteByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机燃烧机状态"));


                bool signal1_2 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机反馈传动启动"));
                bool signal2_2 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机反馈风机启动"));
                bool signal3_2 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机反馈燃烧启动"));

                bool signal4_1 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机燃烧机运行"));
                bool signal14_2 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机存在报警"));

                int signal8 = plc.readInt16ByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机烘干温度"));
                int signal9 = plc.readInt16ByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机加热温度"));
                int signal10 = plc.readInt16ByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机出气温度"));
                int signal11 = plc.readInt16ByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机输出百分比"));

                bool signal7_1 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机堵料报警"));
                int signal7_2 = plc.readByteByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机报警"));


                await App.Current.Dispatcher.BeginInvoke((Action)(() =>
                {
                    HotSignal1_1.Fill = signal1_1 == 1 ? Brushes.Green : Brushes.Red;
                    HotSignal1_1_Value.Text = ChangeHotStatus(signal1_1);
                    HotSignal2_1.Fill = signal2_1 == 1 ? Brushes.Green : Brushes.Red;
                    HotSignal2_1_Value.Text = ChangeHotStatus(signal2_1);
                    HotSignal3_1.Fill = signal3_1 == 1 ? Brushes.Green : Brushes.Red;
                    HotSignal3_1_Value.Text = ChangeHotStatus(signal3_1);

                    HotSignal1_2.Fill = signal1_2 ? Brushes.Green : Brushes.Red;
                    HotSignal2_2.Fill = signal2_2 ? Brushes.Green : Brushes.Red;
                    HotSignal3_2.Fill = signal3_2 ? Brushes.Green : Brushes.Red;

                    HotSignal4_1.Fill = signal4_1 ? Brushes.Green : Brushes.Red;
                    HotSignal4_2.Fill = signal14_2 ? Brushes.Red : Brushes.Green;


                    HotSignal5_1_Value.Text = ((double)signal8 / 10).ToString();
                    HotSignal5_2_Value.Text = ((double)signal9 / 10).ToString();
                    HotSignal6_1_Value.Text = ((double)signal10 / 10).ToString();
                    HotSignal6_2_Value.Text = signal11.ToString();

                    HotSignal7_1.Fill = signal7_1 ? Brushes.Red : Brushes.Green;
                    HotSignal7_2.Fill = signal7_2 == 0 ? Brushes.Green : Brushes.Red;
                    HotSignal7_2_Value.Text = ChangeHotWarn(signal7_2);


                }));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }

        }

        private string ChangeHotStatus(int status)
        {
            switch (status)
            {
                case 0: return "未知";
                case 1: return "运行";
                case 2: return "停止";
                case 3: return "故障";
                default: return "未知";
            }
        }
        private string ChangeHotWarn(int status)
        {

            switch (status)
            {
                case 0: return "正常"; break;
                case 1: return "风机故障"; break;
                case 2: return "燃烧机故障"; break;
                case 4: return "传动故障"; break;
                case 8: return "超温保护"; break;
                case 16: return "烘干温度超温"; break;
                case 32: return "温控模块通讯超时"; break;
                default: return "未知"; break;

            }

        }
        #endregion



        #endregion


        private void MessageBoxAndLog(string message, bool isError = false)
        {
            if (isError)
            {
                _logger.LogError(message);
            }
            else
            {
                _logger.LogInformation(message);
            }
            MessageBox.Show(message);
        }


        private void AmountChangeButton_Click(object sender, RoutedEventArgs e)
        {
            BagsAmountSetWindow window = new BagsAmountSetWindow();
            window.ShowDialog();
        }



        #region  设备管理界面螺旋频率设定--暂未启用

        ///// <summary>
        ///// 螺旋速度设定
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void SpiralSpeed_Click(object sender, RoutedEventArgs e)
        //{

        //    try
        //    {
        //        bool isValidSpeed1 = int.TryParse(Speed1Txt.Text, out int speed1);
        //        bool isValidSpeed2 = int.TryParse(Speed2Txt.Text, out int speed2);

        //        // 校验输入的整数是否在0到50之间且大于0
        //        if (isValidSpeed1 && isValidSpeed2 && speed1 > 0 && speed1 <= 50 && speed2 > 0 && speed2 <= 50)
        //        {
        //            if (speed1 > speed2)
        //            {
        //                MessageBox.Show("螺旋1速度不能大于螺旋2速度");
        //                return;
        //            }
        //            var result = MessageBox.Show("是否确认更改？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Information);
        //            if (result == MessageBoxResult.Yes)
        //            {
        //                List<BaseConfigInfo> configInfos = _configInfoBusiness.GetConfigInfos();
        //                BaseConfigInfo configInfo1 = configInfos.Where(x => x.ConfigKey == "螺旋1速度设定值").FirstOrDefault();
        //                BaseConfigInfo configInfo2 = configInfos.Where(x => x.ConfigKey == "螺旋2速度设定值").FirstOrDefault();

        //                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1速度设置"), speed1);
        //                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2速度设置"), speed2);

        //                configInfo1.ConfigValue = Speed1Txt.Text;
        //                configInfo2.ConfigValue = Speed2Txt.Text;
        //                _configInfoBusiness.UpdateConfigInfo(configInfo1);
        //                _configInfoBusiness.UpdateConfigInfo(configInfo2);
        //            }
        //        }
        //        else
        //        {
        //            MessageBox.Show("请输入0到50之间的正整数！");
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        _logger.LogError(ex.Message);
        //    }
        //}


        ///// <summary>
        ///// 烘干机螺旋频率设定
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void HotSpiralSpeedSet_Click(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        bool isValidSpeed1 = int.TryParse(HotSpiralSpeedTxt.Text, out int speed1);

        //        // 校验输入的整数是否在0到50之间且大于0
        //        if (isValidSpeed1 && speed1 > 0 && speed1 <= 50)
        //        {
        //            var result = MessageBox.Show("是否确认更改？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Information);
        //            if (result == MessageBoxResult.Yes)
        //            {
        //                List<BaseConfigInfo> configInfos = _configInfoBusiness.GetConfigInfos();
        //                BaseConfigInfo configInfo = configInfos.Where(x => x.ConfigKey == "烘干机螺旋频率设定值").FirstOrDefault();

        //                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机螺旋频率设定"), speed1);

        //                configInfo.ConfigValue = HotSpiralSpeedTxt.Text;

        //                _configInfoBusiness.UpdateConfigInfo(configInfo);

        //            }
        //        }
        //        else
        //        {
        //            MessageBox.Show("请输入0到50之间的正整数！");
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        _logger.LogError(ex.Message);
        //    }
        //}

        //private void UnpackSetButton_Click(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //       // bool isValidSpeed1 = int.TryParse(UnpackSet1Txt.Text, out int speed1) && speed1 >= 0 && speed1 <= 50;
        //      //  bool isValidSpeed2 = int.TryParse(UnpackSet2Txt.Text, out int speed2) && speed2 >= 0 && speed2 <= 50;
        //        bool isValidSpeed3 = int.TryParse(UnpackSet3Txt.Text, out int speed3) && speed3 >= 0 && speed3 <= 50;
        //        bool isValidSpeed4 = int.TryParse(UnpackSet4Txt.Text, out int speed4) && speed4 >= 0 && speed4 <= 50;
        //      //  bool isValidSpeed5 = int.TryParse(UnpackSet5Txt.Text, out int speed5) && speed5 >= 0 && speed5 <= 50;


        //        if (  isValidSpeed3 && isValidSpeed4 )
        //        {

        //            var result = MessageBox.Show("是否确认更改？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Information);
        //            if (result == MessageBoxResult.Yes)
        //            {


        //                //频率设定
        //               // plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机翻转机频率设定"), speed1);
        //               // plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机滚筒筛频率设定"), speed2);
        //                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机螺旋1频率设定"), speed3);
        //                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机螺旋2频率设定"), speed4);
        //             //   plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机废袋机频率设定"), speed5);

        //                List<BaseConfigInfo> configInfos = _configInfoBusiness.GetConfigInfos();
        //              //  BaseConfigInfo configInfo1 = configInfos.Where(x => x.ConfigKey == "拆包机翻转机频率设定值").FirstOrDefault();
        //            //    BaseConfigInfo configInfo2 = configInfos.Where(x => x.ConfigKey == "拆包机滚筒筛频率设定值").FirstOrDefault();
        //                BaseConfigInfo configInfo3 = configInfos.Where(x => x.ConfigKey == "拆包机螺旋1频率设定值").FirstOrDefault();
        //                BaseConfigInfo configInfo4 = configInfos.Where(x => x.ConfigKey == "拆包机螺旋2频率设定值").FirstOrDefault();
        //            //    BaseConfigInfo configInfo5 = configInfos.Where(x => x.ConfigKey == "拆包机废袋机频率设定值").FirstOrDefault();
        //             //   configInfo1.ConfigValue = UnpackSet1Txt.Text;
        //              //  configInfo2.ConfigValue = UnpackSet2Txt.Text;
        //                configInfo3.ConfigValue = UnpackSet3Txt.Text;
        //                configInfo4.ConfigValue = UnpackSet4Txt.Text;
        //              //  configInfo5.ConfigValue = UnpackSet5Txt.Text;
        //             //   _configInfoBusiness.UpdateConfigInfo(configInfo1);
        //            //    _configInfoBusiness.UpdateConfigInfo(configInfo2);
        //                _configInfoBusiness.UpdateConfigInfo(configInfo3);
        //                _configInfoBusiness.UpdateConfigInfo(configInfo4);
        //           //     _configInfoBusiness.UpdateConfigInfo(configInfo5);
        //            }
        //        }
        //        else
        //        {
        //            MessageBox.Show("请输入0到50之间的正整数！");
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        _logger.LogError(ex.Message);
        //    }


        //}


        /// <summary>
        /// 烘干机温度设定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void HotTempSet_Click(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        bool isValidTemp = int.TryParse(HotTempTxt.Text, out int temp);

        //        // 校验输入的整数是否在0到50之间且大于0
        //        if (isValidTemp && temp > 0)
        //        {
        //            var result = MessageBox.Show("是否确认更改？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Information);
        //            if (result == MessageBoxResult.Yes)
        //            {
        //                List<BaseConfigInfo> configInfos = _configInfoBusiness.GetConfigInfos();
        //                BaseConfigInfo configInfo = configInfos.Where(x => x.ConfigKey == "烘干机温度设定值").FirstOrDefault();

        //                plc.writeInt16ByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机温度设定"), temp);

        //                configInfo.ConfigValue = HotTempTxt.Text;

        //                _configInfoBusiness.UpdateConfigInfo(configInfo);

        //            }
        //        }
        //        else
        //        {
        //            MessageBox.Show("请输入大于0正整数！");
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        _logger.LogError(ex.Message);
        //    }
        //}
        #endregion



    }
}
