using HslCommunication.Core.IMessage;
using LogForceTestApp.Modules.MainModule.Models;
using LogoForceTestApp.Modules.MainModule.Enums;
using LogoForceTestApp.Modules.MainModule.Models;
using LogoForceTestApp.Modules.MainModule.Services;
using LogoForceTestApp.Services;
using LogoForceTestApp.Services.Interfaces;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Series;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using PropertyChanged;
using Repository;
using Repository.Entiies;
using Serilog;
using SkiaSharp.QrCode; //生成二维码
using SkiaSharp;
using StatementMachineService.Core;
using StatementMachineService.Events;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using Team.Utility;
using static AutoMapper.Internal.ExpressionFactory;
using System.Collections.ObjectModel;
using TouchSocket.Core;
using TouchSocket.Sockets;
using Result = LogoForceTestApp.Modules.MainModule.Models.Result;
using System.Windows.Media;
using SkiaSharp.Views.WPF;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Drawing;
using ZXing.Common;
using ZXing;
using HandyControl.Controls;
using LogoForceTestApp.Core;

namespace LogoForceTestApp.Modules.MainModule.ViewModels
{
    public class MainPageViewModel : BindableBase
    {
        int _upLoadSlowTime;
        private bool _start;
        private List<DataPoint> _points = new();
        private readonly ConcurrentQueue<UpLoadTraceModel> _upLoadTraceModels = new();
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly IScanService _scanService;
        private readonly IModbusTcpSlaverService _modbusTcpSlaverService;
        private readonly IStateService _stateService;
        private readonly IRepository _repository;
        private readonly IWritableOptions<AppSettings> _appSttings;
        private readonly IEventAggregator _eventAggregator;
        private readonly InovanceTcp inovanceTcp;
        private readonly ILogger _logger;
        private readonly IWarningUpdateService _warningUpdateService;
        private readonly IDialogService _dialogService;
        private readonly TcpService tcpService;
        private readonly Dictionary<int, string> SignalMapper;
        private bool _firstStart = true;
        private ResettableTimer _resettableTimer;

        public List<InformationNew> InforNew { get; set; }
        public PlotModel PlotModel { get; private set; }

        public bool ScanConnected { get; set; }
        public Param Param { get; set; }
        public string NewBarcode { get; set; }
        public string UsingBarcode { get; set; }
        public string ErrorCode { get; set; }

        [DoNotNotify]
        public string CSVPath { get; set; }
        [DoNotNotify]
        public string ImagePath { get; set; }
        public int OkDuration { get; set; } = 6000;
        public OeeConfig OeeConfig { get; set; }
        private bool _connected;

        public bool Connected
        {
            get
            {
                _connected = inovanceTcp.Connection("192.168.0.10", 502);
                return _connected;
            }
            set { _connected = value; }
        }

       
        public DelegateCommand QRCommand { get; set; }
        public DelegateCommand HouseCommand { get; set; }
        public DelegateCommand OutWorkCommand { get; set; }
        public DelegateCommand OrderCommand { get; set; }
        public string SelectedOrderName { get; set; }
        public ObservableCollection<string> OrderNames { get; set; }
        public string InQR { get; set; }
        public string LackHouse { get; set; }
        public string UsedHouse { get; set; }
        public string TotalHouse { get; set; }
        public int ActPer { get; set; }
        public int FallPer { get; set; }
        public int AbsPer { get; set; }
        #region Operator
        public string Operator1 { get; set; }
        public string Operator2 { get; set; }
        public string Operator3 { get; set; }
        public string Operator4 { get; set; }
        public string Operator5 { get; set; }
        public string Operator6 { get; set; }
        public string Operator7 { get; set; }
        public string Operator8 { get; set; }
        public string Operator9 { get; set; }
        public string Operator10 { get; set; }
        public string Operator11 { get; set; }
        public string Operator12 { get; set; }
        public string Operator13 { get; set; }
        public string Operator14 { get; set; }
        public string Operator15 { get; set; }
        public string Operator16 { get; set; }
        public string Operator17 { get; set; }
        public string Operator18 { get; set; }
        #endregion

        #region Material
        public string Material1 { get; set; }
        public string Material2 { get; set; }
        public string Material3 { get; set; }
        public string Material4 { get; set; }
        public string Material5 { get; set; }
        public string Material6 { get; set; }
        public string Material7 { get; set; }
        public string Material8 { get; set; }
        public string Material9 { get; set; }
        public string Material10 { get; set; }
        public string Material11 { get; set; }
        public string Material12 { get; set; }
        public string Material13 { get; set; }
        public string Material14 { get; set; }
        public string Material15 { get; set; }
        public string Material16 { get; set; }
        public string Material17 { get; set; }
        public string Material18 { get; set; }
        #endregion

        int[] q = new int[30];
        

