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.Model.enums;
using SlnMesnac.Plc;
using SlnMesnac.Repository.service;
using SlnMesnac.WPF.Dto;
using SlnMesnac.WPF.MessageTips;
using SlnMesnac.WPF.Model;
using SlnMesnac.WPF.Page.WindowPage;
using SlnMesnac.WPF.ViewModel;
using SqlSugar;
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.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TouchSocket.Core;
using static SlnMesnac.Business.ProdMgmtBusiness;

namespace SlnMesnac.WPF.Page
{
    /// <summary>
    /// DevMonitorPage.xaml 的交互逻辑
    /// </summary>
    public partial class DevMonitorPage : UserControl
    {
        // 设备OEE采集缓存
        private List<DmsRecordShutDown>? DmsList = null;

        // 设备报警采集缓存
        private List<DmsRecordAlarmTime>? WarningList = null;

        // 设备参数实时状态
        private List<DmsRealtimeStatus>? realtimeStatusList = null;

        /// <summary>
        /// 刷新日志信息
        /// </summary>
        /// <param name="msg"></param>
        public delegate void PrintMessageToListBox(string msg);

        public static event PrintMessageToListBox? PrintMessageToListBoxEvent;

        private ISqlSugarClient? sqlClient = null;
        private BaseBusiness? baseBusiness = null;
        private readonly ConfigInfoBusiness? _configInfoBusiness;
        private readonly IDmsRecordShutDownService? dmsRecordShutDownService;
        private readonly IDmsRecordAlarmTimeService? dmsRecordAlarmTimeService;
        private readonly IDmsRealtimeStatusService? dmsRealtimeStatusService;

        private PlcAbsractFactory plc = null;
        private PlcAbsractFactory pressurePlc = null;
        private int MachineSleep = 1000;
        private readonly ILogger<DevMonitorPage>? _logger;

        private System.Timers.Timer systemRunTimer = new System.Timers.Timer(1000 * 60);

        //系统频率配方
        private RecipeManageCache recipeManageCache = RecipeManageCache.Instance;

        public DevMonitorPage()
        {
            sqlClient = App.ServiceProvider.GetService<ISqlSugarClient>();
            dmsRecordShutDownService = App.ServiceProvider.GetService<IDmsRecordShutDownService>();
            dmsRecordAlarmTimeService = App.ServiceProvider.GetService<IDmsRecordAlarmTimeService>();
            dmsRealtimeStatusService = App.ServiceProvider.GetService<IDmsRealtimeStatusService>();
            ProdMgmtBusiness.MsgHandlerEvent += MsgHandler;
            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");
            pressurePlc = baseBusiness.GetPlcByKey("pressurePlc");
            InitializeComponent();
            this.DataContext = new DevMonitorViewModel();
            Init();
            StartMachineLisening();
            StartAdjustRecipe();
            StartCheckStatusAndStopMachine();
        }