        public MainPageViewModel(IHttpClientFactory httpClientFactory, IScanService scanService,
            IModbusTcpSlaverService modbusTcpSlaverService, IStateService stateService, IRepository repository,
                IWritableOptions<AppSettings> appSttings, IEventAggregator eventAggregator, InovanceTcp inovanceTcp,
                ILogger logger, IWarningUpdateService warningUpdateService, IDialogService dialogService, TcpService tcpService)
        {

            _httpClientFactory = httpClientFactory;
            _scanService = scanService;
            _modbusTcpSlaverService = modbusTcpSlaverService;
            _stateService = stateService;
            _repository = repository;
            _appSttings = appSttings;
            CSVPath = _appSttings.Value.CSVPath;
            ImagePath = _appSttings.Value.ImageSavePath;
            _eventAggregator = eventAggregator;
            this.inovanceTcp = inovanceTcp;
            _eventAggregator.GetEvent<WaringUpdateLog>().Subscribe(WaringUpdateLogChanged);
            _logger = logger;
            _warningUpdateService = warningUpdateService;
            _dialogService = dialogService;
            this.tcpService = tcpService;
            InforNew = new List<InformationNew>();
            HouseCommand = new DelegateCommand(UploadHouse);
            OutWorkCommand = new DelegateCommand(UploadOutWork);
            OrderCommand = new DelegateCommand(OrderEnter);
            
        #region tcpService

        tcpService.Connecting = (client, e) =>
            {
                #region ip
                /*
                e.Id = $"{client.IP}:{client.Port}";
                if (client.IP == "192.168.10.1")//1号机 
                {
                    e.Id = "Num1";
                }
                if (client.IP == "192.168.10.2")//2号机
                {
                    e.Id = "Num2";
                }
                if (client.IP == "192.168.10.3")//3号机
                {
                    e.Id = "Num3";
                }
                if (client.IP == "192.168.10.4")//4号机
                {
                    e.Id = "Num4";
                }
                if (client.IP == "192.168.10.5")//5号机
                {
                    e.Id = "Num5";
                }
                if (client.IP == "192.168.10.6")//6号机 
                {
                    e.Id = "Num6";
                }
                if (client.IP == "192.168.10.7")//7号机
                {
                    e.Id = "Num7";
                }
                if (client.IP == "192.168.10.8")//8号机
                {
                    e.Id = "Num8";
                }
                if (client.IP == "192.168.10.9")//9号机
                {
                    e.Id = "Num9";
                }
                if (client.IP == "192.168.10.10")//10号机
                {
                    e.Id = "Num10";
                }
                if (client.IP == "192.168.10.11")//11号机 
                {
                    e.Id = "Num11";
                }
                if (client.IP == "192.168.10.12")//12号机
                {
                    e.Id = "Num12";
                }
                if (client.IP == "192.168.10.13")//13号机
                {
                    e.Id = "Num13";
                }
                if (client.IP == "192.168.10.14")//14号机
                {
                    e.Id = "Num14";
                }
                
                if (client.IP == "192.168.10.15")//检测机1
                {
                    e.Id = "Test1";
                }
                if (client.IP == "192.168.10.16")//检测机2
                {
                    e.Id = "Test2";
                }
                if (client.IP == "192.168.10.17")//检测机3
                {
                    e.Id = "Test3";
                }
                if (client.IP == "192.168.10.18")//检测机4
                {
                    e.Id = "Test4";
                }*/
                #endregion
                return EasyTask.CompletedTask;
            };//有客户端正在连接
            tcpService.Connected = (client, e) =>
            {
                WriteLog("有客户端成功连接");
                return EasyTask.CompletedTask;
            };//有客户端成功连接

            tcpService.Disconnecting = (client, e) =>
            {
                return EasyTask.CompletedTask;
            };//有客户端正在断开连接,只有当主动断开时才有效。
            tcpService.Disconnected = (client, e) =>
            {
                WriteLog("有客户端断开连接");
                return EasyTask.CompletedTask;
            };//有客户端断开连接

            tcpService.Received = (client, e) =>
            {
                //从客户端收到信息
                var mes = Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);//注意:数据长度是byteBlock.Len
                //WriteLog($"已从{client.Id}接收到信息:{mes}");
                //client.Send(mes);
                //WriteLog("发送" + mes);
                try
                {
                    #region 1-7

                    if (client.IP == "192.168.10.1")//1号机
                    {
                        if (mes.Split(":")[0] == "WU")
                        {
                            Material1 = mes.Split(":")[1];
                            client.Send($"WU:物料上传成功");
                            WriteLog("1#物料上传成功");
                        }
                        if (mes.Split(":")[0] == "New")
                        {
                            var newOper = new Account()
                            {
                                Id = Guid.NewGuid(),
                                AccountID = mes.Split(":")[1],
                                ChangePassword = mes.Split(":")[2],
                            };
                            _repository.Add(newOper);
                            client.Send($"NewSuc:注册成功");
                            WriteLog("1#注册成功");
                        }
                        if (mes.Split(":")[0] == "Login")
                        {
                            string accountID = mes.Split(":")[1];
                            string changePassword = mes.Split(":")[2];
                            var login = _repository.GetFirstDefault<Account>(c => c.AccountID == accountID && c.ChangePassword == changePassword);//数据库查
                            if (login != null)
                            {
                                Operator1 = accountID;
                                client.Send($"LoginSuc:登录成功");
                                WriteLog("1#登录成功");
                            }
                        }
                        if (mes == "切换完成")
                        {
                            inovanceTcp.WriteDate("D1501.0", true);
                            Thread.Sleep(1000);
                            WriteLog("1#切换完成");
                        }
                        inovanceTcp.WriteDate("D1501.0", false);
                    }
                    if (client.IP == "192.168.10.2")//2号机
                    {
                        if (mes.Split(":")[0] == "WU")
                        {
                            Material2 = mes.Split(":")[1];
                            client.Send($"WU:物料上传成功");
                            WriteLog("2#物料上传成功");
                        }
                        if (mes.Split(":")[0] == "New")
                        {
                            var newOper = new Account()
                            {
                                Id = Guid.NewGuid(),
                                AccountID = mes.Split(":")[1],
                                ChangePassword = mes.Split(":")[2],
                            };
                            _repository.Add(newOper);
                            client.Send($"NewSuc:注册成功");
                            WriteLog("2#注册成功");
                        }
                        if (mes.Split(":")[0] == "Login")
                        {
                            string accountID = mes.Split(":")[1];
                            string changePassword = mes.Split(":")[2];
                            var login = _repository.GetFirstDefault<Account>(c => c.AccountID == accountID && c.ChangePassword == changePassword);//数据库查
                            if (login != null)
                            {
                                Operator2 = accountID;
                                client.Send($"LoginSuc:登录成功");
                                WriteLog("2#登录成功");
                            }
                        }
                        if (mes == "切换完成")
                        {
                            inovanceTcp.WriteDate("D1501.1", true);
                            Thread.Sleep(1000);
                            WriteLog("2#切换完成");
                        }
                        inovanceTcp.WriteDate("D1501.1", false);
                    }
                    if (client.IP == "192.168.10.3")//3号机
                    {
                        if (mes.Split(":")[0] == "WU")
                        {
                            Material3 = mes.Split(":")[1];
                            client.Send($"WU:物料上传成功");
                            WriteLog("3#物料上传成功");
                        }
                        if (mes.Split(":")[0] == "New")
                        {
                            var newOper = new Account()
                            {
                                Id = Guid.NewGuid(),
                                AccountID = mes.Split(":")[1],
                                ChangePassword = mes.Split(":")[2],
                            };
                            _repository.Add(newOper);
                            client.Send($"NewSuc:注册成功");
                            WriteLog("3#注册成功");
                        }
                        if (mes.Split(":")[0] == "Login")
                        {
                            string accountID = mes.Split(":")[1];
                            string changePassword = mes.Split(":")[2];
                            var login = _repository.GetFirstDefault<Account>(c => c.AccountID == accountID && c.ChangePassword == changePassword);//数据库查
                            if (login != null)
                            {
                                Operator3 = accountID;
                                client.Send($"LoginSuc:登录成功");
                                WriteLog("3#登录成功");
                            }
                        }
                        if (mes == "切换完成")
                        {
                            inovanceTcp.WriteDate("D1501.2", true);
                            Thread.Sleep(1000);
                            WriteLog("3#切换完成");
                        }
                        inovanceTcp.WriteDate("D1501.2", false);
                    }
                    if (client.IP == "192.168.10.4")//4号机
                    {
                        if (mes.Split(":")[0] == "WU")
                        {
                            Material4 = mes.Split(":")[1];
                            client.Send($"WU:物料上传成功");
                            WriteLog("4#物料上传成功");
                        }
                        if (mes.Split(":")[0] == "New")
                        {
                            var newOper = new Account()
                            {
                                Id = Guid.NewGuid(),
                                AccountID = mes.Split(":")[1],
                                ChangePassword = mes.Split(":")[2],
                            };
                            _repository.Add(newOper);
                            client.Send($"NewSuc:注册成功");
                            WriteLog("4#注册成功");
                        }
                        if (mes.Split(":")[0] == "Login")
                        {
                            string accountID = mes.Split(":")[1];
                            string changePassword = mes.Split(":")[2];
                            var login = _repository.GetFirstDefault<Account>(c => c.AccountID == accountID && c.ChangePassword == changePassword);//数据库查
                            if (login != null)
                            {
                                Operator4 = accountID;
                                client.Send($"LoginSuc:登录成功");
                                WriteLog("4#登录成功");
                            }
                        }
                        if (mes == "切换完成")
                        {
                            inovanceTcp.WriteDate("D1501.3", true);
                            Thread.Sleep(1000);
                            WriteLog("4#切换完成");
                        }
                        inovanceTcp.WriteDate("D1501.3", false);
                    }
                    if (client.IP == "192.168.10.5")//5号机
                    {
                        if (mes.Split(":")[0] == "WU")
                        {
                            Material5 = mes.Split(":")[1];
                            client.Send($"WU:物料上传成功");
                            WriteLog("5#物料上传成功");
                        }
                        if (mes.Split(":")[0] == "New")
                        {
                            var newOper = new Account()
                            {
                                Id = Guid.NewGuid(),
                                AccountID = mes.Split(":")[1],
                                ChangePassword = mes.Split(":")[2],
                            };
                            _repository.Add(newOper);
                            client.Send($"NewSuc:注册成功");
                            WriteLog("5#注册成功");
                        }
                        if (mes.Split(":")[0] == "Login")
                        {
                            string accountID = mes.Split(":")[1];
                            string changePassword = mes.Split(":")[2];
                            var login = _repository.GetFirstDefault<Account>(c => c.AccountID == accountID && c.ChangePassword == changePassword);//数据库查
                            if (login != null)
                            {
                                Operator5 = accountID;
                                client.Send($"LoginSuc:登录成功");
                                WriteLog("5#登录成功");
                            }
                        }
                        if (mes == "切换完成")
                        {
                            inovanceTcp.WriteDate("D1501.4", true);
                            Thread.Sleep(1000);
                            WriteLog("5#切换完成");
                        }
                        inovanceTcp.WriteDate("D1501.4", false);
                    }
                    if (client.IP == "192.168.10.6")//6号机
                    {
                        if (mes.Split(":")[0] == "WU")
                        {
                            Material6 = mes.Split(":")[1];
                            client.Send($"WU:物料上传成功");
                            WriteLog("6#物料上传成功");
                        }
                        if (mes.Split(":")[0] == "New")
                        {
                            var newOper = new Account()
                            {
                                Id = Guid.NewGuid(),
                                AccountID = mes.Split(":")[1],
                                ChangePassword = mes.Split(":")[2],
                            };
                            _repository.Add(newOper);
                            client.Send($"NewSuc:注册成功");
                            WriteLog("6#注册成功");
                        }
                        if (mes.Split(":")[0] == "Login")
                        {
                            string accountID = mes.Split(":")[1];
                            string changePassword = mes.Split(":")[2];
                            var login = _repository.GetFirstDefault<Account>(c => c.AccountID == accountID && c.ChangePassword == changePassword);//数据库查
                            if (login != null)
                            {
                                Operator6 = accountID;
                                client.Send($"LoginSuc:登录成功");
                                WriteLog("6#登录成功");
                            }
                        }
                        if (mes == "切换完成")
                        {
                            inovanceTcp.WriteDate("D1501.5", true);
                            Thread.Sleep(1000);
                            WriteLog("6#切换完成");
                        }
                        inovanceTcp.WriteDate("D1501.5", false);
                    }
                    if (client.IP == "192.168.10.7")//7号机
                    {
                        if (mes.Split(":")[0] == "WU")
                        {
                            Material7 = mes.Split(":")[1];
                            client.Send($"WU:物料上传成功");
                            WriteLog("7#物料上传成功");
                        }
                        if (mes.Split(":")[0] == "New")
                        {
                            var newOper = new Account()
                            {
                                Id = Guid.NewGuid(),
                                AccountID = mes.Split(":")[1],
                                ChangePassword = mes.Split(":")[2],
                            };
                            _repository.Add(newOper);
                            client.Send($"NewSuc:注册成功");
                            WriteLog("7#注册成功");
                        }
                        if (mes.Split(":")[0] == "Login")
                        {
                            string accountID = mes.Split(":")[1];
                            string changePassword = mes.Split(":")[2];
                            var login = _repository.GetFirstDefault<Account>(c => c.AccountID == accountID && c.ChangePassword == changePassword);//数据库查
                            if (login != null)
                            {
                                Operator7 = accountID;
                                client.Send($"LoginSuc:登录成功");
                                WriteLog("7#登录成功");
                            }
                        }
                        if (mes == "切换完成")
                        {
                            inovanceTcp.WriteDate("D1501.6", true);
                            Thread.Sleep(1000);
                            WriteLog("7#切换完成");
                        }
                        inovanceTcp.WriteDate("D1501.6", false);
                    }
                    #endregion
                    #region 7-14

                    if (client.IP == "192.168.10.8")//8号机
                    {
                        if (mes.Split(":")[0] == "WU")
                        {
                            Material8 = mes.Split(":")[1];
                            client.Send($"WU:物料上传成功");
                            WriteLog("8#物料上传成功");
                        }
                        if (mes.Split(":")[0] == "New")
                        {
                            var newOper = new Account()
                            {
                                Id = Guid.NewGuid(),
                                AccountID = mes.Split(":")[1],
                                ChangePassword = mes.Split(":")[2],
                            };
                            _repository.Add(newOper);
                            client.Send($"NewSuc:注册成功");
                            WriteLog("8#注册成功");
                        }
                        if (mes.Split(":")[0] == "Login")
                        {
                            string accountID = mes.Split(":")[1];
                            string changePassword = mes.Split(":")[2];
                            var login = _repository.GetFirstDefault<Account>(c => c.AccountID == accountID && c.ChangePassword == changePassword);//数据库查
                            if (login != null)
                            {
                                Operator8 = accountID;
                                client.Send($"LoginSuc:登录成功");
                                WriteLog("8#登录成功");
                            }
                        }
                        if (mes == "切换完成")
                        {
                            inovanceTcp.WriteDate("D1501.7", true);
                            Thread.Sleep(1000);
                            WriteLog("8#切换完成");
                        }
                        inovanceTcp.WriteDate("D1501.7", false);
                    }
                    if (client.IP == "192.168.10.9")//9号机
                    {
                        if (mes.Split(":")[0] == "WU")
                        {
                            Material9 = mes.Split(":")[1];
                            client.Send($"WU:物料上传成功");
                            WriteLog("9#物料上传成功");
                        }
                        if (mes.Split(":")[0] == "New")
                        {
                            var newOper = new Account()
                            {
                                Id = Guid.NewGuid(),
                                AccountID = mes.Split(":")[1],
                                ChangePassword = mes.Split(":")[2],
                            };
                            _repository.Add(newOper);
                            client.Send($"NewSuc:注册成功");
                            WriteLog("9#注册成功");
                        }
                        if (mes.Split(":")[0] == "Login")
                        {
                            string accountID = mes.Split(":")[1];
                            string changePassword = mes.Split(":")[2];
                            var login = _repository.GetFirstDefault<Account>(c => c.AccountID == accountID && c.ChangePassword == changePassword);//数据库查
                            if (login != null)
                            {
                                Operator9 = accountID;
                                client.Send($"LoginSuc:登录成功");
                                WriteLog("9#登录成功");
                            }
                        }
                        if (mes == "切换完成")
                        {
                            inovanceTcp.WriteDate("D1501.8", true);
                            Thread.Sleep(1000);
                            WriteLog("9#切换完成");
                        }
                        inovanceTcp.WriteDate("D1501.8", false);
                    }
                    if (client.IP == "192.168.10.10")//10号机
                    {
                        if (mes.Split(":")[0] == "WU")
                        {
                            Material10 = mes.Split(":")[1];
                            client.Send($"WU:物料上传成功");
                            WriteLog("10#物料上传成功");
                        }
                        if (mes.Split(":")[0] == "New")
                        {
                            var newOper = new Account()
                            {
                                Id = Guid.NewGuid(),
                                AccountID = mes.Split(":")[1],
                                ChangePassword = mes.Split(":")[2],
                            };
                            _repository.Add(newOper);
                            client.Send($"NewSuc:注册成功");
                            WriteLog("10#注册成功");
                        }
                        if (mes.Split(":")[0] == "Login")
                        {
                            string accountID = mes.Split(":")[1];
                            string changePassword = mes.Split(":")[2];
                            var login = _repository.GetFirstDefault<Account>(c => c.AccountID == accountID && c.ChangePassword == changePassword);//数据库查
                            if (login != null)
                            {
                                Operator10 = accountID;
                                client.Send($"LoginSuc:登录成功");
                                WriteLog("10#登录成功");
                            }
                        }
                        if (mes == "切换完成")
                        {
                            inovanceTcp.WriteDate("D1501.9", true);
                            Thread.Sleep(1000);
                            WriteLog("10#切换完成");
                        }
                        inovanceTcp.WriteDate("D1501.9", false);
                    }
                    if (client.IP == "192.168.10.11")//11号机
                    {
                        if (mes.Split(":")[0] == "WU")
                        {
                            Material11 = mes.Split(":")[1];
                            client.Send($"WU:物料上传成功");
                            WriteLog("11#物料上传成功");
                        }
                        if (mes.Split(":")[0] == "New")
                        {
                            var newOper = new Account()
                            {
                                Id = Guid.NewGuid(),
                                AccountID = mes.Split(":")[1],
                                ChangePassword = mes.Split(":")[2],
                            };
                            _repository.Add(newOper);
                            client.Send($"NewSuc:注册成功");
                            WriteLog("11#注册成功");
                        }
                        if (mes.Split(":")[0] == "Login")
                        {
                            string accountID = mes.Split(":")[1];
                            string changePassword = mes.Split(":")[2];
                            var login = _repository.GetFirstDefault<Account>(c => c.AccountID == accountID && c.ChangePassword == changePassword);//数据库查
                            if (login != null)
                            {
                                Operator11 = accountID;
                                client.Send($"LoginSuc:登录成功");
                                WriteLog("11#登录成功");
                            }
                        }
                        if (mes == "切换完成")
                        {
                            inovanceTcp.WriteDate("D1501.10", true);
                            Thread.Sleep(1000);
                            WriteLog("11#切换完成");
                        }
                        inovanceTcp.WriteDate("D1501.10", false);
                    }
                    if (client.IP == "192.168.10.12")//12号机
                    {
                        if (mes.Split(":")[0] == "WU")
                        {
                            Material12 = mes.Split(":")[1];
                            client.Send($"WU:物料上传成功");
                            WriteLog("12#物料上传成功");
                        }
                        if (mes.Split(":")[0] == "New")
                        {
                            var newOper = new Account()
                            {
                                Id = Guid.NewGuid(),
                                AccountID = mes.Split(":")[1],
                                ChangePassword = mes.Split(":")[2],
                            };
                            _repository.Add(newOper);
                            client.Send($"NewSuc:注册成功");
                            WriteLog("12#注册成功");
                        }
                        if (mes.Split(":")[0] == "Login")
                        {
                            string accountID = mes.Split(":")[1];
                            string changePassword = mes.Split(":")[2];
                            var login = _repository.GetFirstDefault<Account>(c => c.AccountID == accountID && c.ChangePassword == changePassword);//数据库查
                            if (login != null)
                            {
                                Operator12 = accountID;
                                client.Send($"LoginSuc:登录成功");
                                WriteLog("12#登录成功");
                            }
                        }
                        if (mes == "切换完成")
                        {
                            inovanceTcp.WriteDate("D1501.11", true);
                            Thread.Sleep(1000);
                            WriteLog("12#切换完成");
                        }
                        inovanceTcp.WriteDate("D1501.11", false);
                    }
                    if (client.IP == "192.168.10.13")//13号机
                    {
                        if (mes.Split(":")[0] == "WU")
                        {
                            Material13 = mes.Split(":")[1];
                            client.Send($"WU:物料上传成功");
                            WriteLog("13#物料上传成功");
                        }
                        if (mes.Split(":")[0] == "New")
                        {
                            var newOper = new Account()
                            {
                                Id = Guid.NewGuid(),
                                AccountID = mes.Split(":")[1],
                                ChangePassword = mes.Split(":")[2],
                            };
                            _repository.Add(newOper);
                            client.Send($"NewSuc:注册成功");
                            WriteLog("13#注册成功");
                        }
                        if (mes.Split(":")[0] == "Login")
                        {
                            string accountID = mes.Split(":")[1];
                            string changePassword = mes.Split(":")[2];
                            var login = _repository.GetFirstDefault<Account>(c => c.AccountID == accountID && c.ChangePassword == changePassword);//数据库查
                            if (login != null)
                            {
                                Operator13 = accountID;
                                client.Send($"LoginSuc:登录成功");
                                WriteLog("13#登录成功");
                            }
                        }
                        if (mes == "切换完成")
                        {
                            inovanceTcp.WriteDate("D1501.12", true);
                            Thread.Sleep(1000);
                            WriteLog("13#切换完成");
                        }
                        inovanceTcp.WriteDate("D1501.12", false);
                    }
                    if (client.IP == "192.168.10.14")//14号机
                    {
                        if (mes.Split(":")[0] == "WU")
                        {
                            Material14 = mes.Split(":")[1];
                            client.Send($"WU:物料上传成功");
                            WriteLog("14#物料上传成功");
                        }
                        if (mes.Split(":")[0] == "New")
                        {
                            var newOper = new Account()
                            {
                                Id = Guid.NewGuid(),
                                AccountID = mes.Split(":")[1],
                                ChangePassword = mes.Split(":")[2],
                            };
                            _repository.Add(newOper);
                            client.Send($"NewSuc:注册成功");
                            WriteLog("14#注册成功");
                        }
                        if (mes.Split(":")[0] == "Login")
                        {
                            string accountID = mes.Split(":")[1];
                            string changePassword = mes.Split(":")[2];
                            var login = _repository.GetFirstDefault<Account>(c => c.AccountID == accountID && c.ChangePassword == changePassword);//数据库查
                            if (login != null)
                            {
                                Operator14 = accountID;
                                client.Send($"LoginSuc:登录成功");
                                WriteLog("14#登录成功");
                            }
                        }
                        if (mes == "切换完成")
                        {
                            inovanceTcp.WriteDate("D1501.13", true);
                            Thread.Sleep(1000);
                            WriteLog("14#切换完成");
                        }
                        inovanceTcp.WriteDate("D1501.13", false);
                    }
                    #endregion
                    #region test

                    if (client.IP == "192.168.10.15")//检测1
                    {
                        if (mes.Split(":")[0] == "Test")
                        {
                            for (int i = 0; i < 30; i++)
                            {
                                if (mes.Split(":")[i+1] == "1")
                                {
                                    q[i] = 1;
                                }
                                else
                                {
                                    q[i] = 0;
                                }
                            }
                            string str = DateTime.Now.ToString("yyyy/MM/dd");
                            var list = repository.GetFirstDefault<Quality>(c => c.DateQuality==str);//查一个值
                            if (list != null)
                            {
                                list.Q1 = list.Q1 + q[0];
                                list.Q2 = list.Q2 + q[1];
                                list.Q3 = list.Q3 + q[2];
                                list.Q4 = list.Q4 + q[3];
                                list.Q5 = list.Q5 + q[4];
                                list.Q6 = list.Q6 + q[5];
                                list.Q7 = list.Q7 + q[6];
                                list.Q8 = list.Q8 + q[7];
                                list.Q9 = list.Q9 + q[8];
                                list.Q10 = list.Q10 + q[9];
                                list.Q11 = list.Q11 + q[10];
                                list.Q12 = list.Q12 + q[11];
                                list.Q13 = list.Q13 + q[12];
                                list.Q14 = list.Q14 + q[13];
                                list.Q15 = list.Q15 + q[14];
                                list.Q16 = list.Q16 + q[15];
                                list.Q17 = list.Q17 + q[16];
                                list.Q18 = list.Q18 + q[17];
                                list.Q19 = list.Q19 + q[18];
                                list.Q20 = list.Q20 + q[19];
                                list.Q21 = list.Q21 + q[20];
                                list.Q22 = list.Q22 + q[21];
                                list.Q23 = list.Q23 + q[22];
                                list.Q24 = list.Q24 + q[23];
                                list.Q25 = list.Q25 + q[24];
                                list.Q26 = list.Q26 + q[25];
                                list.Q27 = list.Q27 + q[26];
                                list.Q28 = list.Q28 + q[27];
                                list.Q29 = list.Q29 + q[28];
                                list.Q30 = list.Q30 + q[29];
                                _repository.Update(list);
                                client.Send("Te:上传成功");
                                WriteLog("检测1#上传成功");
                            }
                            else
                            {
                                var item = new Quality()
                                {
                                    Id = Guid.NewGuid(),
                                    DateQuality = str,
                                    Q1 = q[0],Q2 = q[1],Q3 = q[2], Q4 = q[3],Q5 = q[4],
                                    Q6 = q[5], Q7 = q[6], Q8 = q[7],Q9 = q[8],Q10 = q[9],
                                    Q11 = q[10], Q12 = q[11],Q13 = q[12], Q14 = q[13],Q15 = q[14],
                                    Q16 = q[15],Q17 = q[16],Q18 = q[17],Q19 = q[18],Q20 = q[19],
                                    Q21 = q[20],Q22 = q[21],Q23 = q[22], Q24 = q[23], Q25 = q[24],
                                    Q26 = q[25], Q27 = q[26],Q28 = q[27],Q29 = q[28],Q30 = q[29],
                                };
                                _repository.Add(item);
                                client.Send("Te:上传成功");
                                WriteLog("检测1#上传成功");
                            }
                        }
                        if (mes == "切换完成")
                        {
                            inovanceTcp.WriteDate("D1501.14", true);
                            Thread.Sleep(1000);
                            WriteLog("检测1#切换完成");
                        }
                        inovanceTcp.WriteDate("D1501.14", false);
                        if (mes.Split(":")[0] == "New")
                        {
                            var newOper = new Account()
                            {
                                Id = Guid.NewGuid(),
                                AccountID = mes.Split(":")[1],
                                ChangePassword = mes.Split(":")[2],
                            };
                            _repository.Add(newOper);
                            client.Send($"NewSuc:注册成功");
                            WriteLog("检测1#注册成功");
                        }
                        if (mes.Split(":")[0] == "Login")
                        {
                            string accountID = mes.Split(":")[1];
                            string changePassword = mes.Split(":")[2];
                            var login = _repository.GetFirstDefault<Account>(c => c.AccountID == accountID && c.ChangePassword == changePassword);//数据库查
                            if (login != null)
                            {
                                Operator15 = accountID;
                                client.Send($"LoginSuc:登录成功");
                                WriteLog("检测1#登录成功");
                            }
                        }
                    }
                    if (client.IP == "192.168.10.16")//检测2
                    {
                        if (mes.Split(":")[0] == "Test")
                        {
                            for (int i = 0; i < 30; i++)
                            {
                                if (mes.Split(":")[i + 1] == "1")
                                {
                                    q[i] = 1;
                                }
                                else
                                {
                                    q[i] = 0;
                                }
                            }
                            string str = DateTime.Now.ToString("yyyy/MM/dd");
                            var list = repository.GetFirstDefault<Quality>(c => c.DateQuality == str);//查一个值
                            if (list != null)
                            {
                                list.Q1 = list.Q1 + q[0];
                                list.Q2 = list.Q2 + q[1];
                                list.Q3 = list.Q3 + q[2];
                                list.Q4 = list.Q4 + q[3];
                                list.Q5 = list.Q5 + q[4];
                                list.Q6 = list.Q6 + q[5];
                                list.Q7 = list.Q7 + q[6];
                                list.Q8 = list.Q8 + q[7];
                                list.Q9 = list.Q9 + q[8];
                                list.Q10 = list.Q10 + q[9];
                                list.Q11 = list.Q11 + q[10];
                                list.Q12 = list.Q12 + q[11];
                                list.Q13 = list.Q13 + q[12];
                                list.Q14 = list.Q14 + q[13];
                                list.Q15 = list.Q15 + q[14];
                                list.Q16 = list.Q16 + q[15];
                                list.Q17 = list.Q17 + q[16];
                                list.Q18 = list.Q18 + q[17];
                                list.Q19 = list.Q19 + q[18];
                                list.Q20 = list.Q20 + q[19];
                                list.Q21 = list.Q21 + q[20];
                                list.Q22 = list.Q22 + q[21];
                                list.Q23 = list.Q23 + q[22];
                                list.Q24 = list.Q24 + q[23];
                                list.Q25 = list.Q25 + q[24];
                                list.Q26 = list.Q26 + q[25];
                                list.Q27 = list.Q27 + q[26];
                                list.Q28 = list.Q28 + q[27];
                                list.Q29 = list.Q29 + q[28];
                                list.Q30 = list.Q30 + q[29];
                                _repository.Update(list);
                                client.Send("Te:上传成功");
                                WriteLog("检测2#上传成功");
                            }
                            else
                            {
                                var item = new Quality()
                                {
                                    Id = Guid.NewGuid(),
                                    DateQuality = str,
                                    Q1 = q[0],
                                    Q2 = q[1],
                                    Q3 = q[2],
                                    Q4 = q[3],
                                    Q5 = q[4],
                                    Q6 = q[5],
                                    Q7 = q[6],
                                    Q8 = q[7],
                                    Q9 = q[8],
                                    Q10 = q[9],
                                    Q11 = q[10],
                                    Q12 = q[11],
                                    Q13 = q[12],
                                    Q14 = q[13],
                                    Q15 = q[14],
                                    Q16 = q[15],
                                    Q17 = q[16],
                                    Q18 = q[17],
                                    Q19 = q[18],
                                    Q20 = q[19],
                                    Q21 = q[20],
                                    Q22 = q[21],
                                    Q23 = q[22],
                                    Q24 = q[23],
                                    Q25 = q[24],
                                    Q26 = q[25],
                                    Q27 = q[26],
                                    Q28 = q[27],
                                    Q29 = q[28],
                                    Q30 = q[29],
                                };
                                _repository.Add(item);
                                client.Send("Te:上传成功");
                                WriteLog("检测2#上传成功");
                            }
                        }
                        if (mes == "切换完成")
                        {
                            inovanceTcp.WriteDate("D1501.15", true);
                            Thread.Sleep(1000);
                            WriteLog("检测2#切换完成");
                        }
                        inovanceTcp.WriteDate("D1501.15", false);
                        if (mes.Split(":")[0] == "New")
                        {
                            var newOper = new Account()
                            {
                                Id = Guid.NewGuid(),
                                AccountID = mes.Split(":")[1],
                                ChangePassword = mes.Split(":")[2],
                            };
                            _repository.Add(newOper);
                            client.Send($"NewSuc:注册成功");
                            WriteLog("检测2#注册成功");
                        }
                        if (mes.Split(":")[0] == "Login")
                        {
                            string accountID = mes.Split(":")[1];
                            string changePassword = mes.Split(":")[2];
                            var login = _repository.GetFirstDefault<Account>(c => c.AccountID == accountID && c.ChangePassword == changePassword);//数据库查
                            if (login != null)
                            {
                                Operator16 = accountID;
                                client.Send($"LoginSuc:登录成功");
                                WriteLog("检测2#登录成功");
                            }
                        }
                    }
                    if (client.IP == "192.168.10.17")//检测3
                    {
                        if (mes.Split(":")[0] == "Test")
                        {
                            for (int i = 0; i < 30; i++)
                            {
                                if (mes.Split(":")[i + 1] == "1")
                                {
                                    q[i] = 1;
                                }
                                else
                                {
                                    q[i] = 0;
                                }
                            }
                            string str = DateTime.Now.ToString("yyyy/MM/dd");
                            var list = repository.GetFirstDefault<Quality>(c => c.DateQuality == str);//查一个值
                            if (list != null)
                            {
                                list.Q1 = list.Q1 + q[0];
                                list.Q2 = list.Q2 + q[1];
                                list.Q3 = list.Q3 + q[2];
                                list.Q4 = list.Q4 + q[3];
                                list.Q5 = list.Q5 + q[4];
                                list.Q6 = list.Q6 + q[5];
                                list.Q7 = list.Q7 + q[6];
                                list.Q8 = list.Q8 + q[7];
                                list.Q9 = list.Q9 + q[8];
                                list.Q10 = list.Q10 + q[9];
                                list.Q11 = list.Q11 + q[10];
                                list.Q12 = list.Q12 + q[11];
                                list.Q13 = list.Q13 + q[12];
                                list.Q14 = list.Q14 + q[13];
                                list.Q15 = list.Q15 + q[14];
                                list.Q16 = list.Q16 + q[15];
                                list.Q17 = list.Q17 + q[16];
                                list.Q18 = list.Q18 + q[17];
                                list.Q19 = list.Q19 + q[18];
                                list.Q20 = list.Q20 + q[19];
                                list.Q21 = list.Q21 + q[20];
                                list.Q22 = list.Q22 + q[21];
                                list.Q23 = list.Q23 + q[22];
                                list.Q24 = list.Q24 + q[23];
                                list.Q25 = list.Q25 + q[24];
                                list.Q26 = list.Q26 + q[25];
                                list.Q27 = list.Q27 + q[26];
                                list.Q28 = list.Q28 + q[27];
                                list.Q29 = list.Q29 + q[28];
                                list.Q30 = list.Q30 + q[29];
                                _repository.Update(list);
                                client.Send("Te:上传成功");
                                WriteLog("检测3#上传成功");
                            }
                            else
                            {
                                var item = new Quality()
                                {
                                    Id = Guid.NewGuid(),
                                    DateQuality = str,
                                    Q1 = q[0],
                                    Q2 = q[1],
                                    Q3 = q[2],
                                    Q4 = q[3],
                                    Q5 = q[4],
                                    Q6 = q[5],
                                    Q7 = q[6],
                                    Q8 = q[7],
                                    Q9 = q[8],
                                    Q10 = q[9],
                                    Q11 = q[10],
                                    Q12 = q[11],
                                    Q13 = q[12],
                                    Q14 = q[13],
                                    Q15 = q[14],
                                    Q16 = q[15],
                                    Q17 = q[16],
                                    Q18 = q[17],
                                    Q19 = q[18],
                                    Q20 = q[19],
                                    Q21 = q[20],
                                    Q22 = q[21],
                                    Q23 = q[22],
                                    Q24 = q[23],
                                    Q25 = q[24],
                                    Q26 = q[25],
                                    Q27 = q[26],
                                    Q28 = q[27],
                                    Q29 = q[28],
                                    Q30 = q[29],
                                };
                                _repository.Add(item);
                                client.Send("Te:上传成功");
                                WriteLog("检测3#上传成功");
                            }
                        }
                        if (mes == "切换完成")
                        {
                            inovanceTcp.WriteDate("D1502.0", true);
                            Thread.Sleep(1000);
                            WriteLog("检测3#切换完成");
                        }
                        inovanceTcp.WriteDate("D1502.0", false);
                        if (mes.Split(":")[0] == "New")
                        {
                            var newOper = new Account()
                            {
                                Id = Guid.NewGuid(),
                                AccountID = mes.Split(":")[1],
                                ChangePassword = mes.Split(":")[2],
                            };
                            _repository.Add(newOper);
                            client.Send($"NewSuc:注册成功");
                            WriteLog("检测3#注册成功");
                        }
                        if (mes.Split(":")[0] == "Login")
                        {
                            string accountID = mes.Split(":")[1];
                            string changePassword = mes.Split(":")[2];
                            var login = _repository.GetFirstDefault<Account>(c => c.AccountID == accountID && c.ChangePassword == changePassword);//数据库查
                            if (login != null)
                            {
                                Operator17 = accountID;
                                client.Send($"LoginSuc:登录成功");
                                WriteLog("检测3#登录成功");
                            }
                        }
                    }
                    if (client.IP == "192.168.10.18")//检测4
                    {
                        if (mes.Split(":")[0] == "Test")
                        {
                            for (int i = 0; i < 30; i++)
                            {
                                if (mes.Split(":")[i + 1] == "1")
                                {
                                    q[i] = 1;
                                }
                                else
                                {
                                    q[i] = 0;
                                }
                            }
                            string str = DateTime.Now.ToString("yyyy/MM/dd");
                            var list = repository.GetFirstDefault<Quality>(c => c.DateQuality == str);//查一个值
                            if (list != null)
                            {
                                list.Q1 = list.Q1 + q[0];
                                list.Q2 = list.Q2 + q[1];
                                list.Q3 = list.Q3 + q[2];
                                list.Q4 = list.Q4 + q[3];
                                list.Q5 = list.Q5 + q[4];
                                list.Q6 = list.Q6 + q[5];
                                list.Q7 = list.Q7 + q[6];
                                list.Q8 = list.Q8 + q[7];
                                list.Q9 = list.Q9 + q[8];
                                list.Q10 = list.Q10 + q[9];
                                list.Q11 = list.Q11 + q[10];
                                list.Q12 = list.Q12 + q[11];
                                list.Q13 = list.Q13 + q[12];
                                list.Q14 = list.Q14 + q[13];
                                list.Q15 = list.Q15 + q[14];
                                list.Q16 = list.Q16 + q[15];
                                list.Q17 = list.Q17 + q[16];
                                list.Q18 = list.Q18 + q[17];
                                list.Q19 = list.Q19 + q[18];
                                list.Q20 = list.Q20 + q[19];
                                list.Q21 = list.Q21 + q[20];
                                list.Q22 = list.Q22 + q[21];
                                list.Q23 = list.Q23 + q[22];
                                list.Q24 = list.Q24 + q[23];
                                list.Q25 = list.Q25 + q[24];
                                list.Q26 = list.Q26 + q[25];
                                list.Q27 = list.Q27 + q[26];
                                list.Q28 = list.Q28 + q[27];
                                list.Q29 = list.Q29 + q[28];
                                list.Q30 = list.Q30 + q[29];
                                _repository.Update(list);
                                client.Send("Te:上传成功");
                                WriteLog("检测4#上传成功");
                            }
                            else
                            {
                                var item = new Quality()
                                {
                                    Id = Guid.NewGuid(),
                                    DateQuality = str,
                                    Q1 = q[0],
                                    Q2 = q[1],
                                    Q3 = q[2],
                                    Q4 = q[3],
                                    Q5 = q[4],
                                    Q6 = q[5],
                                    Q7 = q[6],
                                    Q8 = q[7],
                                    Q9 = q[8],
                                    Q10 = q[9],
                                    Q11 = q[10],
                                    Q12 = q[11],
                                    Q13 = q[12],
                                    Q14 = q[13],
                                    Q15 = q[14],
                                    Q16 = q[15],
                                    Q17 = q[16],
                                    Q18 = q[17],
                                    Q19 = q[18],
                                    Q20 = q[19],
                                    Q21 = q[20],
                                    Q22 = q[21],
                                    Q23 = q[22],
                                    Q24 = q[23],
                                    Q25 = q[24],
                                    Q26 = q[25],
                                    Q27 = q[26],
                                    Q28 = q[27],
                                    Q29 = q[28],
                                    Q30 = q[29],
                                };
                                _repository.Add(item);
                                client.Send("Te:上传成功");
                                WriteLog("检测4#上传成功");
                            }
                        }
                        if (mes == "切换完成")
                        {
                            inovanceTcp.WriteDate("D1502.1", true);
                            Thread.Sleep(1000);
                            WriteLog("检测4#切换完成");
                        }
                        inovanceTcp.WriteDate("D1502.1", false);
                        if (mes.Split(":")[0] == "New")
                        {
                            var newOper = new Account()
                            {
                                Id = Guid.NewGuid(),
                                AccountID = mes.Split(":")[1],
                                ChangePassword = mes.Split(":")[2],
                            };
                            _repository.Add(newOper);
                            client.Send($"NewSuc:注册成功");
                            WriteLog("检测4#注册成功");
                        }
                        if (mes.Split(":")[0] == "Login")
                        {
                            string accountID = mes.Split(":")[1];
                            string changePassword = mes.Split(":")[2];
                            var login = _repository.GetFirstDefault<Account>(c => c.AccountID == accountID && c.ChangePassword == changePassword);//数据库查
                            if (login != null)
                            {
                                Operator18 = accountID;
                                client.Send($"LoginSuc:登录成功");
                                WriteLog("检测4#登录成功");
                            }
                        }
                    }

                    #endregion
                }
                catch (Exception ex)
                {
                    WriteLog($"报错:{ex.Message}");
                }
                return EasyTask.CompletedTask;
            };
            #endregion

            SignalMapper = new Dictionary<int, string>
            {
                {1, "D1025.0" },
                {2, "D1025.1" },
                {3, "D1025.2" },
                {4, "D1025.3" },
                {5, "D1025.4" },
                {6, "D1025.5" },
                {7, "D1025.8" },
                {8, "D1025.9" },
                {9, "D1025.10" },
                {10, "D1025.11" },
                {11, "D1025.14" },
                {12, "D1025.15" },
                {13, "D1026.0" },
                {14, "D1026.1" },
            };

            _stateService.CreateMachine(1, RecordOneMessage1, null);
            _stateService.CreateMachine(2, RecordOneMessage2, null);
            _stateService.CreateMachine(3, RecordOneMessage3, null);
            _stateService.CreateMachine(4, RecordOneMessage4, null);
            _stateService.CreateMachine(5, RecordOneMessage5, null);
            _stateService.CreateMachine(6, RecordOneMessage6, null);
            _stateService.CreateMachine(7, RecordOneMessage7, null);
            _stateService.CreateMachine(8, RecordOneMessage8, null);
            _stateService.CreateMachine(9, RecordOneMessage9, null);
            _stateService.CreateMachine(10, RecordOneMessage10, null);
            _stateService.CreateMachine(11, RecordOneMessage11, null);
            _stateService.CreateMachine(12, RecordOneMessage12, null);
            _stateService.CreateMachine(13, RecordOneMessage13, null);
            _stateService.CreateMachine(14, RecordOneMessage14, null);