        private void MsgHandler(string message, int msgtype, int outTime = 3)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                Msg.MsgShow(message, msgtype, outTime);
            });
        }

        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(() =>
            {
                List<MachineStatusDto> machineStatusDtos = new List<MachineStatusDto>();
                DmsList = dmsRecordShutDownService.GetAllMachineFirst();
                WarningList = dmsRecordAlarmTimeService.GetMachineWarnList();
                realtimeStatusList = dmsRealtimeStatusService.GetAllList();
                while (true)
                {
                    try
                    {
                        machineStatusDtos.Clear();
                        Thread.Sleep(2000);
                        if (plc != null)
                        {
                            lock (string.Empty)
                            {
                                RefreshMagNet(machineStatusDtos, realtimeStatusList);
                                RefreshSpiral(machineStatusDtos, realtimeStatusList);
                                RefreshHot(machineStatusDtos, realtimeStatusList);
                                RefreshUnPack(machineStatusDtos, realtimeStatusList);

                                //设备缓存区重量监听及启停机控制，监听管道气压
                                RefreshWeight(realtimeStatusList);

                                //开关机时间采集
                                machineStatusDtos.ForEach(x => OeeCollection(x, 1));
                                //报警采集
                                machineStatusDtos.ForEach(x => MachineWarnCollection(x));

                                realtimeStatusList.ForEach(x => x.UpdateTime = DateTime.Now);
                                dmsRealtimeStatusService.Update(realtimeStatusList);

                                //检查监听螺旋和磁选机五个状态，其中一个状态关了就全停机
                            }
                        }
                        else
                        {
                            Application.Current.Dispatcher.Invoke(() =>
                            {
                                Msg.MsgShow($"设备监听失败；PLC连接失败!", 2, 3);
                            });

                            Thread.Sleep(1000 * 20);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError($"设备参数监听StartMachineLisening()异常:{ex.Message}");
                    }
                }
            });
        }

        private DateTime? lastStartTime = null;

        /// <summary>
        /// 设备缓存区重量监听及停机控制，监听包装袋余量
        /// 检查监听螺旋和磁选机五个状态，其中一个状态关了就全停机
        /// </summary>
        private void RefreshWeight(List<DmsRealtimeStatus> realtimeStatusList)
        {
            try
            {
                #region 监听气压    192.168.2.31PLC，DB100.DBD46   压缩空气压力   real

                float pressure = 0;
                if (pressurePlc != null && pressurePlc.IsConnected)
                {
                    float pressureWarnValue = float.Parse(baseBusiness.GetPlcAddressByConfigKey("3楼拆包机气压检测报警阈值"));
                    pressure = pressurePlc.readFloatByAddress("DB100.DBD46");

                    // 预留功能  推送昆明气压值及设定阈值

                    //如果系统设备在运行，气压不足报警
                    if (recipeManageCache.SystemStatus == "1" && pressure < pressureWarnValue)
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            Msg.MsgShow($"设备气压不足,当前{pressure}，阈值{pressureWarnValue}", 2, 1);
                        });
                    }
                }

                #endregion 监听气压    192.168.2.31PLC，DB100.DBD46   压缩空气压力   real

                //  string Bags_Amount = _configInfoBusiness.GetConfigInfos().FirstOrDefault(x => x.ConfigKey == "包装袋余量").ConfigValue;
                App.Current.Dispatcher.BeginInvoke((Action)(() =>
                {
                    //  BagsAmountTxt.Text = Bags_Amount; pressure.ToString();
                    PressureTxt.Text = Math.Round(pressure, 2).ToString() + "MPa";//保留两位小数
                    BufferWeightTxt.Text = recipeManageCache.BufferWeight.ToString("F2");
                }));

                // 判断缓存区重量是否达到设定最大值，如果达到并且设备开机中，那么执行停机；如果达到最小阈值，并且设备处于运行状态，那么自动启动机器
                double Cache_MaxWeight = recipeManageCache.MaxBufferWeight;
                double Cache_MinWeight = recipeManageCache.MinBufferWeight;
                double Cache_Weight = recipeManageCache.BufferWeight;

                //阈值预警消息，100范围，推送到首页系统监控提示
                if (Cache_Weight - Cache_MinWeight > 0 && Cache_Weight - Cache_MinWeight <= 100)
                {
                    PrintMessageToListBoxEvent?.Invoke("");
                }
                if (Cache_MaxWeight - Cache_Weight > 0 && Cache_MaxWeight - Cache_Weight <= 100)
                {
                    PrintMessageToListBoxEvent?.Invoke("");
                }

                bool unPackStatus = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机系统运行状态"));
                if (unPackStatus && (Cache_MaxWeight <= Cache_Weight))
                {
                    // 停所有设备
                    StopMachine(99);
                    //  StopMachine(0);
                    _logger.LogWarning($"设备缓存区当前重量:{Cache_Weight},预设最大重量值:{Cache_MaxWeight},已经超重并且拆包机运行，系统下发停机命令!");
                }
                else if (recipeManageCache.SystemStatus == "1" && (Cache_MinWeight >= Cache_Weight) && unPackStatus == false)
                {
                    bool unPackWarn = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机堵料停螺旋"));

                    if (!unPackWarn && plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机MES允许远程")) == true)
                    {
                        if (lastStartTime == null || DateTime.Now - lastStartTime > TimeSpan.FromMinutes(5))
                        {
                            StartAll();
                            lastStartTime = DateTime.Now;
                        }
                    }
                }

                //  realtimeStatusList.First(x => x.StatusCode == "Bags_Amount").StatusValue = Bags_Amount;
                realtimeStatusList.First(x => x.StatusCode == "Cache_MaxWeight").StatusValue = Cache_MaxWeight.ToString();
                realtimeStatusList.First(x => x.StatusCode == "Cache_Weight").StatusValue = Cache_Weight.ToString();
            }
            catch (Exception ex)
            {
                _logger.LogError($"RefreshWeight出现异常:{ex.Message}");
            }
        }

        /// <summary>
        /// OEE设备关机采集
        /// </summary>
        /// <param name="machineStatusDto"></param>
        private void OeeCollection(MachineStatusDto machineStatusDto, int shutType)
        {
            try
            {
                #region 设备OEE关机采集

                DmsRecordShutDown? record = DmsList.FirstOrDefault(x => x.DeviceId == machineStatusDto.deviceId);
                if (!machineStatusDto.status)  // 关机
                {
                    if (record == null || record.ShutEndTime != null)
                    {
                        DmsRecordShutDown newRecord = new DmsRecordShutDown();
                        newRecord.DeviceId = machineStatusDto.deviceId;
                        newRecord.ShutType = shutType;
                        // newRecord.ShutReason = shutType==1 ? "正常停机" : "报警停机";
                        newRecord.ShutReason = machineStatusDto.warnStatus.ToString();
                        newRecord.ShutBeginTime = DateTime.Now;
                        newRecord.CreateBy = "SlnMesnac";
                        newRecord.CreateTime = DateTime.Now;
                        dmsRecordShutDownService.Insert(newRecord);
                        //更新本地缓存
                        DmsList = dmsRecordShutDownService.GetAllMachineFirst();
                    }
                }
                else //开机
                {
                    if (record != null && record.ShutEndTime == null) //有关机记录，且未结束
                    {
                        record.ShutEndTime = DateTime.Now;
                        record.ShutTime = record.ShutTime = (decimal)(record.ShutEndTime - record.ShutBeginTime).Value.TotalMilliseconds;
                        record.UpdateTime = DateTime.Now;
                        record.UpdateBy = "SlnMesnac";
                        dmsRecordShutDownService.Update(record);
                        //更新本地缓存
                        DmsList = dmsRecordShutDownService.GetAllMachineFirst();
                    }
                }

                #endregion 设备OEE关机采集
            }
            catch (Exception ex)
            {
                _logger.LogError($"OEE设备关机采集异常:{ex.Message}");
            }
        }

        /// <summary>
        /// 设备报警采集
        /// </summary>
        /// <param name="machineStatusDto"></param>
        private void MachineWarnCollection(MachineStatusDto machineStatusDto)
        {
            try
            {
                int alarmRuleId = int.Parse(machineStatusDto.warnStatus.GetDescription());
                // 无报警，找出该设备的报警记录，如果报警记录未结束，则消除报警
                if (machineStatusDto.warnStatus == WarnStatusEnum.无报警)
                {
                    DmsRecordAlarmTime? dmsRecordAlarmTime = WarningList.FirstOrDefault(x => x.DeviceId == machineStatusDto.deviceId);
                    if (dmsRecordAlarmTime != null)
                    {
                        sqlClient.AsTenant().BeginTran();
                        DmsRecordAlarmInfo dmsRecordAlarmInfo = sqlClient.AsTenant().GetConnection("mes").Queryable<DmsRecordAlarmInfo>().First(x => x.AlarmRuleId == dmsRecordAlarmTime.AlarmRuleId && x.AlarmStatus == "0");
                        if (dmsRecordAlarmInfo != null)
                        {
                            dmsRecordAlarmInfo.AlarmEndTime = DateTime.Now;
                            dmsRecordAlarmInfo.AlarmStatus = "2";
                            dmsRecordAlarmInfo.UpdateTime = DateTime.Now;
                            sqlClient.AsTenant().GetConnection("mes").Updateable(dmsRecordAlarmInfo).ExecuteCommand();
                        }
                        sqlClient.AsTenant().GetConnection("mes").Deleteable(dmsRecordAlarmTime).ExecuteCommand();
                        // sqlClient.AsTenant().GetConnection("local").Updateable(localPlan).ExecuteCommand();
                        sqlClient.AsTenant().CommitTran();
                        WarningList = dmsRecordAlarmTimeService.GetMachineWarnList();
                    }
                }
                else
                {
                    // 有报警，找出该设备的报警记录，如果没有报警记录或者报警记录已结束，则新增报警记录
                    int warnRuleId = int.Parse(machineStatusDto.warnStatus.GetDescription());
                    DmsRecordAlarmTime? dmsRecordAlarmTime = WarningList.FirstOrDefault(x => x.AlarmRuleId == warnRuleId);
                    if (dmsRecordAlarmTime == null)
                    {
                        DmsBaseAlarmRule dmsBaseAlarmRule = sqlClient.AsTenant().GetConnection("mes").Queryable<DmsBaseAlarmRule>().First(x => x.AlarmRuleId == warnRuleId);
                        sqlClient.AsTenant().BeginTran();
                        dmsRecordAlarmTime = new DmsRecordAlarmTime();
                        dmsRecordAlarmTime.DeviceId = machineStatusDto.deviceId;
                        dmsRecordAlarmTime.AlarmRuleId = warnRuleId;
                        dmsRecordAlarmTime.AlarmBeginTime = DateTime.Now;
                        dmsRecordAlarmTime.ContinueTime = dmsBaseAlarmRule.ContinueTime;
                        dmsRecordAlarmTime.AlarmReason = dmsBaseAlarmRule.AlarmReason;
                        dmsRecordAlarmTime.AlarmReason = dmsBaseAlarmRule.AlarmReason;
                        dmsRecordAlarmTime.AlarmData = machineStatusDto.warnStatus.ToString();
                        dmsRecordAlarmTime.HandleSuggest = dmsBaseAlarmRule.HandleSuggest;
                        dmsRecordAlarmTime.CreateBy = "SlnMesnac";
                        dmsRecordAlarmTime.CreateTime = DateTime.Now;

                        DmsRecordAlarmInfo dmsRecordAlarmInfo = new DmsRecordAlarmInfo();
                        dmsRecordAlarmInfo.DeviceId = machineStatusDto.deviceId;
                        dmsRecordAlarmInfo.AlarmRuleId = warnRuleId;
                        dmsRecordAlarmInfo.AlarmBeginTime = DateTime.Now;
                        dmsRecordAlarmInfo.AlarmStatus = "0";
                        dmsRecordAlarmInfo.NoticeStatus = "0";
                        dmsRecordAlarmInfo.ContinueTime = dmsBaseAlarmRule.ContinueTime;
                        dmsRecordAlarmInfo.AlarmReason = dmsBaseAlarmRule.AlarmReason;
                        dmsRecordAlarmInfo.AlarmReason = dmsBaseAlarmRule.AlarmReason;
                        dmsRecordAlarmInfo.AlarmData = machineStatusDto.warnStatus.ToString();
                        dmsRecordAlarmInfo.HandleSuggest = dmsBaseAlarmRule.HandleSuggest;
                        dmsRecordAlarmInfo.CreateBy = "SlnMesnac";
                        dmsRecordAlarmInfo.CreateTime = DateTime.Now;

                        sqlClient.AsTenant().GetConnection("mes").Insertable(dmsRecordAlarmTime).ExecuteCommand();
                        sqlClient.AsTenant().GetConnection("mes").Insertable(dmsRecordAlarmInfo).ExecuteCommand();
                        sqlClient.AsTenant().CommitTran();
                        WarningList = dmsRecordAlarmTimeService.GetMachineWarnList();

                        #region 停止设备

                        StopAndMessageWarn(machineStatusDto.warnStatus);
                        //添加报警停机记录
                        // OeeCollection(machineStatusDto, 2);

                        #endregion 停止设备
                    }
                    else
                    {
                        sqlClient.AsTenant().BeginTran();
                        dmsRecordAlarmTime.UpdateTime = DateTime.Now;
                        dmsRecordAlarmTime.UpdateBy = "SlnMesnac";
                        DmsRecordAlarmInfo dmsRecordAlarmInfo = sqlClient.AsTenant().GetConnection("mes").Queryable<DmsRecordAlarmInfo>().First(x => x.AlarmRuleId == warnRuleId);
                        if (dmsRecordAlarmInfo != null)
                        {
                            dmsRecordAlarmInfo.UpdateTime = DateTime.Now;
                            dmsRecordAlarmInfo.UpdateBy = "SlnMesnac";
                        }
                        sqlClient.AsTenant().GetConnection("mes").Updateable(dmsRecordAlarmTime).ExecuteCommand();
                        sqlClient.AsTenant().GetConnection("mes").Updateable(dmsRecordAlarmInfo).ExecuteCommand();
                        sqlClient.AsTenant().CommitTran();
                        WarningList = dmsRecordAlarmTimeService.GetMachineWarnList();
                    }
                }
            }
            catch (Exception ex)
            {
                sqlClient.AsTenant().RollbackTran();
                _logger.LogError($"OEE设备报警采集异常:{ex.Message}");
            }
        }

        /// <summary>
        /// 停止该报警对应的机器及之前的机器，并弹框提醒
        /// </summary>
        private void StopAndMessageWarn(WarnStatusEnum warnStatusEnum)
        {
            int status = getStopLevelByWarnStatus(warnStatusEnum);

            //Application.Current.Dispatcher.Invoke(() =>
            //    {
            //        var alarmWindow = new SystemAlarmWindow();
            //        var viewModel = new SystemAlarmViewModel();
            //        viewModel.AlarmMsg = warnStatusEnum.ToString();
            //        viewModel.AlarmConfirmed += (sender, isConfirmed) =>
            //        {
            //            alarmWindow.Close();
            //        };

            //        alarmWindow.DataContext = viewModel;

            //        alarmWindow.ShowDialog();
            //    });
            if (status >= 0)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Msg.MsgShow($"{warnStatusEnum.ToString()}", 2, 8);
                });
                Task.Run(() =>
                {
                    StopMachine(status);
                });
            }
        }

        /// <summary>
        /// 根据报警状态获取停止等级
        /// -1不停止机器，只弹框报警
        /// </summary>
        /// <param name="warnStatusEnum"></param>
        /// <returns></returns>
        private int getStopLevelByWarnStatus(WarnStatusEnum warnStatusEnum)
        {
            if (warnStatusEnum == WarnStatusEnum.拆包机堵料停螺旋)
            {
                return 0;
            }
            else if (warnStatusEnum == WarnStatusEnum.烘干机烘干温度超温 || warnStatusEnum == WarnStatusEnum.烘干机温控模块通讯超时)
            {   // 不停
                return -1;
            }
            else if (warnStatusEnum.ToString().Contains("烘干机"))
            {
                return 3;
            }
            else if (warnStatusEnum == WarnStatusEnum.螺旋机螺旋1变频器报警)
            {
                return 4;
            }
            else if (warnStatusEnum == WarnStatusEnum.螺旋机螺旋2变频器报警)
            {
                return 6;
            }
            else if (warnStatusEnum.ToString().Contains("磁选机"))
            {
                return 5;
            }
            else
            {
                return -1;
            }
        }

        #region 监测缓存区重量，动态调整配方频率

        /// <summary>
        /// 开始启动监测缓存区重量，动态调整配方频率
        /// </summary>
        private void StartAdjustRecipe()
        {
            Task.Run(() =>
            {
                Thread.Sleep(1000 * 10);
                while (true)
                {
                    try
                    {
                        if (plc != null)
                        {
                            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:
                                            // 当前重量未找到对应配方添加报警记录推送,人工处理
                                            MachineStatusDto machineStatusDto = new MachineStatusDto();
                                            machineStatusDto.warnStatus = WarnStatusEnum.拆包机缓存区重量无对应配方;
                                            MachineWarnCollection(machineStatusDto);
                                            break;

                                        case 0: break;

                                        case 1:
                                            // 高切低
                                            HighToLowSpeed(targetRecipe);
                                            break;

                                        case 2:
                                            // 低切高
                                            LowToHighSpeed(targetRecipe);
                                            break;

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

        /// <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
            {
                recipeManageCache.useRecipeManage.RecipeName = targetRecipet.RecipeName;
                recipeManageCache.RecipeMode = "手动模式";
                return true;
            }
        }

        #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)
        {
            try
            {
                //判断气压
                if (pressurePlc != null && pressurePlc.IsConnected)
                {
                    float pressureWarnValue = float.Parse(baseBusiness.GetPlcAddressByConfigKey("3楼拆包机气压检测报警阈值"));
                    float pressure = pressurePlc.readFloatByAddress("DB100.DBD46");
                    //如果系统设备在运行，气压不足报警
                    if (pressure < pressureWarnValue)
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            Msg.MsgShow($"设备气压不足,当前{pressure}，阈值{pressureWarnValue}", 2, 1);
                        });
                        return;
                    }
                }

                //判断缓存区重量
                double Cache_MaxWeight = recipeManageCache.MaxBufferWeight;
                double Cache_Weight = recipeManageCache.BufferWeight;
                if (Cache_Weight >= Cache_MaxWeight)
                {
                    recipeManageCache.SystemStatus = "1";
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow($"缓存区重量{Cache_Weight}已经超过最大阈值{Cache_MaxWeight}，暂时不启动设备", 2, 3);
                    });
                    return;
                }

                //var result = MessageBox.Show("是否确认启动？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Information);
                //if (result == MessageBoxResult.Yes)
                //{
                // 创建一个自定义对话框
                SelectWindow customDialog = new SelectWindow();
                customDialog.ShowDialog();

                // 判断有无翻转机移走空托盘任务
                WcsTask? task = sqlClient.AsTenant().GetConnection("mes").Queryable<WcsTask>().First(t => (t.IsDelete == 0 || t.IsDelete == null) && t.TaskType == 42);

                if (customDialog.SelectIndex == 1)
                {
                    if (task == null || task.TaskStatus > 4)
                    {
                        MessageBoxAndLog("开始一键启动所有机器!");
                        StartAll();
                        return;
                    }
                    else if (task.TaskStatus == 0 && task.UseFlag == 0)
                    {
                        StartAll();
                        return;
                        //  MessageBoxAndLog("当前有托盘未取走，请点击取走托盘按钮下发命令!");
                    }
                    else
                    {
                        MessageBoxAndLog("3楼agv正在从翻转机搬运空托盘到托盘收集架，请稍等几分钟再开机!");
                        return;
                    }
                }
                else if (customDialog.SelectIndex == 2)
                {
                    if (task == null)
                    {
                        task = new WcsTask();
                        task.TaskType = 42;
                        task.UseFlag = 1;
                        task.TaskStatus = 0;
                        task.IsEmpty = "1";
                        task.Qty = 1;
                        task.NextPointId = 9;
                        task.CurrPointId = 31;
                        task.EndPointId = 35;
                        task.CreateTime = DateTime.Now;
                        sqlClient.AsTenant().GetConnection("mes").Insertable(task).ExecuteCommand();
                    }
                    if (task.TaskStatus == 0 && task.UseFlag == 0)  //激活任务
                    {
                        task.TaskType = 42;
                        task.UseFlag = 1;
                        task.TaskStatus = 0;
                        task.IsEmpty = "1";
                        task.Qty = 1;
                        task.NextPointId = 9;
                        task.CurrPointId = 31;
                        task.EndPointId = 35;
                        task.CreateTime = DateTime.Now;
                        sqlClient.AsTenant().GetConnection("mes").Updateable(task).ExecuteCommand();
                    }
                    else if (task.TaskStatus < 5 && task.UseFlag == 1)
                    {
                        MessageBoxAndLog("3楼agv正在从翻转机搬运空托盘到托盘收集架，请稍等几分钟再开机!");
                        return;
                    }
                }

                //  }
            }
            catch (Exception ex)
            {
                MessageBoxAndLog(ex.Message);
            }
        }

        /// <summary>
        /// 一键启动所有机器
        /// </summary>
        private void StartAll()
        {
            try
            {
                if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机MES允许远程")) == false)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow("拆包机MES屏蔽!", 1, 5);
                    });

                    return;
                }
                if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机MES允许远程")) == false)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow("磁选机MES屏蔽!", 1, 5);
                    });

                    return;
                }
                if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1MES允许远程")) == false)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow("螺旋1MES屏蔽!", 1, 5);
                    });

                    return;
                }
                if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2MES允许远程")) == false)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow("螺旋2MES屏蔽!", 1, 5);
                    });

                    return;
                }
                App.Current.Dispatcher.BeginInvoke((Action)(() =>
                {
                    StartButton.IsEnabled = false;
                }));

                Task.Run(() =>
                {
                    // 启动除尘
                    bool DustStatus = StartDust();
                    if (!DustStatus)
                    {
                        App.Current.Dispatcher.BeginInvoke((Action)(() =>
                        {
                            StartButton.IsEnabled = true;
                        }));
                        MessageBoxAndLog("启动除尘失败!", true);
                        return;
                    }

                    Thread.Sleep(500);

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

                    #region 按顺序依次启动设备

                    //1.螺旋2
                    bool Spiral2Status = StartSpiral2();
                    if (!Spiral2Status)
                    {
                        App.Current.Dispatcher.BeginInvoke((Action)(() =>
                        {
                            StartButton.IsEnabled = true;
                        }));
                        MessageBoxAndLog("启动螺旋2失败!", true);
                        return;
                    }

                    //2.磁选机
                    bool MagNetStatus = StartMagNet();
                    if (!MagNetStatus)
                    {
                        App.Current.Dispatcher.BeginInvoke((Action)(() =>
                        {
                            StartButton.IsEnabled = true;
                        }));
                        MessageBoxAndLog("启动磁选机失败!", true);
                        return;
                    }

                    //3.螺旋1
                    bool Spiral1Status = StartSpiral1();
                    if (!MagNetStatus)
                    {
                        App.Current.Dispatcher.BeginInvoke((Action)(() =>
                        {
                            StartButton.IsEnabled = true;
                        }));
                        MessageBoxAndLog("启动螺旋1失败!", true);
                        return;
                    }

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

                    bool DryerStatus1 = StartDryerMagNet();
                    if (!DryerStatus1)
                    {
                        App.Current.Dispatcher.BeginInvoke((Action)(() =>
                        {
                            StartButton.IsEnabled = true;
                        }));
                        MessageBoxAndLog("启动烘干机螺旋失败!", true);
                        return;
                    }
                    bool DryerStatus2 = StartDryerFan();
                    if (!DryerStatus2)
                    {
                        App.Current.Dispatcher.BeginInvoke((Action)(() =>
                        {
                            StartButton.IsEnabled = true;
                        }));
                        MessageBoxAndLog("启动烘干机风机失败!", true);
                        return;
                    }
                    bool DryerStatus3 = StartDryerHot();
                    if (!DryerStatus3)
                    {
                        App.Current.Dispatcher.BeginInvoke((Action)(() =>
                        {
                            StartButton.IsEnabled = true;
                        }));
                        MessageBoxAndLog("启动烘干机燃烧失败!", true);
                        return;
                    }

                    //5.拆包机
                    bool unpackStatus = StartUnPack();

                    #endregion 按顺序依次启动设备

                    if (unpackStatus)
                    {
                        recipeManageCache.SystemStatus = "1";

                        MessageBoxAndLog("一键启动所有机器成功!");
                    }
                    App.Current.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        StartButton.IsEnabled = true;
                    }));
                });
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Msg.MsgShow($"一键启动异常:{ex.Message}", 2, 5);
                    StartButton.IsEnabled = true;
                });
            }
        }

        /// <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
                {
                    bool unPackStatus5 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机请求移走空托盘"));
                    //先判断请求移走空托盘信号
                    if (unPackStatus5)
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            Msg.MsgShow("拆包机请求移走空托盘信号为true,请等待空托盘移动完成", 0, 5);
                        });
                        return;
                    }

                    App.Current.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        StopButton.IsEnabled = false;
                    }));

                    recipeManageCache.SystemStatus = "0";

                    #region 依次按序停止

                    Task.Run(() =>
                    {
                        bool result = StopMachine(99);
                        if (result)
                        {
                            // 停止除尘
                            StopDust();

                            MessageBoxAndLog("一键停止所有机器成功!");

                            //清空投料系统运行时间
                            BaseConfigInfo runtime = _configInfoBusiness.GetConfigInfos().Where(x => x.ConfigKey == "系统运行时长").FirstOrDefault();
                            BaseConfigInfo timeRangeSet = _configInfoBusiness.GetConfigInfos().Where(x => x.ConfigKey == "投料时间间隔").FirstOrDefault();
                            runtime.ConfigValue = timeRangeSet.ConfigValue;
                            _configInfoBusiness.UpdateConfigInfo(runtime);
                        }

                        App.Current.Dispatcher.BeginInvoke((Action)(() =>
                        {
                            StopButton.IsEnabled = true;
                        }));
                    });

                    #endregion 依次按序停止
                }
                catch (Exception ex)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow($"一键停止:{ex.Message}", 2, 5);
                        StopButton.IsEnabled = true;
                    });
                }
            }
        }

        /// <summary>
        /// 停止机器分级，不同级别停不同机器
        /// 0:停止拆包机
        /// 1:停止拆包机，烘干机螺旋
        /// 2:停止拆包机，烘干机螺旋,`烘干机燃烧
        /// 3:停止拆包机，烘干机螺旋,`烘干机燃烧，烘干机风机
        /// 4:停止拆包机，烘干机螺旋,`烘干机燃烧，烘干机风机，螺旋1
        /// 5:停止拆包机，烘干机螺旋,`烘干机燃烧，烘干机风机，螺旋1，磁选机
        /// 6:停止拆包机，烘干机螺旋,`烘干机燃烧，烘干机风机，螺旋1，磁选机，螺旋2
        /// </summary>
        /// <param name="stopLevel"></param>
        /// <returns></returns>
        private bool StopMachine(int stopLevel = 0)
        {
            bool result = false;

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

            bool unPackStatus1 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机系统运行状态"));
            if (unPackStatus1)
            {
                //检测到拆包机未停止，判断请求移走空托盘信号，如果是该信号引起的无法关机，直接下发急停信号
                bool moveSignal = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机请求移走空托盘"));
                if (moveSignal)
                {
                    SendPulseSignal("拆包机远程急停");
                    Thread.Sleep(MachineSleep);
                    bool unPackStatus = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机系统运行状态"));
                    if (unPackStatus)
                    {
                        MessageBoxAndLog("拆包机无法停止!");
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            if (stopLevel < 1) return true;

            #region 烘干机

            SendPulseSignal("烘干机燃烧停止");
            if (stopLevel < 3) return result;

            Thread.Sleep(MachineSleep);
            SendPulseSignal("烘干机螺旋停止");
            if (stopLevel < 2) return result;

            Thread.Sleep(MachineSleep);
            SendPulseSignal("烘干机风机停止");

            #endregion 烘干机

            if (stopLevel < 4) return result;
            plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1启动"), false);
            if (stopLevel < 5) return result;
            Thread.Sleep(MachineSleep);
            SendPulseSignal("磁选机一键停止");
            if (stopLevel < 6) return result;
            Thread.Sleep(MachineSleep);
            plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2启动"), false);
            result = true;
            // recipeManageCache.SystemStatus = "0";
            // MessageBoxAndLog("一键停止所有机器成功!");
            return result;
        }

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

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

                        recipeManageCache.SystemStatus = "0";
                    }
                }
                else if (StopUrgentButton.Content.ToString() == "复位")
                {
                    var result = MessageBox.Show("是否确认复位？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                    if (result == MessageBoxResult.Yes)
                    {
                        // StopButton.IsEnabled = true;
                        StopUrgentButton.Content = "急停";
                        StopUrgentButton.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#E4B74C"));
                        plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机远程急停"), false);
                        recipeManageCache.SystemStatus = "1";
                    }
                }
            }
            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 (StopUrgentButton.Content.ToString() == "复位")
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow("请先点击复位按钮!", 1, 5);
                    });

                    return;
                }
                if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机MES允许远程")) == false)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow("拆包机MES屏蔽!", 1, 5);
                    });

                    return;
                }
                //bool unPackWarn = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机堵料停螺旋"));
                //if (unPackWarn)
                //{
                //    Application.Current.Dispatcher.Invoke(() =>
                //    {
                //        Msg.MsgShow("拆包机堵料停螺旋，请先处理再开机!!", 1, 5);
                //    });

                //    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
            {
                bool unPackStatus5 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机请求移走空托盘"));
                //先判断请求移走空托盘信号
                if (unPackStatus5)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow("拆包机请求移走空托盘信号为true,请等待空托盘移动完成", 0, 5);
                    });
                    return;
                }

                //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)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow("磁选机MES屏蔽", 1, 5);
                    });

                    return;
                }
                //判断报警---
                //bool magNetWarn = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机设备故障反馈"));
                //if (magNetWarn)
                //{
                //    Application.Current.Dispatcher.Invoke(() =>
                //    {
                //        Msg.MsgShow("磁选机设备故障，请检查后再启动", 1, 5);
                //    });

                //    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)
        {
            Task.Run(() =>
            {
                SendPulseSignal("磁选机一键停止");
            });
            // StartMagNet();
        }

        #endregion 磁选机

        #region 除尘机

        private void StartDustButton_Click(object sender, RoutedEventArgs e)
        {
            bool result = StartDust();
        }

        private void StopDustButton_Click(object sender, RoutedEventArgs e)
        {
            StopDust();
        }

        /// <summary>
        /// 除尘启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private bool StartDust()
        {
            try
            {
                if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("除尘报警")) == true)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow("除尘故障报警,请先点击除尘机变频器复位按钮", 1, 5);
                    });

                    return false;
                }

                //1除尘远程启动
                plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("除尘远程启动"), true);
                Thread.Sleep(1000);
                //2.除尘风机启动
                plc.writeBoolByAddress("DB4.DBX166.1", false);
                Thread.Sleep(200);
                //2.除尘风机启动
                plc.writeBoolByAddress("DB4.DBX166.1", true);
                Thread.Sleep(50);
                //3 清灰启停
                plc.writeBoolByAddress("DB4.DBX166.2", true);
                //震打电机启停1-6
                //plc.writeBoolByAddress("DB4.DBX166.3",true);
                //plc.writeBoolByAddress("DB4.DBX166.4",true);
                //plc.writeBoolByAddress("DB4.DBX166.5",true);
                //plc.writeBoolByAddress("DB4.DBX166.6",true);
                //plc.writeBoolByAddress("DB4.DBX166.7",true);
                //plc.writeBoolByAddress("DB4.DBX167.0", true);
                // 阀门启停1-7
                plc.writeBoolByAddress("DB4.DBX167.1", true);
                plc.writeBoolByAddress("DB4.DBX167.2", true);
                plc.writeBoolByAddress("DB4.DBX167.3", true);
                plc.writeBoolByAddress("DB4.DBX167.4", true);
                plc.writeBoolByAddress("DB4.DBX167.5", true);
                plc.writeBoolByAddress("DB4.DBX167.6", true);
                plc.writeBoolByAddress("DB4.DBX167.7", true);

                return true;
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Msg.MsgShow($"除尘启动:{ex.Message}", 2, 5);
                });

                return false;
            }
        }

        /// <summary>
        /// 除尘停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private bool StopDust()
        {
            try
            {
                //2.除尘风机停止
                plc.writeBoolByAddress("DB4.DBX166.1", false);
                Thread.Sleep(50);
                //3 清灰启停
                plc.writeBoolByAddress("DB4.DBX166.2", false);
                //震打电机启停1-6
                //plc.writeBoolByAddress("DB4.DBX166.3", false);
                //plc.writeBoolByAddress("DB4.DBX166.4", false);
                //plc.writeBoolByAddress("DB4.DBX166.5", false);
                //plc.writeBoolByAddress("DB4.DBX166.6", false);
                //plc.writeBoolByAddress("DB4.DBX166.7", false);
                //plc.writeBoolByAddress("DB4.DBX167.0", false);
                // 阀门启停1-7
                plc.writeBoolByAddress("DB4.DBX167.1", false);
                plc.writeBoolByAddress("DB4.DBX167.2", false);
                plc.writeBoolByAddress("DB4.DBX167.3", false);
                plc.writeBoolByAddress("DB4.DBX167.4", false);
                plc.writeBoolByAddress("DB4.DBX167.5", false);
                plc.writeBoolByAddress("DB4.DBX167.6", false);
                plc.writeBoolByAddress("DB4.DBX167.7", false);
                Thread.Sleep(50);
                //1除尘远程启动停止
                plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("除尘远程启动"), false);

                return true;
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Msg.MsgShow($"除尘停止异常:{ex.Message}", 2, 5);
                });

                _logger.LogError($"除尘停止异常:{ex.Message}");
                return false;
            }
        }

        #endregion 除尘机

        #region 螺旋机

        /// <summary>
        /// 螺旋1启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartSpiral1Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1MES允许远程")) == false)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow("螺旋1MES允许远程，未切换远程", 1, 5);
                    });

                    return;
                }
                bool spiralWarn = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1变频器状态"));
                bool spira2Warn = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2变频器状态"));
                //if (spiralWarn || spira2Warn)
                //{
                //    Application.Current.Dispatcher.Invoke(() =>
                //    {
                //        Msg.MsgShow("螺旋1或螺旋2设备故障，请检查后再启动", 1, 5);
                //    });

                //    return;
                //}
                plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1启动"), true);
                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1速度设置"), recipeManageCache.useRecipeManage.Spiral1);
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Msg.MsgShow($"螺旋1启动异常:{ex.Message}", 2, 5);
                });
            }
            return;
        }

        /// <summary>
        /// 螺旋2启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartSpiral2Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2MES允许远程")) == false)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow("螺旋2MES允许远程，未切换远程", 1, 5);
                    });

                    return;
                }
                else
                {
                    bool spiralWarn = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1变频器状态"));
                    bool spira2Warn = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2变频器状态"));
                    //if (spiralWarn || spira2Warn)
                    //{
                    //    Application.Current.Dispatcher.Invoke(() =>
                    //    {
                    //        Msg.MsgShow("螺旋1或螺旋2设备故障，请检查后再启动", 1, 5);

                    //    });

                    //    return;
                    //}

                    plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2启动"), true);
                    plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2速度设置"), recipeManageCache.useRecipeManage.Spiral2);
                }
            }
            catch (Exception ex)
            {
                MessageBoxAndLog($"螺旋2启动异常:{ex.Message}", true);
            }
            return;
        }

        /// <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
            {
                //bool hotWarn = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机堵料报警"));
                //if (hotWarn)
                //{
                //    MessageBoxAndLog("请先处理烘干机堵料报警,再重新启动!", true);
                //    return;
                //}
                SendPulseSignal("烘干机螺旋启动");
                plc.writeFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机螺旋频率设定"), recipeManageCache.useRecipeManage.DryerSpiral);
            }
            catch (Exception ex)
            {
                MessageBoxAndLog($"烘干机螺旋启动异常:{ex.Message}", true);
            }
            return;
        }

        /// <summary>
        /// 启动烘干机风机2
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartDryerFanButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //bool hotWarn = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机堵料报警"));
                //if (hotWarn)
                //{
                //    MessageBoxAndLog("请先处理烘干机堵料报警,再重新启动!", true);
                //    return;
                //}
                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)
        {
            try
            {
                //bool hotWarn = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机堵料报警"));
                //if (hotWarn)
                //{
                //    MessageBoxAndLog("请先处理烘干机堵料报警,再重新启动!", true);
                //    return;
                //}
                SendPulseSignal("烘干机燃烧启动");
            }
            catch (Exception ex)
            {
                MessageBoxAndLog($"烘干机燃烧启动异常:{ex.Message}", true);
            }
            return;
        }

        /// <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)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow("螺旋2MES允许远程，未切换远程", 1, 5);
                    });

                    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)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow("磁选机MES允许远程，未切换远程", 1, 5);
                    });

                    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)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow($"前提条件螺旋2未成功启动,请检查后重新启动", 2, 5);
                    });

                    return false;
                }
                if (speed2 < value2 * 100 * 0.8)
                {
                    plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2启动"), false);
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow($"前提条件螺旋2速度{speed2}未达到设定值{value2}的下限阈值80%,请检查后重新启动", 2, 5);
                    });

                    return false;
                }
                SendPulseSignal("磁选机一键启动");
                Thread.Sleep(MachineSleep);

                #endregion 启动磁选机 / 前提:check螺旋2启动及速度是否达标

                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)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow($"螺旋1MES允许远程，未切换远程", 1, 5);
                    });

                    return false;
                }
                bool flag1 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机磁选启动"));
                bool flag2 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机震动启动"));
                if (!flag1 || !flag2)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow($"前提条件磁选机未启动，请先检查设备状态再启动", 1, 5);
                    });

                    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)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Msg.MsgShow($"螺旋1启动异常:{ex.Message}", 1, 5);
                });

                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)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow($"烘干机螺旋启动失败:前提条件螺旋1未成功启动,请检查后重新启动", 2, 5);
                    });

                    return false;
                }
                if (speed1 < value1 * 100 * 0.8)
                {
                    // plc.writeBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2启动"), false);
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow($"烘干机螺旋启动失败:前提条件螺旋1速度{speed1}未达到设定值{value1}的下限阈值80%,请检查后重新启动", 2, 5);
                    });

                    return false;
                }

                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)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow($"烘干机风机启动失败:前提条件烘干机螺旋未成功启动,请检查后重新启动", 2, 5);
                    });

                    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)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Msg.MsgShow($"烘干机燃烧启动失败:前提条件烘干机风机未成功启动,请检查后重新启动", 2, 5);
                    });

                    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)
                {
                    _logger.LogError($"拆包机启动失败:前提条件烘干机燃烧未成功启动,请检查后重新启动");
                    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 void RefreshUnPack(List<MachineStatusDto> machineStatusDtos, List<DmsRealtimeStatus> realtimeStatusList)
        {
            try
            {
                bool UnPack_MesUse_Flag = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机MES允许远程"));
                bool UnPack_Status = 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 UnPack_Flip_HZ = plc.readFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机翻转机频率反馈"));
                float UnPack_Roll_HZ = plc.readFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机滚筒筛频率反馈"));
                float UnPack_Spiral1_HZ = plc.readFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机螺旋1频率反馈"));
                float UnPack_Spiral2_HZ = plc.readFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机螺旋2频率反馈"));
                float UnPack_Waste_HZ = plc.readFloatByAddress(baseBusiness.GetPlcAddressByConfigKey("拆包机废袋机频率反馈"));

                App.Current.Dispatcher.BeginInvoke((Action)(() =>
               {
                   UnpackBackColor.Background = UnPack_Status ? Brushes.Green : Brushes.Red;
                   UnpackStatus0.Fill = UnPack_MesUse_Flag ? Brushes.Green : Brushes.Red;
                   UnpackStatus1.Fill = UnPack_Status ? Brushes.Green : Brushes.Red;

                   //UnpackStatus2.Text = unPackStatus2.ToString();
                   UnpackStatus2.Fill = unPackStatus2 ? Brushes.Green : Brushes.Red;
                   //UnpackStatus3.Text = unPackStatus3.ToString();
                   UnpackStatus3.Fill = unPackStatus3 ? Brushes.Green : Brushes.Red;
                   //UnpackStatus4.Text = unPackStatus4.ToString();
                   UnpackStatus4.Fill = unPackStatus4 ? Brushes.Green : Brushes.Red;
                   //UnpackStatus5.Text = unPackStatus5.ToString();
                   UnpackStatus5.Fill = unPackStatus5 ? Brushes.Green : Brushes.Red;
                   UnpackStatus7.Fill = unPackStatus7 ? Brushes.Green : Brushes.Red;
                   UnpackStatus8.Fill = unPackStatus8 ? Brushes.Red : Brushes.Green;

                   UnpackStatus9.Text = UnPack_Flip_HZ.ToString("F2");
                   UnpackStatus10.Text = UnPack_Roll_HZ.ToString("F2");
                   UnpackStatus11.Text = UnPack_Spiral1_HZ.ToString("F2");
                   UnpackStatus12.Text = UnPack_Spiral2_HZ.ToString("F2");
                   UnpackStatus13.Text = UnPack_Waste_HZ.ToString("F2");

                   if (recipeManageCache.SystemStatus == "1")
                   {
                       SystemStatusTxt.Text = "系统运行中";
                       SystemStatusColor.Fill = Brushes.Green;
                   }
                   else
                   {
                       SystemStatusTxt.Text = "系统停机中";
                       SystemStatusColor.Fill = Brushes.Red;
                   }
               }));

                //数据采集部分
                MachineStatusDto machineStatusDto = new MachineStatusDto();
                machineStatusDto.deviceId = 1016;
                machineStatusDto.status = UnPack_Status;
                if (unPackStatus8)
                {
                    machineStatusDto.warnStatus = WarnStatusEnum.拆包机堵料停螺旋;
                }
                else
                {
                    machineStatusDto.warnStatus = WarnStatusEnum.无报警;
                }
                machineStatusDtos.Add(machineStatusDto);
                //设备参数实时更新
                realtimeStatusList.First(x => x.StatusCode == "UnPack_MesUse_Flag").StatusValue = UnPack_MesUse_Flag.ToString();
                realtimeStatusList.First(x => x.StatusCode == "UnPack_Status").StatusValue = UnPack_Status.ToString();
                realtimeStatusList.First(x => x.StatusCode == "UnPack_Flip_HZ").StatusValue = UnPack_Flip_HZ.ToString("F2");
                realtimeStatusList.First(x => x.StatusCode == "UnPack_Roll_HZ").StatusValue = UnPack_Roll_HZ.ToString("F2");
                realtimeStatusList.First(x => x.StatusCode == "UnPack_Spiral1_HZ").StatusValue = UnPack_Spiral1_HZ.ToString("F2");
                realtimeStatusList.First(x => x.StatusCode == "UnPack_Spiral2_HZ").StatusValue = UnPack_Spiral2_HZ.ToString("F2");
                realtimeStatusList.First(x => x.StatusCode == "UnPack_Waste_HZ").StatusValue = UnPack_Waste_HZ.ToString("F2");

                #region 监听气压

                if (pressurePlc != null && pressurePlc.IsConnected)
                {
                    float pressure = pressurePlc.readFloatByAddress("DB100.DBD46");
                    realtimeStatusList.First(x => x.StatusCode == "PressureValue").StatusValue = pressure.ToString("F2");
                }

                #endregion 监听气压
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }
        }

        /// <summary>
        /// 磁选机参数监控  / 除尘
        /// </summary>
        private void RefreshMagNet(List<MachineStatusDto> machineStatusDtos, List<DmsRealtimeStatus> realtimeStatusList)
        {
            try
            {
                bool MagNet_Shake_Status = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机震动启动"));
                bool MagNet_Status = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机磁选启动"));
                bool MagNet_MesUse_Flag = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机MES允许远程"));
                bool signal3 = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机设备故障反馈"));
                //除尘变频器状态
                bool DustStatus = plc.readBoolByAddress("DB4.DBX148.0");

                App.Current.Dispatcher.BeginInvoke((Action)(() =>
               {
                   DustBackColor.Background = DustStatus ? Brushes.Green : Brushes.Red;
                   MagNetShakeBackColor.Background = MagNet_Shake_Status ? Brushes.Green : Brushes.Red;
                   MagNetBackColor.Background = MagNet_Status ? Brushes.Green : Brushes.Red;

                   MagNetStatus1.Fill = MagNet_Shake_Status ? Brushes.Green : Brushes.Red;
                   MagNetStatus2.Fill = MagNet_Status ? Brushes.Green : Brushes.Red;
                   MagNetStatus3.Fill = MagNet_MesUse_Flag ? Brushes.Green : Brushes.Red;
                   MagNetStatus4.Fill = signal3 ? Brushes.Red : Brushes.Green;
               }));
                MachineStatusDto machineStatusDto = new MachineStatusDto();
                machineStatusDto.deviceId = 1017;
                machineStatusDto.status = MagNet_Shake_Status && MagNet_Status;
                if (signal3)
                {
                    machineStatusDto.warnStatus = WarnStatusEnum.磁选机设备故障报警;
                }
                else
                {
                    machineStatusDto.warnStatus = WarnStatusEnum.无报警;
                }
                machineStatusDtos.Add(machineStatusDto);
                //设备参数实时更新
                realtimeStatusList.First(x => x.StatusCode == "MagNet_Shake_Status").StatusValue = MagNet_Shake_Status.ToString();
                realtimeStatusList.First(x => x.StatusCode == "MagNet_Status").StatusValue = MagNet_Status.ToString();
                realtimeStatusList.First(x => x.StatusCode == "MagNet_MesUse_Flag").StatusValue = MagNet_MesUse_Flag.ToString();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }
        }

        /// <summary>
        /// 螺旋机参数监控
        /// </summary>
        private void RefreshSpiral(List<MachineStatusDto> machineStatusDtos, List<DmsRealtimeStatus> realtimeStatusList)
        {
            try
            {
                bool Spiral1_MesUse_Flag = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1MES允许远程"));
                bool Spiral2_MesUse_Flag = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2MES允许远程"));
                bool Spiral1_Status = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1状态"));
                bool Spiral2_Status = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2状态"));

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

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

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

                App.Current.Dispatcher.BeginInvoke((Action)(() =>
               {
                   Spiral1BackColor.Background = Spiral1_Status ? Brushes.Green : Brushes.Red;
                   Spiral2BackColor.Background = Spiral2_Status ? Brushes.Green : Brushes.Red;

                   SpiralSignal0.Fill = Spiral1_MesUse_Flag ? Brushes.Green : Brushes.Red;
                   SpiralSignal1.Fill = Spiral2_MesUse_Flag ? Brushes.Green : Brushes.Red;
                   SpiralSignal2.Fill = Spiral1_Status ? Brushes.Green : Brushes.Red;
                   SpiralSignal3.Fill = Spiral2_Status ? Brushes.Green : Brushes.Red;
                   //变频器状态  0正常1故障
                   SpiralSignal4.Fill = Spiral1_Inverter_Status ? Brushes.Red : Brushes.Green;
                   SpiralSignal5.Fill = Spiral2_Inverter_Status ? Brushes.Red : Brushes.Green;
                   //螺旋1 速度低于80%预警
                   SpiralSignal6.Fill = Spiral1_Speed < Spiral1_Set_Speed * 0.8 ? Brushes.Red : Brushes.Green;
                   SpiralSignal6_Value.Text = Spiral1_Speed.ToString();
                   //螺旋2 速度低于80%预警
                   SpiralSignal7.Fill = Spiral2_Speed < Spiral2_Set_Speed * 0.8 ? Brushes.Red : Brushes.Green;
                   SpiralSignal7_Value.Text = Spiral2_Speed.ToString();
               }));

                MachineStatusDto machineStatusDto = new MachineStatusDto();
                machineStatusDto.deviceId = 1018;
                machineStatusDto.status = Spiral1_Status && Spiral2_Status;
                if (Spiral1_Inverter_Status || Spiral2_Inverter_Status)
                {
                    machineStatusDto.warnStatus = Spiral1_Inverter_Status ? WarnStatusEnum.螺旋机螺旋1变频器报警 : WarnStatusEnum.螺旋机螺旋2变频器报警;
                }
                else
                {
                    machineStatusDto.warnStatus = WarnStatusEnum.无报警;
                }
                machineStatusDtos.Add(machineStatusDto);

                //设备参数实时更新
                realtimeStatusList.First(x => x.StatusCode == "Spiral1_MesUse_Flag").StatusValue = Spiral1_MesUse_Flag.ToString();
                realtimeStatusList.First(x => x.StatusCode == "Spiral2_MesUse_Flag").StatusValue = Spiral2_MesUse_Flag.ToString();
                realtimeStatusList.First(x => x.StatusCode == "Spiral1_Status").StatusValue = Spiral1_Status.ToString();
                realtimeStatusList.First(x => x.StatusCode == "Spiral2_Status").StatusValue = Spiral2_Status.ToString();
                realtimeStatusList.First(x => x.StatusCode == "Spiral1_Inverter_Status").StatusValue = Spiral1_Inverter_Status.ToString();
                realtimeStatusList.First(x => x.StatusCode == "Spiral2_Inverter_Status").StatusValue = Spiral2_Inverter_Status.ToString();
                realtimeStatusList.First(x => x.StatusCode == "Spiral1_Speed").StatusValue = Spiral1_Speed.ToString();
                realtimeStatusList.First(x => x.StatusCode == "Spiral2_Speed").StatusValue = Spiral2_Speed.ToString();
                realtimeStatusList.First(x => x.StatusCode == "Spiral1_Set_Speed").StatusValue = Spiral1_Set_Speed.ToString();
                realtimeStatusList.First(x => x.StatusCode == "Spiral2_Set_Speed").StatusValue = Spiral2_Set_Speed.ToString();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }
        }

        #region 烘干机参数监控

        /// <summary>
        /// 烘干机参数监控
        /// </summary>
        private void RefreshHot(List<MachineStatusDto> machineStatusDtos, List<DmsRealtimeStatus> realtimeStatusList)
        {
            try
            {
                int Hot_Spiral_Status = plc.readByteByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机螺旋状态"));
                int Hot_Fan_Status = plc.readByteByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机风机状态"));
                int Hot_Burn_Status = 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 Hot_Drying_Temperature = plc.readInt16ByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机烘干温度"));
                int Hot_Heat_Temperature = plc.readInt16ByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机加热温度"));
                int Hot_OutAir_Temperature = plc.readInt16ByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机出气温度"));
                int Hot_OutPut_Rate = plc.readInt16ByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机输出百分比"));

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

                App.Current.Dispatcher.BeginInvoke((Action)(() =>
               {
                   HotSpiralBackColor.Background = Hot_Spiral_Status == 1 ? Brushes.Green : Brushes.Red;
                   HotFansBackColor.Background = Hot_Fan_Status == 1 ? Brushes.Green : Brushes.Red;
                   HotBurnBackColor.Background = Hot_Burn_Status == 1 ? Brushes.Green : Brushes.Red;

                   HotSignal1_1.Fill = Hot_Spiral_Status == 1 ? Brushes.Green : Brushes.Red;
                   HotSignal1_1_Value.Text = ChangeHotStatus(Hot_Spiral_Status);
                   HotSignal2_1.Fill = Hot_Fan_Status == 1 ? Brushes.Green : Brushes.Red;
                   HotSignal2_1_Value.Text = ChangeHotStatus(Hot_Fan_Status);
                   HotSignal3_1.Fill = Hot_Burn_Status == 1 ? Brushes.Green : Brushes.Red;
                   HotSignal3_1_Value.Text = ChangeHotStatus(Hot_Burn_Status);

                   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)Hot_Drying_Temperature / 10).ToString();
                   HotSignal5_2_Value.Text = ((double)Hot_Heat_Temperature / 10).ToString();
                   HotSignal6_1_Value.Text = ((double)Hot_OutAir_Temperature / 10).ToString();
                   HotSignal6_2_Value.Text = ((double)Hot_OutPut_Rate / 10).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);
               }));

                MachineStatusDto machineStatusDto = new MachineStatusDto();
                machineStatusDto.deviceId = 1019;
                machineStatusDto.status = signal1_2 && signal2_2;
                if (signal7_1)
                {
                    machineStatusDto.warnStatus = WarnStatusEnum.烘干机堵料报警;
                }
                else if (signal7_2 > 0)
                {
                    switch (signal7_2)
                    {
                        case 1: machineStatusDto.warnStatus = WarnStatusEnum.烘干机风机故障; break;
                        case 2: machineStatusDto.warnStatus = WarnStatusEnum.烘干机燃烧机故障; break;
                        case 4: machineStatusDto.warnStatus = WarnStatusEnum.烘干机传动故障; break;
                        case 16: machineStatusDto.warnStatus = WarnStatusEnum.烘干机烘干温度超温; break;
                        case 32: machineStatusDto.warnStatus = WarnStatusEnum.烘干机温控模块通讯超时; break;
                        default: break;
                    }
                }
                else
                {
                    machineStatusDto.warnStatus = WarnStatusEnum.无报警;
                }
                machineStatusDtos.Add(machineStatusDto);

                //设备参数实时更新
                realtimeStatusList.First(x => x.StatusCode == "Hot_Spiral_Status").StatusValue = (Hot_Spiral_Status == 1).ToString();
                realtimeStatusList.First(x => x.StatusCode == "Hot_Fan_Status").StatusValue = (Hot_Fan_Status == 1).ToString();
                realtimeStatusList.First(x => x.StatusCode == "Hot_Burn_Status").StatusValue = (Hot_Burn_Status == 1).ToString();

                realtimeStatusList.First(x => x.StatusCode == "Hot_Drying_Temperature").StatusValue = ((double)Hot_Drying_Temperature / 10).ToString();
                realtimeStatusList.First(x => x.StatusCode == "Hot_Heat_Temperature").StatusValue = ((double)Hot_Heat_Temperature / 10).ToString(); ;
                realtimeStatusList.First(x => x.StatusCode == "Hot_OutAir_Temperature").StatusValue = ((double)Hot_OutAir_Temperature / 10).ToString();
                realtimeStatusList.First(x => x.StatusCode == "Hot_OutPut_Rate").StatusValue = ((double)Hot_OutPut_Rate / 10).ToString();
            }
            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);
            }
            Application.Current.Dispatcher.Invoke(() =>
            {
                Msg.MsgShow(message, isError == false ? 0 : 2, 5);
            });
        }

        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 设备管理界面螺旋频率设定--暂未启用

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

        private void testTips()
        {
            MessageBoxAndLog("一键启动所有机器成功");
            Task.Run(() =>
            {
                while (true)
                {
                    Thread.Sleep(7000);
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        Random random = new Random();
                        int randomValue = random.Next(0, 3); // 生成 0 到 2 之间的随机整数
                        Msg.MsgShow("消息提示测试", randomValue, 5);
                        // MessageBoxAndLog("一键启动所有机器成功");
                    });
                }
            });
        }

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

        #region 检测多个设备状态，有设备停止则停止所有设备

        /// <summary>
        ///检查监听螺旋和磁选机五个状态是否需要停机，其中一个状态关了就全停机
        /// </summary>
        private bool CheckStatusAndStopMachine(out string machineName)
        {
            machineName = "";
            try
            {
                if (plc != null && plc.IsConnected)
                {
                    int Hot_Spiral_Status = plc.readByteByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机螺旋状态"));
                    int Hot_Fan_Status = plc.readByteByAddress(baseBusiness.GetPlcAddressByConfigKey("烘干机风机状态"));
                    bool MagNet_Status = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("磁选机磁选启动"));
                    bool Spiral1_Status = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋1状态"));
                    bool Spiral2_Status = plc.readBoolByAddress(baseBusiness.GetPlcAddressByConfigKey("螺旋2状态"));
                    if (Hot_Spiral_Status == 1 && Hot_Fan_Status == 1 && MagNet_Status && Spiral1_Status && Spiral2_Status)
                    {  // 全开机
                        return false;
                    }
                    else if (Hot_Spiral_Status == 0 && Hot_Fan_Status == 0 && !MagNet_Status && !Spiral1_Status && !Spiral2_Status)
                    {   // 全关机
                        return false;
                    }
                    else
                    {   // 有部分设备关机,需要停所有
                        if (Hot_Spiral_Status == 0)
                        {
                            machineName = "烘干机螺旋";
                        }
                        else if (Hot_Fan_Status == 0)
                        {
                            machineName = "烘干机风机";
                        }
                        else if (!MagNet_Status)
                        {
                            machineName = "磁选机磁选";
                        }
                        else if (!Spiral1_Status)
                        {
                            machineName = "螺旋机螺旋1状态";
                        }
                        else if (!Spiral2_Status)
                        {
                            machineName = "螺旋机螺旋2状态";
                        }

                        return true;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        ///  检测多个设备状态，有设备停止则停止所有设备
        /// </summary>
        private void StartCheckStatusAndStopMachine()
        {
            Task.Run(() =>
            {
                while (true)
                {
                    try
                    {
                        bool result = CheckStatusAndStopMachine(out string machineName1);
                        if (result)
                        {
                            Thread.Sleep(1000 * 90);
                            // 90s二次确认防止误停： 如果正在一键开机，有可能存在部分机器没开完，此时需要等待90s再次确认
                            bool endResult = CheckStatusAndStopMachine(out string machineName);
                            if (endResult && recipeManageCache.SystemStatus == "1")
                            {
                                // 停所有设备
                                StopMachine(99);
                                //添加停机记录
                                DmsRecordShutDown? record = DmsList.FirstOrDefault(x => x.DeviceId == 1019);
                                if (record != null)
                                {
                                    record.ShutType = 4;
                                    record.ShutReason = $"{machineName}设备关机导致停机";
                                    dmsRecordShutDownService.Update(record);
                                }
                                else
                                {
                                    DmsRecordShutDown newRecord = new DmsRecordShutDown();
                                    newRecord.DeviceId = 1019;
                                    newRecord.ShutType = 4;
                                    newRecord.ShutReason = $"{machineName}设备关机导致停机";
                                    newRecord.ShutBeginTime = DateTime.Now;
                                    newRecord.CreateBy = "SlnMesnac";
                                    newRecord.CreateTime = DateTime.Now;
                                    dmsRecordShutDownService.Insert(newRecord);
                                }

                                //更新本地缓存
                                DmsList = dmsRecordShutDownService.GetAllMachineFirst();
                                _logger.LogWarning($"检测多个设备状态，有设备停止则停止所有设备，系统下发停机命令!");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError($"StartCheckStatusAndStopMachine()发生异常，检测多个设备状态，有设备停止则停止所有设备，发生异常:{ex.Message}");
                    }
                    Thread.Sleep(1000 * 30);
                }
            });
        }

        #endregion 检测多个设备状态，有设备停止则停止所有设备
    }
}