            Task.Factory.StartNew(Timer_Elapsed, TaskCreationOptions.LongRunning);
            Task.Factory.StartNew(Timer_Elapsed2, TaskCreationOptions.LongRunning);

            QRCommand = new DelegateCommand(QRcode);

            //_eventAggregator.GetEvent<FileChangedEvent>().Subscribe(ReadConfig);
            
        }

        private void OrderEnter()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(SelectedOrderName))
                {
                    
                }
                else
                {
                    Quest(SelectedOrderName);
                    WriteLog("切换订单成功");
                }
            }
            catch (Exception)
            {

            }
        }
        
        public void ReadOrder()
        {
            var customRepo = new CustomRepository();
            try
            {
                DateTime max = DateTime.Today.AddDays(1);
                DateTime min = DateTime.Today.AddDays(-1);
                //var list = customRepo.GetAllQuery<ICMO>(c => c.FDate == DateTime.Today);
                var list = customRepo.GetAllQuery<ICMO>(c => c.FDate < max && c.FDate > min);
                if (list != null)
                {
                    OrderNames = new ObservableCollection<string>();
                    for (int i = 0; i < list.Count; i++)
                    {
                        OrderNames.Add(list[i].FBillNo);
                    }
                }
            }
            catch (Exception ex)
            {
                
            }
        }
        private void UploadOutWork()
        {
            string str = DateTime.Now.ToString("yyyy/MM/dd");
            var list = _repository.GetFirstDefault<OutofWork>(c => c.DateOutWork == str);
            if (list != null)
            {
                list.DateOutWork = str;
                list.Actual = ActPer;
                list.FallIll = FallPer;
                list.Absenteeism = AbsPer;
                _repository.Update(list);
                WriteLog("出勤信息上传成功");
            }
            else
            {
                var outwork = new OutofWork()
                {
                    Id = Guid.NewGuid(),
                    DateOutWork = DateTime.Now.ToString("yyyy/MM/dd"),
                    Actual = ActPer,
                    FallIll = FallPer,
                    Absenteeism = AbsPer,
                };
                _repository.Add(outwork);
                WriteLog("出勤信息上传成功");
            }
        }

        private void UploadHouse()
        {
            string str = DateTime.Now.ToString("yyyy/MM/dd");
            var list = _repository.GetFirstDefault<House>(c => c.DateH == str);
            if (list != null)
            {
                list.DateH = str;
                list.LackH = LackHouse;
                list.UsedH = UsedHouse;
                list.TotalH = TotalHouse;
                _repository.Update(list);
                WriteLog("线边仓数据上传成功");
            }
            else
            {
                var houses = new House()
                {
                    Id = Guid.NewGuid(),
                    DateH = DateTime.Now.ToString("yyyy/MM/dd"),
                    LackH = LackHouse,
                    UsedH = UsedHouse,
                    TotalH = TotalHouse,
                };
                _repository.Add(houses);
                WriteLog("线边仓数据上传成功");
            }
        }

        //void SwitchProduct()
        //{
        //    SendToClient("Num1");
        //}
        //public void SendToClient(string id)
        //{
        //    //tcpService.SocketClients.GetIds() 向所有id发送
        //    //foreach (var item in tcpService.SocketClients.GetIds())
        //    //{
        //    //    if (string.IsNullOrWhiteSpace(SelectedConfigName))
        //    //    {
        //    //        tcpService.Send(item, "None");
        //    //        WriteLog("发送:None");
        //    //        return;
        //    //    }
        //    //    tcpService.Send(item, SelectedConfigName);
        //    //    WriteLog("发送:" + SelectedConfigName);
        //    //}
        //    if (string.IsNullOrWhiteSpace(SelectedConfigName))
        //    {
        //        tcpService.Send(id, "None");
        //        WriteLog("发送:None");
        //        return;
        //    }
        //    tcpService.Send(id, SelectedConfigName);
        //    WriteLog("发送:" + SelectedConfigName);

        //}
        public void SendPro(string id, string name)
        {
            try
            {
                var ids = tcpService.SocketClients.GetIds();
                foreach (var item in tcpService.SocketClients.GetClients())
                {
                    if (item.IP == id)
                    {
                        item.Send("Type:" + name + ":" + id);
                        WriteLog("发送:" + name);
                        break;
                    }

                }
                //tcpService.Send(id, "Type:" + name + ":" + id);
                //WriteLog("发送:" + name);
            }
            catch (Exception)
            {

            }
        }

        #region 工位
        public void RecordOneMessage1(object sender, StateEventArgs e)//1
        {
            var spt = inovanceTcp.ReadInt("D1003");
            var d1 = inovanceTcp.ReadInt("D1030");
            var d2 = inovanceTcp.ReadInt("D1031");
            var d3 = inovanceTcp.ReadInt("D1032");
            var pno = d1.ToString() + d2.ToString() + d3.ToString();
            var productNew = new InformationNew
            {
                OperatorCode = Operator1,
                ProCode = Material1,
                SpendTime = spt/10,
                CreateTime = DateTime.Now,
                ProType = proName,
                ProNo=pno,
            };
            var product = new Information()
            {
                CreateTime = productNew.CreateTime,
                Id = Guid.NewGuid(),
                OperatorCode = productNew.OperatorCode,
                ProCode = productNew.ProCode,
                SpendTime = productNew.SpendTime,
                ProType = productNew.ProType,
                ProNo=productNew.ProNo
            };

            InforNew.Add(productNew);
            _repository.Add(product);
            inovanceTcp.WriteDate("D1025.0", false);
        }
        public void RecordOneMessage2(object sender, StateEventArgs e)//2
        {
            var spt = inovanceTcp.ReadInt("D1004");
            var d1 = inovanceTcp.ReadInt("D1033");
            var d2 = inovanceTcp.ReadInt("D1034");
            var d3 = inovanceTcp.ReadInt("D1035");
            var pno = d1.ToString() + d2.ToString() + d3.ToString();
            var productNew = new InformationNew
            {
                OperatorCode = Operator2,
                ProCode = Material2,
                SpendTime = spt/10,
                CreateTime = DateTime.Now,
                ProType = proName,
                ProNo = pno,
            };
            var product = new Information()
            {
                CreateTime = productNew.CreateTime,
                Id = Guid.NewGuid(),
                OperatorCode = productNew.OperatorCode,
                ProCode = productNew.ProCode,
                SpendTime = productNew.SpendTime,
                ProType = productNew.ProType,
                ProNo = productNew.ProNo
            };

            _repository.Add(product);
            InforNew.Add(productNew);
            inovanceTcp.WriteDate("D1025.1", false);
        }
        public void RecordOneMessage3(object sender, StateEventArgs e)//3
        {
            var spt = inovanceTcp.ReadInt("D1005");
            var d1 = inovanceTcp.ReadInt("D1036");
            var d2 = inovanceTcp.ReadInt("D1037");
            var d3 = inovanceTcp.ReadInt("D1038");
            var pno = d1.ToString() + d2.ToString() + d3.ToString();
            var productNew = new InformationNew
            {
                OperatorCode = Operator3,
                ProCode = Material3,
                SpendTime = spt/10,
                CreateTime = DateTime.Now,
                ProType = proName,
                ProNo = pno,
            };
            var product = new Information()
            {
                CreateTime = productNew.CreateTime,
                Id = Guid.NewGuid(),
                OperatorCode = productNew.OperatorCode,
                ProCode = productNew.ProCode,
                SpendTime = productNew.SpendTime,
                ProType = productNew.ProType,
                ProNo=productNew.ProNo
            };

            _repository.Add(product);
            InforNew.Add(productNew);
            inovanceTcp.WriteDate("D1025.2", false);
        }
        public void RecordOneMessage4(object sender, StateEventArgs e)//4
        {
            var spt = inovanceTcp.ReadInt("D1006");
            var d1 = inovanceTcp.ReadInt("D1039");
            var d2 = inovanceTcp.ReadInt("D1040");
            var d3 = inovanceTcp.ReadInt("D1041");
            var pno = d1.ToString() + d2.ToString() + d3.ToString();
            var productNew = new InformationNew
            {
                OperatorCode = Operator4,
                ProCode = Material4,
                SpendTime = spt/10,
                CreateTime = DateTime.Now,
                ProType = proName,
                ProNo = pno,
            };
            var product = new Information()
            {
                CreateTime = productNew.CreateTime,
                Id = Guid.NewGuid(),
                OperatorCode = productNew.OperatorCode,
                ProCode = productNew.ProCode,
                SpendTime = productNew.SpendTime,
                ProType = productNew.ProType,
                ProNo = productNew.ProNo
            };

            _repository.Add(product);
            InforNew.Add(productNew);
            inovanceTcp.WriteDate("D1025.3", false);
        }
        public void RecordOneMessage5(object sender, StateEventArgs e)//5
        {
            var spt = inovanceTcp.ReadInt("D1007");
            var d1 = inovanceTcp.ReadInt("D1042");
            var d2 = inovanceTcp.ReadInt("D1043");
            var d3 = inovanceTcp.ReadInt("D1044");
            var pno = d1.ToString() + d2.ToString() + d3.ToString();
            var productNew = new InformationNew
            {
                OperatorCode = Operator5,
                ProCode = Material5,
                SpendTime = spt/10,
                CreateTime = DateTime.Now,
                ProType = proName,
                ProNo = pno,
            };
            var product = new Information()
            {
                CreateTime = productNew.CreateTime,
                Id = Guid.NewGuid(),
                OperatorCode = productNew.OperatorCode,
                ProCode = productNew.ProCode,
                SpendTime = productNew.SpendTime,
                ProType = productNew.ProType,
                ProNo = productNew.ProNo
            };

            _repository.Add(product);
            InforNew.Add(productNew);
            inovanceTcp.WriteDate("D1025.4", false);
        }
        public void RecordOneMessage6(object sender, StateEventArgs e)//6
        {
            var spt = inovanceTcp.ReadInt("D1008");
            var d1 = inovanceTcp.ReadInt("D1045");
            var d2 = inovanceTcp.ReadInt("D1046");
            var d3 = inovanceTcp.ReadInt("D1047");
            var pno = d1.ToString() + d2.ToString() + d3.ToString();
            var productNew = new InformationNew
            {
                OperatorCode = Operator6,
                ProCode = Material6,
                SpendTime = spt/10,
                CreateTime = DateTime.Now,
                ProType = proName,
                ProNo = pno,
            };
            var product = new Information()
            {
                CreateTime = productNew.CreateTime,
                Id = Guid.NewGuid(),
                OperatorCode = productNew.OperatorCode,
                ProCode = productNew.ProCode,
                SpendTime = productNew.SpendTime,
                ProType = productNew.ProType,
                ProNo=productNew.ProNo
            };

            _repository.Add(product);
            InforNew.Add(productNew);
            inovanceTcp.WriteDate("D1025.5", false);
        }
        public void RecordOneMessage7(object sender, StateEventArgs e)//7
        {
            var spt = inovanceTcp.ReadInt("D1011");
            var d1 = inovanceTcp.ReadInt("D1048");
            var d2 = inovanceTcp.ReadInt("D1049");
            var d3 = inovanceTcp.ReadInt("D1050");
            var pno = d1.ToString() + d2.ToString() + d3.ToString();
            var productNew = new InformationNew
            {
                OperatorCode = Operator9,
                ProCode = Material9,
                SpendTime = spt / 10,
                CreateTime = DateTime.Now,
                ProType = proName,
                ProNo = pno,
            };
            var product = new Information()
            {
                CreateTime = productNew.CreateTime,
                Id = Guid.NewGuid(),
                OperatorCode = productNew.OperatorCode,
                ProCode = productNew.ProCode,
                SpendTime = productNew.SpendTime,
                ProType = productNew.ProType,
                ProNo = productNew.ProNo,
            };

            _repository.Add(product);
            InforNew.Add(productNew);
            inovanceTcp.WriteDate("D1025.8", false);
        }
        public void RecordOneMessage8(object sender, StateEventArgs e)//8
        {
            var spt = inovanceTcp.ReadInt("D1012");
            var d1 = inovanceTcp.ReadInt("D1051");
            var d2 = inovanceTcp.ReadInt("D1052");
            var d3 = inovanceTcp.ReadInt("D1053");
            var pno = d1.ToString() + d2.ToString() + d3.ToString();
            var productNew = new InformationNew
            {
                OperatorCode = Operator10,
                ProCode = Material10,
                SpendTime = spt/10,
                CreateTime = DateTime.Now,
                ProType = proName,
                ProNo = pno,
            };
            var product = new Information()
            {
                CreateTime = productNew.CreateTime,
                Id = Guid.NewGuid(),
                OperatorCode = productNew.OperatorCode,
                ProCode = productNew.ProCode,
                SpendTime = productNew.SpendTime,
                ProType = productNew.ProType,
                ProNo= productNew.ProNo,
            };

            _repository.Add(product);
            InforNew.Add(productNew);
            inovanceTcp.WriteDate("D1025.9", false);
        }
        public void RecordOneMessage9(object sender, StateEventArgs e)//9
        {
            var spt = inovanceTcp.ReadInt("D1013");
            var d1 = inovanceTcp.ReadInt("D1054");
            var d2 = inovanceTcp.ReadInt("D1055");
            var d3 = inovanceTcp.ReadInt("D1056");
            var pno = d1.ToString() + d2.ToString() + d3.ToString();
            var productNew = new InformationNew
            {
                OperatorCode = Operator11,
                ProCode = Material11,
                SpendTime = spt/10,
                CreateTime = DateTime.Now,
                ProType = proName,
                ProNo = pno,
            };
            var product = new Information()
            {
                CreateTime = productNew.CreateTime,
                Id = Guid.NewGuid(),
                OperatorCode = productNew.OperatorCode,
                ProCode = productNew.ProCode,
                SpendTime = productNew.SpendTime,
                ProType = productNew.ProType,
                ProNo= productNew.ProNo,
            };

            _repository.Add(product);
            InforNew.Add(productNew);
            inovanceTcp.WriteDate("D1025.10", false);
        }
        public void RecordOneMessage10(object sender, StateEventArgs e)//10
        {
            var spt = inovanceTcp.ReadInt("D1014");
            var d1 = inovanceTcp.ReadInt("D1057");
            var d2 = inovanceTcp.ReadInt("D1058");
            var d3 = inovanceTcp.ReadInt("D1059");
            var pno = d1.ToString() + d2.ToString() + d3.ToString();
            var productNew = new InformationNew
            {
                OperatorCode = Operator12,
                ProCode = Material12,
                SpendTime = spt/10,
                CreateTime = DateTime.Now,
                ProType = proName,
                ProNo = pno,
            };
            var product = new Information()
            {
                CreateTime = productNew.CreateTime,
                Id = Guid.NewGuid(),
                OperatorCode = productNew.OperatorCode,
                ProCode = productNew.ProCode,
                SpendTime = productNew.SpendTime,
                ProType = productNew.ProType,
                ProNo= productNew.ProNo,
            };

            _repository.Add(product);
            InforNew.Add(productNew);
            inovanceTcp.WriteDate("D1025.11", false);
        }
        public void RecordOneMessage11(object sender, StateEventArgs e)//11
        {
            var spt = inovanceTcp.ReadInt("D1017");
            var d1 = inovanceTcp.ReadInt("D1060");
            var d2 = inovanceTcp.ReadInt("D1061");
            var d3 = inovanceTcp.ReadInt("D1062");
            var pno = d1.ToString() + d2.ToString() + d3.ToString();
            var productNew = new InformationNew
            {
                OperatorCode = Operator15,
                ProCode = Material15,
                SpendTime = spt/10,
                CreateTime = DateTime.Now,
                ProType = proName,
                ProNo = pno,
            };
            var product = new Information()
            {
                CreateTime = productNew.CreateTime,
                Id = Guid.NewGuid(),
                OperatorCode = productNew.OperatorCode,
                ProCode = productNew.ProCode,
                SpendTime = productNew.SpendTime,
                ProType = productNew.ProType,
                ProNo= productNew.ProNo,
            };

            _repository.Add(product);
            InforNew.Add(productNew);
            inovanceTcp.WriteDate("D1025.14", false);
        }
        public void RecordOneMessage12(object sender, StateEventArgs e)//12
        {
            var spt = inovanceTcp.ReadInt("D1018");
            var d1 = inovanceTcp.ReadInt("D1063");
            var d2 = inovanceTcp.ReadInt("D1064");
            var d3 = inovanceTcp.ReadInt("D1065");
            var pno = d1.ToString() + d2.ToString() + d3.ToString();
            var productNew = new InformationNew
            {
                OperatorCode = Operator16,
                ProCode = Material16,
                SpendTime = spt/10,
                CreateTime = DateTime.Now,
                ProType = proName,
                ProNo = pno,
            };
            var product = new Information()
            {
                CreateTime = productNew.CreateTime,
                Id = Guid.NewGuid(),
                OperatorCode = productNew.OperatorCode,
                ProCode = productNew.ProCode,
                SpendTime = productNew.SpendTime,
                ProType = productNew.ProType,
                ProNo = productNew.ProNo,
            };

            _repository.Add(product);
            InforNew.Add(productNew);
            inovanceTcp.WriteDate("D1025.15", false);
        }
        public void RecordOneMessage13(object sender, StateEventArgs e)//13
        {
            var spt = inovanceTcp.ReadInt("D1019");
            var d1 = inovanceTcp.ReadInt("D1066");
            var d2 = inovanceTcp.ReadInt("D1067");
            var d3 = inovanceTcp.ReadInt("D1068");
            var pno = d1.ToString() + d2.ToString() + d3.ToString();
            var productNew = new InformationNew
            {
                OperatorCode = Operator17,
                ProCode = Material17,
                SpendTime = spt/10,
                CreateTime = DateTime.Now,
                ProType = proName,
                ProNo = pno,
            };
            var product = new Information()
            {
                CreateTime = productNew.CreateTime,
                Id = Guid.NewGuid(),
                OperatorCode = productNew.OperatorCode,
                ProCode = productNew.ProCode,
                SpendTime = productNew.SpendTime,
                ProType = productNew.ProType,
                ProNo = productNew.ProNo,
            };

            _repository.Add(product);
            InforNew.Add(productNew);
            inovanceTcp.WriteDate("D1026.0", false);
        }
        public void RecordOneMessage14(object sender, StateEventArgs e)//14
        {
            var spt = inovanceTcp.ReadInt("D1020");
            var d1 = inovanceTcp.ReadInt("D1069");
            var d2 = inovanceTcp.ReadInt("D1070");
            var d3 = inovanceTcp.ReadInt("D1071");
            var pno = d1.ToString() + d2.ToString() + d3.ToString();
            var productNew = new InformationNew
            {
                OperatorCode = Operator18,
                ProCode = Material18,
                SpendTime = spt/10,
                CreateTime = DateTime.Now,
                ProType = proName,
                ProNo = pno,
            };
            var product = new Information()
            {
                CreateTime = productNew.CreateTime,
                Id = Guid.NewGuid(),
                OperatorCode = productNew.OperatorCode,
                ProCode = productNew.ProCode,
                SpendTime = productNew.SpendTime,
                ProType = productNew.ProType,
                ProNo = productNew.ProNo,
            };

            _repository.Add(product);
            InforNew.Add(productNew);
            inovanceTcp.WriteDate("D1026.1", false);
        }
        #endregion
        public void Quest(string str)
        {
            _eventAggregator.GetEvent<QuestEvent>().Publish(str);
        }

        public void Alarm(Dictionary<string, string> plcsignal)
        {
            _eventAggregator.GetEvent<AlarmEvent>().Publish(plcsignal);//跨viewmodel发信息,Publish(发送的消息)
        }

        bool mybool = false;
        bool one = true;
        string proName;
        private void Timer_Elapsed()
        {
            while (true)
            {
                if (!Connected)
                {
                    if (one)
                    {
                        WriteLog("plc连接异常", LogType.Error);
                        one = false;
                    }
                    continue;
                }

                try
                {
                    if (one)
                    {
                        WriteLog("plc连接成功", LogType.Info);
                        one = false;
                    }

                    if (!mybool)
                    {
                        inovanceTcp.WriteDate("D1500", 0);
                        mybool = true;
                    }
                    else
                    {
                        inovanceTcp.WriteDate("D1500", 1);
                        mybool = false;
                    }

                    foreach (var item in SignalMapper)
                    {
                        //if (e.StartingAddress+e.Points.Length < item.Value)
                        //{
                        //    continue;
                        //}
                        //var data = e.Points[item.Value];

                        //var value = inovanceTcp.Read(item.Value, 1);
                        
                        var value=inovanceTcp.ReadBool(item.Value);
                        _stateService.ExecuteState(item.Key, value ? (ushort)1 : (ushort)0);
                    }
                }
                catch (ObjectDisposedException ex)
                {
                    _logger.Information(ex.ToString());
                }
                finally
                {
                    Thread.Sleep(1000);
                }
            }
        }
        int a=0;
        private void Timer_Elapsed2()
        {
            while (true)
            {
                if (!Connected)
                {
                    continue;
                }
                try
                {
                    ReadOrder();
                    //切换产品
                    int type = inovanceTcp.ReadInt("D1000");
                    if (a !=type)
                    {
                        Change();
                    }
                    a = type;
                    #region 报警
                    var dictionary = new Dictionary<string, string>();
                    
                    for (int i = 0; i < 31; i++)
                    {
                        var adrress = "D" + (1100 + i).ToString();
                        int ad = inovanceTcp.ReadInt(adrress);
                        if (ad != 0)
                        {
                            dictionary.Add(adrress, "报警");
                        }
                        else
                        {
                            dictionary.Add(adrress, "正常");
                        }
                    }
                    for (int i = 0; i < 25; i++)
                    {
                        var adrress = "D" + (1141.15 + i).ToString();
                        if (inovanceTcp.ReadBool(adrress))
                        {
                            dictionary.Add(adrress, "缺料");
                        }
                        else
                        {
                            dictionary.Add(adrress, "正常");
                        }
                    }
                    for (int i = 0; i < 7; i++)
                    {
                        var adrress = "D" + (1166 + (double)i / 10).ToString("0.0");
                        if (inovanceTcp.ReadBool(adrress))
                        {
                            dictionary.Add(adrress, "缺料");
                        }
                        else
                        {
                            dictionary.Add(adrress, "正常");
                        }
                    }

                    Alarm(dictionary);
                    #endregion
                }
                catch (ObjectDisposedException ex)
                {
                    _logger.Information(ex.ToString());
                }
                finally
                {
                    Thread.Sleep(1000);
                }
            }
        }
        public void Change()
        {
            int type = inovanceTcp.ReadInt("D1000");
            switch (type)
            {
                case 0:
                    break;
                case 1:
                    proName = "P60";
                    break;
                case 2:
                    proName = "P70";
                    break;
                case 3:
                    proName = "P80";
                    break;
                case 4:
                    proName = "P90";
                    break;
            }
            if (inovanceTcp.ReadBool("D1001.0"))
            {
                SendPro("192.168.10.1", proName);
            }
            if (inovanceTcp.ReadBool("D1001.1"))
            {
                SendPro("192.168.10.2", proName);
            }
            if (inovanceTcp.ReadBool("D1001.2"))
            {
                SendPro("192.168.10.3", proName);
            }
            if (inovanceTcp.ReadBool("D1001.3"))
            {
                SendPro("192.168.10.4", proName);
            }
            if (inovanceTcp.ReadBool("D1001.4"))
            {
                SendPro("192.168.10.5", proName);
            }
            if (inovanceTcp.ReadBool("D1001.5"))
            {
                SendPro("192.168.10.6", proName);
            }
            if (inovanceTcp.ReadBool("D1001.6"))
            {
                SendPro("192.168.10.7", proName);
            }
            if (inovanceTcp.ReadBool("D1001.7"))
            {
                SendPro("192.168.10.8", proName);
            }
            if (inovanceTcp.ReadBool("D1001.8"))
            {
                SendPro("192.168.10.9", proName);
            }
            if (inovanceTcp.ReadBool("D1001.9"))
            {
                SendPro("192.168.10.10", proName);
            }
            if (inovanceTcp.ReadBool("D1001.10"))
            {
                SendPro("192.168.10.11", proName);
            }
            if (inovanceTcp.ReadBool("D1001.11"))
            {
                SendPro("192.168.10.12", proName);
            }
            if (inovanceTcp.ReadBool("D1001.12"))
            {
                SendPro("192.168.10.13", proName);
            }
            if (inovanceTcp.ReadBool("D1001.13"))
            {
                SendPro("192.168.10.14", proName);
            }
            if (inovanceTcp.ReadBool("D1001.14"))
            {
                SendPro("192.168.10.15", proName);
            }
            if (inovanceTcp.ReadBool("D1001.15"))
            {
                SendPro("192.168.10.16", proName);
            }
            if (inovanceTcp.ReadBool("D1002.0"))
            {
                SendPro("192.168.10.17", proName);
            }
            if (inovanceTcp.ReadBool("D1002.1"))
            {
                SendPro("192.168.10.18", proName);
            }

        }

        public string SelectedConfigName { get; set; }
        public ObservableCollection<string> ConfigNames { get; set; }
        public WriteableBitmap QrImage { get; set; }

        public void ReadConfig()
        {
            ConfigNames = new ObservableCollection<string>();
            if (!Directory.Exists(@"d:\作业指导书\"))
            {
                return;
            }
            var files = Directory.GetFiles(@"d:\作业指导书\");
            foreach (var item in files)
            {
                var file = new FileInfo(item);
                if (file.Extension == ".json")
                {
                    ConfigNames.Add(file.Name.Replace(file.Extension, ""));
                }
            }
        }

        #region old

        private void StopCheck(object sender, StateEventArgs e)
        {
            var modbus = _modbusTcpSlaverService.GetModbusSlaveByIp();
            //var points = modbus.DataStore.HoldingRegisters.ReadPoints(200, 1);

            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                var (errorCode, error) = _warningUpdateService.GetErrorCode(1);
                //Dialog.Show(new OeeDialogPage(), "");
                // var DialogResult = await Dialog.Show<OeeDialogPage>()
                //.Initialize<OeeDialogPageViewModel>(vm => vm.Message = "DialogResult")
                //.GetResultAsync<string>();
                var param = new DialogParameters
                {
                    { "OP_Id", Param.OPID },
                    {"ExceptionCode", errorCode}
                };
                modbus.DataStore.CoilInputs.WritePoints(12, new bool[] { true });
                _dialogService.ShowDialog("OeeDialogPage", param, async r =>
                {
                    //dialog.Parameters.Add("OP_Id", OP_Id);
                    //dialog.Parameters.Add("ExceptionCode", ExceptionCode);
                    //dialog.Parameters.Add("ExceptionContent", ExceptionContent);
                    //dialog.Parameters.Add("Duration", Duration);
                    //dialog.Parameters.Add("ExceptionTime", ExceptionTime.ToString("yyyy-mm-dd HH:mm:ss"));
                    //dialog.Parameters.Add("Mode", "手动调试模式");
                    //dialog.Parameters.Add("Reason", ExceptionReason);
                    var param = r.Parameters;
                    var opid = param.GetValue<string>("OP_Id");
                    var exceptionCodeMessage = param.GetValue<string>("ExceptionCode");
                    var exceptionCode = exceptionCodeMessage.Split('-')[0];
                    var exceptionContent = param.GetValue<string>("ExceptionContent");
                    var duration = param.GetValue<int>("Duration");
                    var exceptionTime = param.GetValue<string>("ExceptionTime");
                    var mode = param.GetValue<string>("Mode");
                    var reason = param.GetValue<string>("Reason");
                    var oeeLogger = new OeeLogger
                    {
                        site = OeeConfig.Site,
                        floor = OeeConfig.Floor,
                        product = OeeConfig.Product,
                        line = OeeConfig.Line,
                        vendor = "Team",
                        process = OeeConfig.Process,
                        terminalId = OeeConfig.TerminalId,
                        machineId = OeeConfig.MachineId,
                        status = mode,
                        op_id = opid,
                        startTime = exceptionTime,
                        ipaddr = OeeConfig.Ipaddr,
                        macaddr = OeeConfig.Macaddr,
                        warningCodeList = new Warningcodelist[2]
                    };
                    oeeLogger.warningCodeList[0] = new Warningcodelist
                    {
                        warningCode = "400002",
                        remark = exceptionContent
                    };
                    oeeLogger.warningCodeList[1] = new Warningcodelist
                    {
                        warningCode = exceptionCode,
                        remark = reason
                    };
                    await UploadOeeAsync(oeeLogger);

                    modbus.DataStore.CoilInputs.WritePoints(12, new bool[] { false });

                });
            }));
        }
        private async void ResettableTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            OeeLogger oeeLogger = new()
            {
                site = OeeConfig.Site,
                floor = OeeConfig.Floor,
                product = OeeConfig.Product,
                line = OeeConfig.Line,
                vendor = "Team",
                process = OeeConfig.Process,
                terminalId = OeeConfig.TerminalId,
                machineId = OeeConfig.MachineId,
                status = "Waiting for parts",
                op_id = Param.OPID,
                startTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                ipaddr = OeeConfig.Ipaddr,
                macaddr = OeeConfig.Macaddr,
                warningCodeList = new Warningcodelist[1]
            };
            oeeLogger.warningCodeList[0] = new Warningcodelist
            {
                warningCode = "100002",
                remark = "待料"
            };
            await UploadOeeAsync(oeeLogger);

        }
        private void WaringUpdateLogChanged(Tuple<LogType, string> tuple)
        {
            Debug.WriteLine(tuple.Item2);
            HandyControl.Controls.MessageBox.Show("test");
        }
        private void OeeConfigChanged(OeeConfig config)
        {
            OeeConfig ??= new OeeConfig();
            OeeConfig.Ip = config.Ip;
            OeeConfig.Port = config.Port;
            OeeConfig.WaitPartDuration = config.WaitPartDuration;
            OeeConfig.StopDuration = config.StopDuration;
            OeeConfig.Site = config.Site;
            OeeConfig.Floor = config.Floor;
            OeeConfig.Product = config.Product;
            OeeConfig.Line = config.Line;
            OeeConfig.Process = config.Process;
            OeeConfig.Vendor = config.Vendor;
            OeeConfig.TerminalId = config.TerminalId;
            OeeConfig.MachineId = config.MachineId;
            OeeConfig.Op_id = config.Op_id;
            OeeConfig.Ipaddr = config.Ipaddr;
            OeeConfig.Macaddr = config.Macaddr;
            OeeConfig.OeePath = config.OeePath;
            OeeConfig.UnUse = config.UnUse;
        }
        private async Task UploadOeeAsync(OeeLogger oeeLogger)
        {
            if (OeeConfig == null)
            {
                WriteLog("oee配置文件不存在请重新配置", LogType.Error);
                return;
            }
            using var client = _httpClientFactory.CreateClient();
            //var url = _appSttings.Value.OeeUrl;
            var loggingURI = $"http://{OeeConfig.Ip}:{OeeConfig.Port}/device/upload/logging/v1";

            try
            {
                var json = JsonConvert.SerializeObject(oeeLogger, Formatting.Indented);
                WriteToLocal(json);
                if (!OeeConfig.UnUse)
                {
                    client.BaseAddress = new Uri(loggingURI);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    var response = await client.PostAsync(loggingURI, content);
                    WriteLog("oee上传成功");
                    var s = await response.Content.ReadAsStringAsync();
                    WriteLog($"状态码:{response.StatusCode}:" + s, LogType.Info);
                }
                else
                {
                    WriteLog("oee上传屏蔽,未上传");
                }

            }
            catch (Exception e)
            {
                WriteLog($"oee上传失败,{e.Message}", LogType.Error);
            }
        }
        private void WriteToLocal(string json)
        {
            var name = DateTime.Now.ToString("yyyy-mm-dd-HH-mm-ss") + "_oee" + ".json";
            var path = Path.Combine(OeeConfig.OeePath, name);
            if (!Directory.Exists(OeeConfig.OeePath))
            {
                WriteLog("oee路径不存在", LogType.Error);
                return;
            }
            using var stream = new StreamWriter(path);
            stream.Write(json);
        }
        private void ClearQueue(object sender, StateEventArgs e)
        {
            var length = _upLoadTraceModels.Count;
            for (int i = 0; i < length; i++)
            {
                _upLoadTraceModels.TryDequeue(out _);
            }
        }
        private void InitTraceData()
        {
            var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "param.json");
            if (File.Exists(filePath))
            {
                using var stream = new StreamReader(filePath);
                var json = stream.ReadToEnd();
                Param = JsonConvert.DeserializeObject<Param>(json);
            }
            else
            {
                Param = new Param
                {
                    station_id = "LkYC_BO7_2F_01_002_TRACE",
                    line_id = "B07-2F-01",
                    station_vendor = "Team",
                    test = "Logo 30N Non-Destructive Test",
                    OPID = "C10088888",
                    DownLimit = "30",
                    UpperLimit = "60"
                };
            }
        }
        private void ScanMethodComplete(object sender, StateEventArgs e)
        {
            //var modbus = _modbusTcpSlaverService.GetModbusSlaveByIp();
            //modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { false });
            //WriteLog("复位扫码OK信号");
        }
        private void SaveDataCompleted(object sender, StateEventArgs e)
        {
            var modbus = _modbusTcpSlaverService.GetModbusSlaveByIp();
            modbus.DataStore.CoilInputs.WritePoints(10, new bool[] { false });
            modbus.DataStore.CoilInputs.WritePoints(11, new bool[] { false });
        }
        private void SaveImage(string barcode, string result)
        {
            var filePath = string.Empty;
            var fileName = barcode + "-" + Guid.NewGuid().ToString("N") + $"-{result}" + ".png";
            string directory = ImagePath;


            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                try
                {
                    var finalPath = Path.Combine(directory, result);
                    if (!Directory.Exists(finalPath))
                    {

                        Directory.CreateDirectory(finalPath);
                    }
                    filePath = Path.Combine(finalPath, fileName);

                    (PlotModel.PlotView as OxyPlot.Wpf.PlotView)?.SaveBitmap(filePath);
                }
                catch (Exception e)
                {
                    WriteLog($"保存图片出现异常:{e.Message}");
                }

            }));

        }
        public float ReadFloat(ushort startId)
        {
            var modbus = _modbusTcpSlaverService.GetModbusSlaveByIp();
            var data = modbus.DataStore
               .HoldingRegisters.ReadPoints((ushort)(32 + startId), 2);
            var bytes1 = BitConverter.GetBytes(data[0]);
            var bytes2 = BitConverter.GetBytes(data[1]);
            var bytes = new List<byte>();
            bytes.AddRange(bytes1);
            bytes.AddRange(bytes2);
            var value = BitConverter.ToSingle(bytes.ToArray(), 0);
            return value;
        }

        private async void ScanMethod(object sender, StateEventArgs e)
        {
            ErrorCode = string.Empty;
            var modbus = _modbusTcpSlaverService.GetModbusSlaveByIp();
            if (!ScanConnected)
            {
                WriteLog($"扫码枪未连接,无法执行扫码动作");
                ErrorCode = "扫码枪未连接,无法执行扫码动作";
                modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { false });
                return;
            }

            for (int i = 0; i < 3; i++)
            {
                try
                {
                    WriteLog($"开始第{i + 1}次扫码");
                    NewBarcode = await _scanService.ReadAsync("start");
                    WriteLog($"第{i + 1}次扫码结果:{NewBarcode}");
                    if (NewBarcode != string.Empty && (NewBarcode.ToUpper()) != "NOREAD")
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { false });
                    WriteLog($"扫码出现异常:{ex.Message}", LogType.Error, ex);
                    ErrorCode = "扫码出现异常";
                }
            }


            if (NewBarcode != string.Empty && NewBarcode.ToUpper() != "NOREAD")
            {
                // modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { true });
                WriteLog($"扫码成功,SN:{NewBarcode}");
                if (!_appSttings.Value.TraceDisable)
                {
                    var result = await GetTraceAsync(NewBarcode);
                    if (result)
                    {
                        modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { true });
                        WriteLog($"获取trace成功,SN:{NewBarcode}");
                        if (OkDuration <= 1000)
                        {
                            OkDuration = 4000;
                        }
                        await Task.Delay(OkDuration);
                        modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { false });
                    }
                    else
                    {
                        modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { false });
                        WriteLog($"trace卡关无法继续 ");
                        ErrorCode = "trace卡关校验失败";
                    }
                }
                else
                {
                    modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { true });
                    WriteLog($"卡关屏蔽中,直接放行:SN:{NewBarcode}");
                }

            }
            else
            {
                ErrorCode = $"扫码没有读取正确的二维码";
                modbus.DataStore.CoilInputs.WritePoints(9, new bool[] { false });
                WriteLog($"扫码失败:{NewBarcode}", LogType.Error);
            }
        }
        private async Task Test()
        {
            var updateModel = new UpLoadTraceModel()
            {
                serials = new Serials { part_id = UsingBarcode },
                data = new Data
                {
                    insight = new Insight
                    {
                        test_attributes = new Test_Attributes()
                        {
                            test_result = "pass",
                            uut_start = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        },
                        test_station_attributes = new Test_Station_Attributes()
                        {
                            line_id = Param.line_id,
                            software_name = "ForceTest",
                            software_version = "1.0.12",
                            station_id = Param.station_id
                        },
                        uut_attributes = new Uut_Attributes()
                        {
                            station_vendor = Param.station_vendor
                        },
                        results = new Result[1]
                        {
                            new() {
                                test=Param.test,
                                units="N"
                            }
                        }
                    }
                }
            };
            var dateName = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");
            var fileName = dateName + "-" + updateModel.serials.part_id + ".csv";
            var filePath = Path.Combine(CSVPath, fileName);
            var exsit = File.Exists(filePath);
            using var streamWriter = new StreamWriter(filePath, false, Encoding.UTF8);
            if (!exsit)
            {
                var header = "SERIAL_NUMBER,MEASURE_DATE,MEASURE_TIME,STATION,OP_NAME,AIM_VENDOR,AIM_NAME,AIM_UNIQUE," +
                    "INSPECTION_PROGRAM_NAME,PROJECT,PART,PROCESS,BUILDS,SHIFT_D_N,CAVITY,RESULT,BIN_MP,COLOR,TEMPERATURE," +
                    "HUMIDITY,PRODUCT_TEMP,COLOR_BANKING,KB_LAYOUT,DATA_BIN," +
                    "DATA1,DATA2,DATA3,DATA4,DATA5,DATA6,DATA7,DATA8,DATA9,DATA10,DATA11,DATA12,DATA13," +
                    "DATA14,DATA15,DATA16,DATA17,DATA18,DATA19,DATA20,DATA21,DATA22,DATA23,DATA24,DATA25,DATA26," +
                    "DATA27,DATA28,DATA29,DATA30,DATA31,DATA32,DATA33,DATA34,DATA35,DATA36,DATA37,DATA38,DATA39," +
                    "DATA40,DATA41,DATA42,DATA43,DATA44,DATA45,DATA46,DATA47,DATA48,DATA49,DATA50,DATA51,DATA52," +
                    "DATA53,DATA54,DATA55,DATA56,DATA57,DATA58,DATA59,DATA60,DATA61,DATA62,DATA63,DATA64,DATA65," +
                    "DATA66,DATA67,DATA68,DATA69,DATA70,DATA71,DATA72,DATA73,DATA74,DATA75," +
                    "DATA76,DATA77,DATA78,DATA79,DATA80,DATA81,DATA82,DATA83,DATA84,DATA85,DATA86,DATA87,DATA88," +
                    "DATA89,DATA90,DATA91,DATA92,DATA93,DATA94,DATA95,DATA96,DATA97,DATA98,DATA99,DATA100";
                await streamWriter.WriteLineAsync(header);
                await streamWriter.FlushAsync();
            }
            var value = $"SPC_G1/{updateModel.data.insight.results[0].value}/H{Param.UpperLimit}/L{Param.DownLimit}";
            var data = $"{updateModel.serials.part_id},{DateTime.Now:yyyy/MM/dd}" + $",{DateTime.Now:HH:mm:ss}" +
               $",logo-test,{Param.OPID},{updateModel.data.insight.uut_attributes.station_vendor}," +
               $"{_appSttings.Value.AimName},{_appSttings.Value.AIM_UNIQUE},{_appSttings.Value.INSPECTION_PROGRAM_NAME}," +
               $"{_appSttings.Value.Project},{_appSttings.Value.Part},{_appSttings.Value.Process},{_appSttings.Value.Builds},,," +
               $"{updateModel.data.insight.test_attributes.test_result},,color,,,,,,,{value}";
            var list = new List<string>();
            for (int i = 0; i < 99; i++)
            {
                data += ",";
            }
            data += "test";
            await streamWriter.WriteLineAsync(data);

            await streamWriter.FlushAsync();
            streamWriter.Close();
            WriteLog("保存csv完成");
        }
        private async Task<bool> GetTraceAsync(string barcode)
        {
            using var client = _httpClientFactory.CreateClient();
            try
            {
                var content = await client.GetStringAsync($"http://localhost:8765/v2/process_control?serial={barcode}&serial_type=part_id");
                var data = JsonConvert.DeserializeObject<Rootobject>(content);
                try
                {
                    if (string.IsNullOrWhiteSpace(barcode))
                    {
                        barcode = Guid.NewGuid().ToString("N");
                    }
                    var fileName = "request_" + barcode + ".json";
                    var path = Path.Combine("logs", fileName);
                    using var stream = new StreamWriter(path);
                    await stream.WriteLineAsync(content);
                    _logger.Information(content);
                }
                catch (Exception)
                {
                }

                if (!data.pass)
                {
                    foreach (var item in data.processes)
                    {
                        if (!item.pass)
                        {
                            WriteLog($"{item.id}:{item.name}卡关fail!", LogType.Error);
                        }

                    }
                }
                return data.pass;
            }
            catch (HttpRequestException e)
            {

                WriteLog($"请求超时失败:{e.Message}", LogType.Error, e);
                return false;
            }

        }

        private async void SaveData(object sender, StateEventArgs e)
        {
            var modbus = _modbusTcpSlaverService.GetModbusSlaveByIp();
            _upLoadTraceModels.TryDequeue(out var _updateModel);
            if (_updateModel == null)
            {
                WriteLog("_updateModel not init");
                modbus.DataStore.CoilInputs.WritePoints(10, new bool[] { false });
                modbus.DataStore.CoilInputs.WritePoints(11, new bool[] { true });
                return;
            }
            var productTestForce = ReadFloat(74);//test
            WriteLog($"读取当前压检值:{productTestForce}");
            modbus.DataStore.CoilInputs.WritePoints(10, new bool[] { false });
            modbus.DataStore.CoilInputs.WritePoints(11, new bool[] { false });
            var plcResult = modbus.DataStore.HoldingRegisters.ReadPoints(32, 1);
            var juge = plcResult[0] == 1 ? "pass" : "fail";
            _updateModel.data.insight.test_attributes.uut_stop = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            _updateModel.data.insight.test_attributes.test_result = juge;
            _updateModel.data.insight.results[0].value = productTestForce.ToString("F2");
            _updateModel.data.insight.results[0].result = juge;
            var runResult = plcResult[0] == 1 ? RunResultState.OK : RunResultState.NG;
            _eventAggregator.GetEvent<ResultEvent>().Publish(runResult);
            WriteLog("开始保存图片");
            SaveImage(_updateModel.serials.part_id, juge);
            WriteLog("保存图片完成");
            await _repository.AddAsync(new TestResult
            {
                Id = Guid.NewGuid(),
                Barcode = _updateModel.serials.part_id,
                Datetime = DateTime.Now,
                Result = productTestForce
            });
            WriteLog("开始保存csv");
            try
            {
                var dateName = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");
                var fileName = dateName + "-" + _updateModel.serials.part_id + ".csv";
                var filePath = Path.Combine(CSVPath, fileName);
                var exsit = File.Exists(filePath);
                using var streamWriter = new StreamWriter(filePath, false, Encoding.UTF8);
                if (!exsit)
                {
                    var header = "SERIAL_NUMBER,MEASURE_DATE,MEASURE_TIME,STATION,OP_NAME,AIM_VENDOR,AIM_NAME,AIM_UNIQUE," +
                        "INSPECTION_PROGRAM_NAME,PROJECT,PART,PROCESS,BUILDS,SHIFT_D_N,CAVITY,RESULT,BIN_MP,COLOR,TEMPERATURE," +
                        "HUMIDITY,PRODUCT_TEMP,COLOR_BANKING,KB_LAYOUT,DATA_BIN," +
                        "DATA1,DATA2,DATA3,DATA4,DATA5,DATA6,DATA7,DATA8,DATA9,DATA10,DATA11,DATA12,DATA13," +
                        "DATA14,DATA15,DATA16,DATA17,DATA18,DATA19,DATA20,DATA21,DATA22,DATA23,DATA24,DATA25,DATA26," +
                        "DATA27,DATA28,DATA29,DATA30,DATA31,DATA32,DATA33,DATA34,DATA35,DATA36,DATA37,DATA38,DATA39," +
                        "DATA40,DATA41,DATA42,DATA43,DATA44,DATA45,DATA46,DATA47,DATA48,DATA49,DATA50,DATA51,DATA52," +
                        "DATA53,DATA54,DATA55,DATA56,DATA57,DATA58,DATA59,DATA60,DATA61,DATA62,DATA63,DATA64,DATA65," +
                        "DATA66,DATA67,DATA68,DATA69,DATA70,DATA71,DATA72,DATA73,DATA74,DATA75," +
                        "DATA76,DATA77,DATA78,DATA79,DATA80,DATA81,DATA82,DATA83,DATA84,DATA85,DATA86,DATA87,DATA88," +
                        "DATA89,DATA90,DATA91,DATA92,DATA93,DATA94,DATA95,DATA96,DATA97,DATA98,DATA99,DATA100";
                    await streamWriter.WriteLineAsync(header);
                    await streamWriter.FlushAsync();
                }
                var value = $"SPC_G1/{_updateModel.data.insight.results[0].value}/H{Param.UpperLimit}/L{Param.DownLimit}";
                var data = $"{_updateModel.serials.part_id},{DateTime.Now:yyyy/MM/dd}" + $",{DateTime.Now:HH:mm:ss}" +
                   $",logo-test,{Param.OPID},{_updateModel.data.insight.uut_attributes.station_vendor}," +
                   $"{_appSttings.Value.AimName},{_appSttings.Value.AIM_UNIQUE},{_appSttings.Value.INSPECTION_PROGRAM_NAME}," +
                   $"{_appSttings.Value.Project},{_appSttings.Value.Part},{_appSttings.Value.Process},{_appSttings.Value.Builds},,," +
                   $"{_updateModel.data.insight.test_attributes.test_result},,color,,,,,,,{value}";
                var list = new List<string>();
                for (int i = 0; i < 99; i++)
                {
                    data += ",";
                }
                await streamWriter.WriteLineAsync(data);
                await streamWriter.FlushAsync();
                streamWriter.Close();
                WriteLog("保存csv完成");
            }
            catch (Exception ex)
            {
                WriteLog($"保存csv失败:{ex}");
            }
            WriteLog("开始上传数据");

            if (!_appSttings.Value.UnUseUpload)
            {
                var json = JsonConvert.SerializeObject(_updateModel, Formatting.Indented);
                try
                {

                    var barcode = _updateModel.serials.part_id;
                    if (string.IsNullOrWhiteSpace(barcode))
                    {
                        barcode = Guid.NewGuid().ToString("N");
                    }

                    var fileName = "upload_" + barcode + ".json";
                    var path = Path.Combine("logs", fileName);
                    using var stream = new StreamWriter(path);
                    await stream.WriteLineAsync(json);
                }
                catch (Exception)
                {
                }

                _logger.Information("正在上传数据:" + json);
                var stopWatch = new System.Diagnostics.Stopwatch();
                stopWatch.Start();
                var ret = await UploadAsync(json);

                if (stopWatch.ElapsedMilliseconds > 2000)
                {
                    _upLoadSlowTime++;
                    WriteLog($"连续{_upLoadSlowTime}上传trace数据大于2s", LogType.Warning);
                    if (_upLoadSlowTime >= 5)
                    {
                        ErrorCode = "连续5次上传数据缓慢,请检查网络连接";
                    }
                }
                else
                {
                    _upLoadSlowTime = 0;
                }
                if (ret)
                {
                    modbus.DataStore.CoilInputs.WritePoints(10, new bool[] { true });
                    modbus.DataStore.CoilInputs.WritePoints(11, new bool[] { false });
                }
                else
                {
                    modbus.DataStore.CoilInputs.WritePoints(10, new bool[] { false });
                    modbus.DataStore.CoilInputs.WritePoints(11, new bool[] { true });
                }

            }
            else
            {
                modbus.DataStore.CoilInputs.WritePoints(10, new bool[] { true });
                modbus.DataStore.CoilInputs.WritePoints(11, new bool[] { false });
            }

            OeeLogger oeeLogger = new()
            {
                site = OeeConfig.Site,
                floor = OeeConfig.Floor,
                product = OeeConfig.Product,
                line = OeeConfig.Line,
                vendor = "Team",
                process = OeeConfig.Process,
                terminalId = OeeConfig.TerminalId,
                machineId = OeeConfig.MachineId,
                status = "running",
                op_id = Param.OPID,
                startTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                ipaddr = OeeConfig.Ipaddr,
                macaddr = OeeConfig.Macaddr,
                warningCodeList = new Warningcodelist[1]
            };
            oeeLogger.warningCodeList[0] = new Warningcodelist
            {
                warningCode = "100001",
                remark = "压力检测完成"
            };
            await UploadOeeAsync(oeeLogger);

            WriteLog("上传数据完成");
        }

        //UpLoadTraceModel _updateModel;

        private async Task<bool> UploadAsync(string data)
        {
            using var client = _httpClientFactory.CreateClient();
            var stringContent = new StringContent(data);
            stringContent.Headers.ContentType = new
                System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            var statisticsLog = new StatisticsLog
            {
                Id = Guid.NewGuid(),
                Timestamp = DateTime.Now,
                RequstType = RequstType.Post
            };
            try
            {
                var responseMessage = await client.PostAsync("http://localhost:8765/v2/logs", stringContent);
                if (responseMessage.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    WriteLog($"上传数据成功");
                    statisticsLog.TraceState = TraceState.PostOK;
                    var s = await responseMessage.Content.ReadAsStringAsync();
                    WriteLog($"response:{s}");
                    statisticsLog.RequestCode = (int)responseMessage.StatusCode;
                    return true;
                }
                else
                {
                    statisticsLog.TraceState = TraceState.PostNG;
                    WriteLog($"上传失败:状态码{responseMessage.StatusCode}," +
                        $"请求uri:{responseMessage.RequestMessage.RequestUri}");
                    statisticsLog.RequestCode = (int)responseMessage.StatusCode;
                    var s = await responseMessage.Content.ReadAsStringAsync();
                    WriteLog($"response:{s}");
                    return false;
                }
            }
            catch (HttpRequestException e)
            {
                statisticsLog.TraceState = TraceState.PostNG;
                statisticsLog.RequestCode = 600;
                WriteLog($"上传失败:{e.Message}");
                return false;
            }
            finally
            {
                await _repository.AddAsync(statisticsLog);
            }

        }
        private async void StartReadForceMethod(object sender, StateEventArgs e)
        {
            WriteLog("开始读取压力传感器数值");
            UsingBarcode = NewBarcode;
            _resettableTimer.Stop();
            var updateModel = new UpLoadTraceModel()
            {
                serials = new Serials { part_id = UsingBarcode },
                data = new Data
                {
                    insight = new Insight
                    {
                        test_attributes = new Test_Attributes()
                        {
                            test_result = "pass",
                            uut_start = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        },
                        test_station_attributes = new Test_Station_Attributes()
                        {
                            line_id = Param.line_id,
                            software_name = "ForceTest",
                            software_version = "1.0.12",
                            station_id = Param.station_id
                        },
                        uut_attributes = new Uut_Attributes()
                        {
                            station_vendor = Param.station_vendor
                        },
                        results = new Result[1]
                        {
                            new() {
                                test=Param.test,
                                units="N"
                            }
                        }
                    }
                }
            };
            _upLoadTraceModels.Enqueue(updateModel);
            var modbusSlave = _modbusTcpSlaverService.GetModbusSlaveByIp();
            _start = true;
            //Clear();
            int i = 1;
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            var points = new List<DataPoint>();
            while (true)
            {
                var data = modbusSlave.DataStore.HoldingRegisters.ReadPoints(32 + 68, 2);//读取节拍
                var bytes1 = BitConverter.GetBytes(data[0]);
                var bytes2 = BitConverter.GetBytes(data[1]);
                var bytes = new List<byte>();
                bytes.AddRange(bytes1);
                bytes.AddRange(bytes2);
                var force = BitConverter.ToSingle(bytes.ToArray(), 0);
                var dataPoint = new DataPoint((++i) * 0.005, force);
                points.Add(dataPoint);
                lock (PlotModel.SyncRoot)
                {
                    //Update(dataPoint);
                }

                this.PlotModel.InvalidatePlot(true);

                if (!_start)
                {
                    break;
                }
                await Task.Delay(5);
                if (sw.ElapsedMilliseconds > 10000)
                {
                    break;
                }
            }
            _resettableTimer.Reset();
        }

        private void StopReadForceMethod(object sender, StateEventArgs e)
        {
            WriteLog("停止读取压力传感器数值");
            _start = false;

        }

        private void ModbusTcpSlaverService_CoilDiscretesHandler(object sender, LogoForceTestApp.Services.Interfaces.Events.StorageEventArgs<bool> e)
        {

        }

        //private void SetupModel()
        //{

        //    PlotModel = new PlotModel();
        //    PlotModel.Axes.Add(new LinearAxis { Position = OxyPlot.Axes.AxisPosition.Left, Minimum = 0, Maximum = 80 });


        //    PlotModel.Series.Add(new OxyPlot.Series.LineSeries { LineStyle = LineStyle.Solid });

        //    RaisePropertyChanged(nameof(PlotModel));
        //}

        //private void Clear()
        //{
        //    var s = (OxyPlot.Series.LineSeries)PlotModel.Series[0];
        //    s.Points.Clear();
        //}
        //private void Update(DataPoint dataPoint)
        //{
        //    var s = (OxyPlot.Series.LineSeries)PlotModel.Series[0];
        //    s.Points.Add(dataPoint);
        //}

        #endregion

        #region log
        private void WriteLog(string message, LogType logType = LogType.Info, Exception exception = null)
        {
            if (exception != null)
            {
                _logger.Error("{@Message}", exception.ToString());
            }
            else
            {
                _logger.Information("{@Message}", message);
            }

            string singleLine = message.Trim();
            string item = $"【{DateTime.Now:F}】 {singleLine}";
            _eventAggregator.GetEvent<LogEvent>().Publish(new Tuple<LogType, string>(logType, item));
        }
        #endregion

        #region 生成二维码

        public void QRcode()
        {
            //GenerateQRCode(InQR);
            //GenerateBarCode(InQR, 400, 150).Save("BarCode.png", System.Drawing.Imaging.ImageFormat.Png);
            
        }
        /// <summary>
        /// 生成二维码图片
        /// </summary>
        public void GenerateQRCode(string qrCodeContent)
        {
            if (qrCodeContent != null)
            {
                using (var generator = new QRCodeGenerator())
                {
                    // 创建二维码(并设置纠错能力最高级)
                    var createQrCode = generator.CreateQrCode(qrCodeContent, ECCLevel.H);

                    var skImageInfo = new SKImageInfo(300, 300);

                    // 创建SkiaSharp画布
                    using (var surface = SKSurface.Create(skImageInfo))
                    {
                        var canvas = surface.Canvas;

                        // 渲染二维码到画布
                        canvas.Render(createQrCode, skImageInfo.Width, skImageInfo.Height);

                        using var image = surface.Snapshot();// 获取画布快照
                        using var data = image.Encode(SKEncodedImageFormat.Png, 100);// 编码画布快照为PNG格式的数据
                        using (var stream = File.OpenWrite(@"MyQRCode.png"))
                        {
                            data.SaveTo(stream);// 将数据保存到文件流中,生成二维码图片
                        }
                        QrImage = image.ToWriteableBitmap();
                    }
                    WriteLog("二维码生成成功");
                }
            }
        }
        /// <summary>
        /// 生成一维条形码
        /// </summary>
        /// <param name="text">内容</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <returns></returns>
        public Bitmap GenerateBarCode(string text, int width, int height)
        {
            BarcodeWriter writer = new BarcodeWriter();
            //使用ITF 格式,不能被现在常用的支付宝、微信扫出来
            //如果想生成可识别的可以使用 CODE_128 格式
            writer.Format = BarcodeFormat.CODE_128;
            EncodingOptions options = new EncodingOptions()
            {
                Width = width,
                Height = height,
                //GS1Format = false,
                //PureBarcode = true,
                Margin = 20
            };
            writer.Options = options;

            BitMatrix bm = writer.Encode(text);
            //Bitmap b = writer.Write(bm);
            Bitmap b = writer.Write(text);
            WriteLog("一维码生成成功");
            return b;
        }
        #endregion
    }
}