
using Khd.Core.Domain.Models;
using Khd.Core.EntityFramework;
using Masuit.Tools.Logging;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Win32;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Thrift.Protocol;
using Thrift.Transport;

namespace Khd.Core.Wpf.Form
{
    /// <summary>
    /// FormBoard.xaml 的交互逻辑
    /// </summary>
    public partial class FormBoard : Window
    {
        private readonly IHost _host;
        private Khd.Core.Plc.S7.Plc _plc;
        private DispatcherTimer ShowTimer;//刷新时间
        private DispatcherTimer PLCMessage;//呈现PLC机柜信息
        private DispatcherTimer ShowOrderMessage;//呈现PLC机柜信息
        private object order_code;
        private int UpState;//对应上件站点的状态,0为良好 1为损坏
        //FormShowSelect formSelect;
        // public static int WeekNo = CommonHelper.WeekOfYear(DateTime.Now, new System.Globalization.CultureInfo("zh-CN"));

        /// <summary>
        /// 构造方法
        /// </summary>
        public FormBoard(IHost host)
        {
            InitializeComponent();
            this._host = host;
        }
        /// <summary>
        /// 页面加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormBoard_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                LogManager.Info($"--------------------------当前时间 :{DateTime.Now} >>> 客户端启动;");
                //设置显示任务栏
                if (WindowState == WindowState.Normal)
                {
                    MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight;
                    WindowState = WindowState.Maximized;
                }
                //加载dategrid信息
                LoadMaterial_GetMessage("");
                ////连接PLC判断
                //var plc = new Khd.Core.Plc.S7.Plc((CpuType)PlcConfig.CpuType, PlcConfig.IP, PlcConfig.Port,
                //PlcConfig.Rack, PlcConfig.Slot);
                //// plc.Open();
                //if (!plc.IsConnected)
                //{
                //    MessageBox.Show("PLC连接失败,重新连接");
                //}
                //else
                //{
                //    this._plc = plc;
                //}

                //ShowTimer = new System.Windows.Threading.DispatcherTimer();
                //ShowTimer.Tick += new EventHandler(ShowCurTimer);//起个Timer一直获取当前时间
                //ShowTimer.Interval = new TimeSpan(0, 0, 0, 1, 0);
                //ShowTimer.Start();

                //#region 测试client，调用wcs服务端

                ////TTransport transport = new TSocket("localhost", 9091);
                ////transport.Open();
                ////TProtocol protocol = new TBinaryProtocol(transport);
                ////WcsThrift.Client client = new WcsThrift.Client(protocol);
                ////client.hello("Sunzy");

                //#endregion

                ////启动Thriftserver
                //Thread ThriftThread = new Thread(StartThriftServer);//接收服务端的推送信息
                //ThriftThread.IsBackground = true;
                //ThriftThread.Start();

                //PLCMessage = new DispatcherTimer();
                //PLCMessage.Tick += new EventHandler(PLCmessage); //委托获取点位方法
                //PLCMessage.Interval = new TimeSpan(0, 0, 0, 0, 300);
                //PLCMessage.Start();

                ////string result = ThriftConfig.UpSite == "k46" ? " K46" : " K48";
                ////this.lab_Title.Content = (string)this.lab_Title.Content + result;

                ////载具到位状态
                //this.labzjydw.Visibility = System.Windows.Visibility.Hidden;
                //this.imgzjydw.Visibility = System.Windows.Visibility.Hidden;
                //this.labzjwdw.Visibility = System.Windows.Visibility.Visible;
                //this.imgzjwdw.Visibility = System.Windows.Visibility.Visible;

                //if (ThriftConfig.UpSite == "k48")
                //{
                //    this.spl_sunhuaizhakoumianban.Visibility = System.Windows.Visibility.Visible;
                //    using var scope = _host.Services.CreateScope();
                //    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                //    var getFlagState = dbContext.BaseAmima.Where(t => t.name == "UpState").FirstOrDefault();
                //    if (getFlagState != null)
                //    {
                //        int zhuangtai = getFlagState.password == "2" ? 2 : 1;
                //        string quxiang = getFlagState.direction == 1 ? "直通" : "弯通";
                //        if (zhuangtai == 2)
                //        {
                //            this.lab_shangjiandianzhuangtai.Content = "上件点正常!K22按照任务线别方向流转.";
                //            this.lab_shangjiandianzhuangtai.Foreground = new SolidColorBrush(Colors.Green);
                //            this.spl_sunhuaizhakouquxiang.Visibility = System.Windows.Visibility.Hidden;
                //        }
                //        else
                //        {
                //            this.lab_shangjiandianzhuangtai.Content = $"上件点损坏!人工维护去向:{quxiang}";
                //            this.lab_shangjiandianzhuangtai.Foreground = new SolidColorBrush(Colors.Red);
                //            this.spl_sunhuaizhakouquxiang.Visibility = System.Windows.Visibility.Visible;
                //        }
                //    }
                //}
                //else
                //{
                //    this.spl_sunhuaizhakoumianban.Visibility = System.Windows.Visibility.Hidden;
                //}

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        public void StartThriftServer()
        {
            try
            {
                //int point = Convert.ToInt32(ThriftConfig.JiesShouDuanKou);
                //WcsServer wcsServer = new WcsServer();
                ////wcsServer.SendCarEvent += SendCar;
                //wcsServer.helloEvent += hello;
                //WcsThrift.Processor processor = new WcsThrift.Processor(wcsServer);
                //TServerTransport serverTransport = new TServerSocket(point);
                //TServer server = new TSimpleServer(processor, serverTransport);
                //server.Serve();
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(new Action(
                    delegate
                    {
                        //设置图片为未到位
                        this.CarNo.Text = "Null";
                        this.labzjydw.Visibility = System.Windows.Visibility.Hidden;
                        this.imgzjydw.Visibility = System.Windows.Visibility.Hidden;
                        this.labzjwdw.Visibility = System.Windows.Visibility.Visible;
                        this.imgzjwdw.Visibility = System.Windows.Visibility.Visible;
                    }));
                LogManager.Error(ex);
            }

        }
        public string hello(string name)
        {
            //Console.WriteLine($"hello {name}");
            //return $"ServerResponse receive from client name:{name}";
            try
            {
                if (!string.IsNullOrWhiteSpace(name))
                {
                    Application.Current.Dispatcher.Invoke(new Action(
                     delegate
                     {
                         //设置图片为已到位、显示挂具号
                         this.CarNo.Text = name;
                         this.labzjydw.Visibility = System.Windows.Visibility.Visible;
                         this.imgzjydw.Visibility = System.Windows.Visibility.Visible;
                         this.labzjwdw.Visibility = System.Windows.Visibility.Hidden;
                         this.imgzjwdw.Visibility = System.Windows.Visibility.Hidden;
                     }));
                }
                else
                {
                    Application.Current.Dispatcher.Invoke(new Action(
                    delegate
                    {
                        //设置图片为未到位
                        //this.CarNo.Clear();
                        this.labzjydw.Visibility = System.Windows.Visibility.Hidden;
                        this.imgzjydw.Visibility = System.Windows.Visibility.Hidden;
                        this.labzjwdw.Visibility = System.Windows.Visibility.Visible;
                        this.imgzjwdw.Visibility = System.Windows.Visibility.Visible;
                    }));
                }
            }
            catch (Exception ex)
            {
                LogManager.Info($"客户端接收服务端推送的小车信息方法报错 >>> {ex.Message}");
            }
            return "";
        }

        /// <summary>
        /// 发车方法
        /// </summary>
        /// <param name="carlist"></param>
        /// <param name="order_code">Vin条码号</param>
        public void SendCar(List<string> carlist, string order_code)
        {
            TTransport transport = new TSocket(ThriftConfig.ThriftIpAddress, ThriftConfig.TuiSongDuankou);
            try
            {
                //Console.WriteLine($"hello carlist[0]:{carlist.FirstOrDefault()}|order_code:{order_code}|amount:{amount}");
                //return $"ServerResponse receive from client order_code:{order_code}";
                transport.Open();
                TProtocol protocol = new TBinaryProtocol(transport);
                WcsThrift.Client client = new WcsThrift.Client(protocol);
                //var ret = client.SendCar(carlist, order_code, order_code);
                //if (ret == "1")//与服务端交互成功发车时
                //{
                //    Application.Current.Dispatcher.Invoke(new Action(
                //                  delegate
                //                  {
                //                      //发车成功提示反馈
                //                      this.lba_ThrifTtitle.Foreground = new SolidColorBrush(Colors.Green);
                //                      this.lba_ThrifTtitle.Content = "发车成功!";
                //                      //设置为未到位 
                //                      this.labzjwdw.Visibility = System.Windows.Visibility.Visible;
                //                      this.imgzjwdw.Visibility = System.Windows.Visibility.Visible;
                //                      this.labzjydw.Visibility = System.Windows.Visibility.Hidden;
                //                      this.imgzjydw.Visibility = System.Windows.Visibility.Hidden;
                //                  }));
                //}
                //else//与服务端交互失败时
                //{

                //    Application.Current.Dispatcher.Invoke(new Action(
                //    delegate
                //    {
                //        this.lba_ThrifTtitle.Foreground = new SolidColorBrush(Colors.Red);
                //        this.lba_ThrifTtitle.Content = $"Thrift交互失败!";
                //        //发车失败依然显示到位
                //        this.labzjwdw.Visibility = System.Windows.Visibility.Hidden;
                //        this.imgzjwdw.Visibility = System.Windows.Visibility.Hidden;
                //        this.labzjydw.Visibility = System.Windows.Visibility.Visible;
                //        this.imgzjydw.Visibility = System.Windows.Visibility.Visible;
                //    }));
                //}
            }
            catch (Exception ex)
            {
                LogManager.Info($"发车方法报错 >>> {ex.Message}");
            }
            finally
            {
                transport.Close();
                transport.Dispose();
            }
        }
        /// <summary>
        /// 显示序号事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgData_LoadingRow(object sender, DataGridRowEventArgs e)
        { e.Row.Header = e.Row.GetIndex() + 1; }
        /// <summary>
        /// 显示日期事件timer
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ShowCurTimer(object sender, EventArgs e)
        {
            try
            {
                LabDate.Content = DateTime.Now.ToString("yyyy年MM月dd日");
                LabTime.Content = DateTime.Now.ToString("HH:mm:ss");
            }
            catch (Exception)
            {
            }
        }
        /// <summary>
        /// 点击退出按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            //if (MessageBox.Show("是否确认关闭程序", "提示信息", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.No)
            //{

            //}
            //else
            //{
            //    System.Environment.Exit(System.Environment.ExitCode);
            //}
            if (MessageBox.Show("是否确认关闭程序", "提示信息", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
            {
                System.Environment.Exit(System.Environment.ExitCode);
            }
        }
        private void Close(object sender, EventArgs e)
        {
            System.Environment.Exit(System.Environment.ExitCode);
        }
        /// <summary>
        /// dgData_LoadingRow 序号列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgData_LoadingRow1(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
            dynamic item = e.Row.Item;
            if (item != null)
            {
                if (order_code != null)
                {
                    if (item.order_code.Equals(order_code))
                    {
                        e.Row.Background = new SolidColorBrush(Colors.Green);
                    }
                }
            }
        }
        /// <summary>
        /// 上件操作按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnUpMenu_Click(object sender, RoutedEventArgs e)
        {
            this.UpperStart.Visibility = System.Windows.Visibility.Visible;//显示上件操作页面
            this.imgshangjiancaouzo.Source = new BitmapImage(new Uri(@"..\Resources\kucun2.png", UriKind.Relative));//上件按钮点击变选定中的蓝色
            this.splPlcMessage.Visibility = System.Windows.Visibility.Collapsed;//隐藏plc交互信息页面
            this.imgPlcMessage.Source = new BitmapImage(new Uri(@"..\Resources\caozuo.png", UriKind.Relative));//上件按钮点击变选定中的蓝色
        }
        /// <summary>
        /// PLC信息按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnPlcMessage_Click(object sender, RoutedEventArgs e)
        {
            this.UpperStart.Visibility = System.Windows.Visibility.Collapsed;//隐藏上件操作页面
            this.imgshangjiancaouzo.Source = new BitmapImage(new Uri(@"..\Resources\kucun1.png", UriKind.Relative));//上件按钮变未选中白色
            this.splPlcMessage.Visibility = System.Windows.Visibility.Visible;//显示plc交互信息页面
            this.imgPlcMessage.Source = new BitmapImage(new Uri(@"..\Resources\caozuo2.png", UriKind.Relative));//plc交互信息页面变选定中的蓝色
        }

        /// <summary>
        /// 电气机柜信息面板定时器调用方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PLCmessage(object sender, EventArgs e)
        {
            try
            {
                #region 注释代码折叠  周义帆 2023/11/16
                //string XiaoCheID = "0";
                //string GuaJuDaoWei = "0";
                //string XiaoCheQuXiang = "0";
                //string PLCChuLiZhuangTai = "0";
                //string WCSChuLiZhuangTai = "0";
                //string wcsWriteMessage = "";
                //string plcWriteMessageCLZW = "";
                //#region K02交互点
                //string plcpointAddress = "DB301.DBW0";
                ////小车ID

                //XiaoCheID = _plc.Read(plcpointAddress).ToString();
                //if (XiaoCheID != null)
                //{
                //    this.tbxK02XCID.Text = XiaoCheID;
                //}
                ////挂具到位状态
                //plcpointAddress = "DB4.DBW4";
                //GuaJuDaoWei = _plc.Read(plcpointAddress).ToString();
                //if (GuaJuDaoWei != null)
                //{
                //    this.tbxK02GJDW.Text = GuaJuDaoWei;
                //}
                ////PLC处理状态
                //plcpointAddress = "DB4.DBW6";
                //PLCChuLiZhuangTai = _plc.Read(plcpointAddress).ToString();
                //if (PLCChuLiZhuangTai != null)
                //{
                //    this.tbxK02CLZT.Text = PLCChuLiZhuangTai;
                //}
                ////挂具去向
                //plcpointAddress = "DB5.DBW4";
                //XiaoCheQuXiang = _plc.Read(plcpointAddress).ToString();
                //if (XiaoCheQuXiang != null)
                //{
                //    this.tbxK02XCQX.Text = XiaoCheQuXiang;
                //}
                ////WCS处理状态
                //plcpointAddress = "DB5.DBW6";
                //WCSChuLiZhuangTai = _plc.Read(plcpointAddress).ToString();
                //if (WCSChuLiZhuangTai != null)
                //{
                //    this.tbxK02WCSCLZT.Text = WCSChuLiZhuangTai;
                //}
                ////WCS写入物料信息
                //plcpointAddress = "DB5.DBW60";
                //wcsWriteMessage = _plc.Read(plcpointAddress).ToString();
                //if (WCSChuLiZhuangTai != null)
                //{
                //    this.tbxK02WriteMaterial.Text = wcsWriteMessage;
                //}
                ////PLC写入物料信息处理状态
                //plcpointAddress = "DB4.DBW60";
                //plcWriteMessageCLZW = _plc.Read(plcpointAddress).ToString();
                //if (WCSChuLiZhuangTai != null)
                //{
                //    this.tbxK02WriteMaterialPlc.Text = plcWriteMessageCLZW;
                //}
                //#endregion

                //#region K07交互点
                //plcpointAddress = "DB302.DBW0";
                ////小车ID
                //XiaoCheID = _plc.Read(plcpointAddress).ToString();
                //if (XiaoCheID != null)
                //{
                //    this.tbxK07XCID.Text = XiaoCheID;
                //}
                ////挂具到位状态
                //plcpointAddress = "DB4.DBW8";
                //GuaJuDaoWei = _plc.Read(plcpointAddress).ToString();
                //if (GuaJuDaoWei != null)
                //{
                //    this.tbxK07GJDW.Text = GuaJuDaoWei;
                //}
                ////PLC处理状态
                //plcpointAddress = "DB4.DBW10";
                //PLCChuLiZhuangTai = _plc.Read(plcpointAddress).ToString();
                //if (PLCChuLiZhuangTai != null)
                //{
                //    this.tbxK07CLZT.Text = PLCChuLiZhuangTai;
                //}
                ////挂具去向
                //plcpointAddress = "DB5.DBW8";
                //XiaoCheQuXiang = _plc.Read(plcpointAddress).ToString();
                //if (XiaoCheQuXiang != null)
                //{
                //    this.tbxK07XCQX.Text = XiaoCheQuXiang;
                //}
                ////WCS处理状态
                //plcpointAddress = "DB5.DBW10";
                //WCSChuLiZhuangTai = _plc.Read(plcpointAddress).ToString();
                //if (WCSChuLiZhuangTai != null)
                //{
                //    this.tbxK07WCSCLZT.Text = WCSChuLiZhuangTai;
                //}
                ////WCS写入物料信息
                //plcpointAddress = "DB5.DBW62";
                //wcsWriteMessage = _plc.Read(plcpointAddress).ToString();
                //if (WCSChuLiZhuangTai != null)
                //{
                //    this.tbxK07WriteMaterial.Text = wcsWriteMessage;
                //}
                ////PLC写入物料信息处理状态
                //plcpointAddress = "DB4.DBW62";
                //plcWriteMessageCLZW = _plc.Read(plcpointAddress).ToString();
                //if (WCSChuLiZhuangTai != null)
                //{
                //    this.tbxK07WriteMaterialPlc.Text = plcWriteMessageCLZW;
                //}
                //#endregion

                //#region K18交互点
                //plcpointAddress = "DB304.DBW0";
                ////小车ID
                //XiaoCheID = _plc.Read(plcpointAddress).ToString();
                //if (XiaoCheID != null)
                //{
                //    this.tbxK18XCID.Text = XiaoCheID;
                //}
                ////挂具到位状态
                //plcpointAddress = "DB4.DBW16";
                //GuaJuDaoWei = _plc.Read(plcpointAddress).ToString();
                //if (GuaJuDaoWei != null)
                //{
                //    this.tbxK18GJDW.Text = GuaJuDaoWei;
                //}
                ////PLC处理状态
                //plcpointAddress = "DB4.DBW18";
                //PLCChuLiZhuangTai = _plc.Read(plcpointAddress).ToString();
                //if (PLCChuLiZhuangTai != null)
                //{
                //    this.tbxK18CLZT.Text = PLCChuLiZhuangTai;
                //}
                ////挂具去向
                //plcpointAddress = "DB5.DBW16";
                //XiaoCheQuXiang = _plc.Read(plcpointAddress).ToString();
                //if (XiaoCheQuXiang != null)
                //{
                //    this.tbxK18XCQX.Text = XiaoCheQuXiang;
                //}
                ////WCS处理状态
                //plcpointAddress = "DB5.DBW18";
                //WCSChuLiZhuangTai = _plc.Read(plcpointAddress).ToString();
                //if (WCSChuLiZhuangTai != null)
                //{
                //    this.tbxK18WCSCLZT.Text = WCSChuLiZhuangTai;
                //}
                //#endregion

                //#region K22交互点
                //plcpointAddress = "DB306.DBW0";
                ////小车ID
                //XiaoCheID = _plc.Read(plcpointAddress).ToString();
                //if (XiaoCheID != null)
                //{
                //    this.tbxK22XCID.Text = XiaoCheID;
                //}
                ////挂具到位状态
                //plcpointAddress = "DB4.DBW24";
                //GuaJuDaoWei = _plc.Read(plcpointAddress).ToString();
                //if (GuaJuDaoWei != null)
                //{
                //    this.tbxK22GJDW.Text = GuaJuDaoWei;
                //}
                ////PLC处理状态
                //plcpointAddress = "DB4.DBW26";
                //PLCChuLiZhuangTai = _plc.Read(plcpointAddress).ToString();
                //if (PLCChuLiZhuangTai != null)
                //{
                //    this.tbxK22CLZT.Text = PLCChuLiZhuangTai;
                //}
                ////挂具去向
                //plcpointAddress = "DB5.DBW24";
                //XiaoCheQuXiang = _plc.Read(plcpointAddress).ToString();
                //if (XiaoCheQuXiang != null)
                //{
                //    this.tbxK22XCQX.Text = XiaoCheQuXiang;
                //}
                ////WCS处理状态
                //plcpointAddress = "DB5.DBW26";
                //WCSChuLiZhuangTai = _plc.Read(plcpointAddress).ToString();
                //if (WCSChuLiZhuangTai != null)
                //{
                //    this.tbxK22WCSCLZT.Text = WCSChuLiZhuangTai;
                //}
                //#endregion

                //#region K46交互点
                //plcpointAddress = "DB307.DBW0";
                ////小车ID
                //XiaoCheID = _plc.Read(plcpointAddress).ToString();
                //if (XiaoCheID != null)
                //{
                //    this.tbxK46XCID.Text = XiaoCheID;
                //}
                ////挂具到位状态
                //plcpointAddress = "DB4.DBW28";
                //GuaJuDaoWei = _plc.Read(plcpointAddress).ToString();
                //if (GuaJuDaoWei != null)
                //{
                //    this.tbxK46GJDW.Text = GuaJuDaoWei;
                //}
                ////PLC处理状态
                //plcpointAddress = "DB4.DBW30";
                //PLCChuLiZhuangTai = _plc.Read(plcpointAddress).ToString();
                //if (PLCChuLiZhuangTai != null)
                //{
                //    this.tbxK46CLZT.Text = PLCChuLiZhuangTai;
                //}
                ////挂具去向
                //plcpointAddress = "DB5.DBW28";
                //XiaoCheQuXiang = _plc.Read(plcpointAddress).ToString();
                //if (XiaoCheQuXiang != null)
                //{
                //    this.tbxK46XCQX.Text = XiaoCheQuXiang;
                //}
                ////WCS处理状态
                //plcpointAddress = "DB5.DBW30";
                //WCSChuLiZhuangTai = _plc.Read(plcpointAddress).ToString();
                //if (WCSChuLiZhuangTai != null)
                //{
                //    this.tbxK46WCSCLZT.Text = WCSChuLiZhuangTai;
                //}
                ////WCS写入物料信息
                //plcpointAddress = "DB5.DBW64";
                //wcsWriteMessage = _plc.Read(plcpointAddress).ToString();
                //if (WCSChuLiZhuangTai != null)
                //{
                //    this.tbxK46WriteMaterial.Text = wcsWriteMessage;
                //}
                ////PLC写入物料信息处理状态
                //plcpointAddress = "DB4.DBW64";
                //plcWriteMessageCLZW = _plc.Read(plcpointAddress).ToString();
                //if (WCSChuLiZhuangTai != null)
                //{
                //    this.tbxK46WriteMaterialPlc.Text = plcWriteMessageCLZW;
                //}
                //#endregion

                //#region K48交互点
                //plcpointAddress = "DB308.DBW0";
                ////小车ID
                //XiaoCheID = _plc.Read(plcpointAddress).ToString();
                //if (XiaoCheID != null)
                //{
                //    this.tbxK48XCID.Text = XiaoCheID;
                //}
                ////挂具到位状态
                //plcpointAddress = "DB4.DBW32";
                //GuaJuDaoWei = _plc.Read(plcpointAddress).ToString();
                //if (GuaJuDaoWei != null)
                //{
                //    this.tbxK48GJDW.Text = GuaJuDaoWei;
                //}
                ////PLC处理状态
                //plcpointAddress = "DB4.DBW34";
                //PLCChuLiZhuangTai = _plc.Read(plcpointAddress).ToString();
                //if (PLCChuLiZhuangTai != null)
                //{
                //    this.tbxK48CLZT.Text = PLCChuLiZhuangTai;
                //}
                ////挂具去向
                //plcpointAddress = "DB5.DBW32";
                //XiaoCheQuXiang = _plc.Read(plcpointAddress).ToString();
                //if (XiaoCheQuXiang != null)
                //{
                //    this.tbxK48XCQX.Text = XiaoCheQuXiang;
                //}
                ////WCS处理状态
                //plcpointAddress = "DB5.DBW34";
                //WCSChuLiZhuangTai = _plc.Read(plcpointAddress).ToString();
                //if (WCSChuLiZhuangTai != null)
                //{
                //    this.tbxK48WCSCLZT.Text = WCSChuLiZhuangTai;
                //}
                ////WCS写入物料信息
                //plcpointAddress = "DB5.DBW66";
                //wcsWriteMessage = _plc.Read(plcpointAddress).ToString();
                //if (WCSChuLiZhuangTai != null)
                //{
                //    this.tbxK48WriteMaterial.Text = wcsWriteMessage;
                //}
                ////PLC写入物料信息处理状态
                //plcpointAddress = "DB4.DBW66";
                //plcWriteMessageCLZW = _plc.Read(plcpointAddress).ToString();
                //if (WCSChuLiZhuangTai != null)
                //{
                //    this.tbxK48WriteMaterialPlc.Text = plcWriteMessageCLZW;
                //}
                //#endregion
                #endregion

                // 调用方法，传递 K02 交互点的信息
                ReadPlcData("DB301.DBW0", 1, "2", tbxK02XCID, tbxK02GJDW, tbxK02CLZT, tbxK02XCQX, tbxK02WCSCLZT);
                // 调用方法，传递 K07 交互点的信息
                ReadPlcData("DB302.DBW0", 1, "2", tbxK07XCID, tbxK07GJDW, tbxK07CLZT, tbxK07XCQX, tbxK07WCSCLZT);
                // 调用方法，传递 K18 交互点的信息
                ReadPlcData("DB304.DBW0", 1, "2", tbxK18XCID, tbxK18GJDW, tbxK18CLZT, tbxK18XCQX, tbxK18WCSCLZT);
                // 调用方法，传递 K22 交互点的信息
                ReadPlcData("DB306.DBW0", 1, "2", tbxK22XCID, tbxK22GJDW, tbxK22CLZT, tbxK22XCQX, tbxK22WCSCLZT);
                // 调用方法，传递 K46 交互点的信息
                ReadPlcData("DB307.DBW0", 1, "2", tbxK46XCID, tbxK46GJDW, tbxK46CLZT, tbxK46XCQX, tbxK46WCSCLZT);
                // 调用方法，传递 K48 交互点的信息
                ReadPlcData("DB308.DBW0", 1, "2", tbxK48XCID, tbxK48GJDW, tbxK48CLZT, tbxK48XCQX, tbxK48WCSCLZT);

                #region 1号上件点给PLC信息
                ReadAndUpdatePlcData("DB5.DBW60", "DB4.DBW60", tbxK48WriteMaterial, tbxK48WriteMaterialPlc);
                #endregion

                #region 2号上件点给PLC信息
                ReadAndUpdatePlcData("DB5.DBW62", "DB4.DBW62", tbxK46WriteMaterial, tbxK46WriteMaterialPlc);
                #endregion

                #region 1线下件点给PLC信息
                ReadAndUpdatePlcData("DB5.DBW64", "DB4.DBW64", tbxK07WriteMaterial, tbxK07WriteMaterialPlc);
                #endregion

                #region 2线上件点给PLC信息
                ReadAndUpdatePlcData("DB5.DBW66", "DB4.DBW66", tbxK02WriteMaterial, tbxK02WriteMaterialPlc);
                #endregion

                #region 嵌套方法折叠
                void ReadAndUpdatePlcData(string addressWcs, string addressPlc, TextBox textBoxMaterial, TextBox textBoxMaterialPlc)
                {
                    // WCS键入物料信息
                    string wcsChuLiZhuangTai = _plc.Read(addressWcs).ToString();
                    if (wcsChuLiZhuangTai != null && !textBoxMaterial.IsFocused)
                    {
                        textBoxMaterial.Text = wcsChuLiZhuangTai;
                    }

                    // PLC接收键入物料信息状态
                    string chuLiZhuangTai = _plc.Read(addressPlc).ToString();
                    if (chuLiZhuangTai != null)
                    {
                        textBoxMaterialPlc.Text = chuLiZhuangTai;
                    }
                }
                #endregion

                //显示K46上件点状态
                string K46UpState = _plc.Read("DB4.DBW70").ToString();
                if (K46UpState != null && !this.tbx_K46State.IsFocused)
                {
                    string k46state = K46UpState == "1" ? "启用上件" : "直接放行";
                    this.tbx_K46State.Text = k46state;
                }
                //显示K48上件点状态
                string K48UpState = _plc.Read("DB4.DBW72").ToString();
                if (K48UpState != null && !this.tbx_K48State.IsFocused)
                {
                    string k48state = K48UpState == "1" ? "启用上件" : "直接放行";
                    this.tbx_K48State.Text = k48state;
                }
                string state = ThriftConfig.UpSite == "k46" ? K46UpState : K48UpState;
                string result = state == "1" ? "启用上件" : "直接放行";
                this.lab_Title.Content = $"上件点:{ThriftConfig.UpSite},使用模式:{result}";
                this.tBoxMessage.IsEnabled = state == "1" ? true : false;
            }
            catch (Exception ex)
            {
                LogManager.Info($"电气机柜信息面板定时器调用方法报错 >>> {ex.Message}");
            }
        }

        /// <summary>
        /// PLC读取方法封装
        /// </summary>
        /// <param name="plcAddress">plc地址位</param>
        /// <param name="plcDataType">plc数据类型(int类型默认为1)</param>
        /// <param name="plcValueLength">plc地址位长度(string类型默认为2)</param>
        /// <param name="textBoxXcid">载具号文本输入框</param>
        /// <param name="textBoxGjdw">载具到位文本输入框</param>
        /// <param name="textBoxClzt">PLC车辆状态文本输入框</param>
        /// <param name="textBoxXcqx">载具去向文本输入框</param>
        /// <param name="textBoxWcsclzt">WCS处理状态文本输入框</param>
        private void ReadPlcData(string plcAddress, int plcDataType, string plcValueLength,
                      TextBox textBoxXcid, TextBox textBoxGjdw, TextBox textBoxClzt,
                      TextBox textBoxXcqx, TextBox textBoxWcsclzt)
        {
            try
            {
                // 载具号
                ReadAndSetText(plcAddress, textBoxXcid);

                // 载具到位
                //DQXX.plcpointAddress = $"DB4.DBW{GetOffset(plcAddress, 0)}";
                string gjdw = $"DB4.DBW{GetOffset(plcAddress, 0)}";
                ReadAndSetText(gjdw, textBoxGjdw);

                // PLC处理状态
                //DQXX.plcpointAddress = $"DB4.DBW{GetOffset(plcAddress, 2)}";
                string plcclzt = $"DB4.DBW{GetOffset(plcAddress, 2)}";
                ReadAndSetText(plcclzt, textBoxClzt);

                // 小车去向
                //DQXX.plcpointAddress = $"DB5.DBW{GetOffset(plcAddress, 0)}";
                string xcqx = $"DB5.DBW{GetOffset(plcAddress, 0)}";
                ReadAndSetText(xcqx, textBoxXcqx, textBoxXcqx.IsFocused);

                // WCS处理完成
                //DQXX.plcpointAddress = $"DB5.DBW{GetOffset(plcAddress, 2)}";
                string wcsclzt = $"DB5.DBW{GetOffset(plcAddress, 2)}";
                ReadAndSetText(wcsclzt, textBoxWcsclzt, textBoxWcsclzt.IsFocused);
                //-------------------------------------------------------------------------以下为方法内部嵌套方法
                //嵌套方法1
                void ReadAndSetText(string dw, TextBox textBox, bool checkFocus = false)
                {
                    string value = _plc.Read(dw).ToString();
                    if (value != null && (!checkFocus || !textBox.IsFocused))
                    {
                        textBox.Text = value;
                    }
                }
                //嵌套方法2
                int GetOffset(string PlcAddress, int baseOffset)
                {
                    int result = int.Parse(PlcAddress.Substring(4, 1)) * 4 + baseOffset;
                    return result;
                }

            }
            catch (Exception ex)
            {
                LogManager.Info($"PLC读取方法封装报错 >>> {ex.Message}");
            }

        }
        /// <summary>
        /// 清除信息按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnsendNullCar_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.tBoxMessage.Clear();
                this.tbx_CheLiangChangDu.Clear();
                this.lba_ThrifTtitle.Content = string.Empty;
            }
            catch (Exception)
            {
            }
        }
        /// <summary>
        /// 使用DataTable当做数据传递中介向DataGrid中传输数据源
        /// </summary>
        private void LoadMaterial_GetMessage(string wheresql)
        {
            try
            {
                string pjsql = string.IsNullOrEmpty(wheresql) ? "" : $"where order_code like '%{wheresql}'";
                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                string sql = $@"SELECT
                                line_code AS lineCode,   
                                order_code AS orderCode,   
                                prod_code AS prodCode,  
                                est,  
                                IsOver AS isover
                                FROM base_production_order_split
                                {pjsql}
                                ORDER BY IsOver , est ;";
                var QueryOrder = dbContext.ExecuteSqlQuery<BaseProductionOrderSplit>(sql);
                #region 注释代码折叠
                //string sql = ($@"SELECT   

                //      a.line_code AS lineCode,   

                //      a.order_code AS orderCode,   

                //      a.prod_code AS prodCode,  

                //      a.est,  

                //      a.IsOver AS isover,   

                //     CONVERT(b.downline, CHAR) AS siteCode 

                //    FROM base_production_order_split a  

                //    LEFT JOIN base_waitdownline b  

                //    ON a.order_code = b.materiel_no {pjsql} ORDER BY est ,IsOver ");
                //var QueryOrder = dbContext.BaseProductionOrderSplit.OrderBy(t => t.est).OrderBy(t => t.isover).ToList();
                #endregion
                if (QueryOrder?.Count > 0)
                {
                    DataTable dt = new DataTable();
                    dt.Columns.Add("order_code");
                    dt.Columns.Add("prod_code");
                    dt.Columns.Add("line_code");
                    dt.Columns.Add("est");
                    dt.Columns.Add("isover");
                    foreach (var i in QueryOrder)
                    {
                        DataRow dr = dt.NewRow();
                        dr["order_code"] = i.orderCode.ToString();
                        dr["prod_code"] = i.prodCode.ToString();
                        dr["line_code"] = i.lineCode.ToString();
                        dr["est"] = i.est.ToString();
                        dr["isover"] = i.isover.ToString();
                        switch (i.isover)
                        {
                            case 0:
                                dr["isover"] = "未上线";
                                break;
                            case 1:
                                dr["isover"] = "已上线";
                                break;
                            case 2:
                                dr["isover"] = "已完成";
                                break;
                            default:
                                dr["isover"] = "状态错误!";
                                break;
                        }
                        dt.Rows.Add(dr);
                    }
                    this.LoadMaterial.ItemsSource = dt.DefaultView;
                    this.LoadMaterial.Items.Refresh();
                }
            }
            catch (Exception ex)
            {
                LogManager.Info($"dagird获取信息报错1 >>> {ex.Message}");
            }

        }

        /// <summary>
        /// 查询按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ChaXunButton_Click(object sender, RoutedEventArgs e)
        {
            string vin = this.MoHuChaXunWuLiaoName.Text.Trim().ToUpper().ToString();
            this.LoadMaterial.ItemsSource = null;
            LoadMaterial_GetMessage(vin);
        }
        /// <summary>
        /// 清空按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QingKongButton_Click(object sender, RoutedEventArgs e)
        {
            this.MoHuChaXunWuLiaoName.Clear();
            this.LoadMaterial.ItemsSource = null;
            LoadMaterial_GetMessage("");
        }
        /// <summary>
        /// 上件点状态损坏确认按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_shangjiansunhuai_Click(object sender, RoutedEventArgs e)
        {
            //this.spl_sunhuaizhakouquxiang.Visibility = System.Windows.Visibility.Visible;
            //using var scope = _host.Services.CreateScope();
            //using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            //dbContext.BaseAmima.Where(t => t.name == "UpState").Update(a => new BaseAmima() { password = "1" });
            //var data = dbContext.BaseAmima.Where(t => t.name == "UpState").FirstOrDefault();
            //string quxiang = data.direction == 1 ? "直通" : "弯通";
            //this.lab_shangjiandianzhuangtai.Content = $"上件点状态:损坏!K22固定去向:" + quxiang;
            //this.lab_shangjiandianzhuangtai.Foreground = new SolidColorBrush(Colors.Red);
        }
        /// <summary>
        /// 上件点状态良好确认按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_shangjianweixiu_click(object sender, RoutedEventArgs e)
        {
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            this.lab_shangjiandianzhuangtai.Content = $"上件点状态:正常!K22走任务线别去向!";
            this.lab_shangjiandianzhuangtai.Foreground = new SolidColorBrush(Colors.Green);
            this.spl_sunhuaizhakouquxiang.Visibility = System.Windows.Visibility.Hidden;
            // dbContext.BaseAmima.Where(t => t.name == "UpState").Update(a => new BaseAmima() { password = "2" });
        }
        /// <summary>
        /// 上件点状态维护损坏后固定K22去向1
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_K22QuXiang1_Click(object sender, RoutedEventArgs e)
        {
            //this.spl_sunhuaizhakouquxiang.Visibility = System.Windows.Visibility.Visible;
            //using var scope = _host.Services.CreateScope();
            //using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            //dbContext.BaseAmima.Where(t => t.name == "UpState").Update(a => new BaseAmima() { direction = 1 });
            //Btn_shangjiansunhuai_Click(null, null);
        }

        /// <summary>
        /// 上件点状态维护损坏后固定K22去向2
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_K22QuXiang2_Click(object sender, RoutedEventArgs e)
        {
            this.spl_sunhuaizhakouquxiang.Visibility = System.Windows.Visibility.Visible;
            using var scope = _host.Services.CreateScope();
            using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
            //dbContext.BaseAmima.Where(t => t.name == "UpState").Update(a => new BaseAmima() { direction = 2 });
            Btn_shangjiansunhuai_Click(null, null);
        }
        /// <summary>
        /// 修改车身长度信息点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnXiuGaiCheShenChangDu_Click(object sender, RoutedEventArgs e)
        {
            CheShenChangDuGuanLi cscdgl = new(_host);
            cscdgl.Show();
        }
        /// <summary>
        /// 扫码枪扫码后发车操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtInput_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //输入字符长度为17且有回车按键响应
                if (this.tBoxMessage.Text.Trim().Length == 17 && e.Key == Key.Enter)
                {
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    string VinResult = this.tBoxMessage.Text.Trim().ToUpper().ToString();
                    //var orderModel = dbContext.BaseProductionOrderSplit.Where(t => t.orderCode == VinResult).FirstOrDefault();
                    //if (orderModel == null)
                    //{
                    //    MessageBox.Show($"该VIN条码:{VinResult}未搜索到对应订单!");
                    //    return;
                    //}
                    //if (orderModel.isover != 0)
                    //{
                    //    if (orderModel.isover == 1) MessageBox.Show($"该Vin条码:{VinResult}对应订单已上线!", "发车错误提示!");
                    //    if (orderModel.isover == 2) MessageBox.Show($"该Vin条码:{VinResult}对应订单已下线完成!", "发车错误提示!");
                    //    return;
                    //}
                    // var waitdownlineModel = dbContext.BaseWaitdownline.Where(t => t.definefield1 == orderModel.lineCode).ToList();
                    //int FlagNum = waitdownlineModel.Count();
                    //if (FlagNum >= FlagConfig.UpFlagNum)
                    //{
                    //    MessageBox.Show($"已上线数量:{FlagNum}>=缓存闸口设置数量:{FlagConfig.UpFlagNum},限制发车操作!", "发车错误提示!");
                    //    LogManager.Info($"当前时间:{DateTime.Now},物料:{orderModel.orderCode},线别:{orderModel.lineCode},数量:{FlagNum} >= 缓存数量:{FlagConfig.UpFlagNum},限制发车操作!");
                    //    return;
                    //}
                    string sqlQuery = @$"
                                    SELECT 
                                        b1.material_no AS materialNo, 
                                        b1.k46up_length AS k46upLength,
                                        b1.k48up_length AS k48upLength,
                                        b1.down_length AS downLength, 
                                        b2.order_code AS definefield1,
                                        b2.line_code AS definefield2,
                                        b2.prod_code AS definefield3
                                    FROM 
                                        base_materialinfo b1
                                        JOIN base_production_order_split b2 
                                        ON b2.prod_code LIKE CONCAT('%', b1.material_no, '%')
                                    WHERE 
                                        b2.order_code = '{VinResult}'";
                    var QueryOrder = dbContext.ExecuteSqlQuery<BaseMaterialinfo>(sqlQuery);
                    #region 周义帆 20231202 注释sql折叠
                    //(@$"SELECT b1.material_no as materialNo, 
                    //b1.k46up_length as k46upLength,
                    //b1.k48up_length as k48upLength,
                    //b1.down_length as downLength, 
                    //b2.order_code as definefield1,
                    //b2.line_code as definefield2,
                    //b2.prod_code as definefield3
                    //FROM base_materialinfo b1
                    //JOIN base_production_order_split b2 ON b2.prod_code LIKE CONCAT('%', b1.material_no, '%')
                    //WHERE b2.order_code = '{vinText}'; ");
                    #endregion
                    if (QueryOrder?.Count == 0)
                    {
                        MessageBox.Show($"未查找到Vin:{VinResult}对应车型", "发车错误提示!");
                        return;
                    }
                    string changduText = ThriftConfig.UpSite == "k46" ? QueryOrder[0].k46upLength : QueryOrder[0].k48upLength;
                    if (string.IsNullOrWhiteSpace(changduText))
                    {
                        MessageBox.Show($"未查找到Vin:{VinResult}对应车型长度", "发车错误提示!");
                        return;
                    }
                    string carId = this.CarNo.Text;
                    if (string.IsNullOrWhiteSpace(carId))
                    {
                        MessageBox.Show($"挂具号为空!", "发车错误提示!");
                        return;
                    }
                    string zhandianText = ThriftConfig.UpSite == "k46" ? "K46" : "K48";
                    List<string> carList = new()
                    {
                    $"上件站点 >>> {zhandianText}"
                    };
                    SendCar(carList, VinResult);
                    LogManager.Info($"当前时间;{DateTime.Now},发车方法调用记录 >>> 挂具ID:{carId},上件站点:{carList[0]} , Vin条码号:{VinResult},车身长度:{changduText}");
                    carList.Clear();
                    //this.LoadMaterial.Items.Refresh();
                    this.LoadMaterial.ItemsSource = null;
                    LoadMaterial_GetMessage("");
                }
                else if (this.tBoxMessage.Text.Trim().Length < 17 && e.Key == Key.Enter)
                {
                    MessageBox.Show($"输入Vin条码:{this.tBoxMessage.Text.Trim()}长度有误!");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"扫码发车方法报错 >>> {ex.Message}");
            }
        }
        /// <summary>
        /// 订单导入按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_dingdandaoru_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Application.Current.Dispatcher.Invoke(new Action(
                delegate
                {
                    // 设置 EPPlus 许可上下文
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                    OpenFileDialog openFileDialog = new OpenFileDialog();
                    openFileDialog.Filter = "Excel Files|*.xls;*.xlsx";
                    if (openFileDialog.ShowDialog() == true)
                    {
                        FileInfo fileInfo = new FileInfo(openFileDialog.FileName);

                        using (ExcelPackage package = new ExcelPackage(fileInfo))
                        {
                            ExcelWorksheet worksheet = package.Workbook.Worksheets.FirstOrDefault();

                            if (worksheet != null)
                            {
                                // 获取 Excel 表头
                                var columnHeaders = worksheet.Cells[1, 1, 1, worksheet.Dimension.End.Column]
                                    .Select(cell => cell.Text)
                                    .ToList();
                                BaseProductionOrderSplit orderMoedel = new();
                                // 映射数据库字段，这里需要根据你的实际需求进行调整
                                var columnMappings = new Dictionary<string, string>
                                {
                                // 添加映射
                                {columnHeaders[0],"production_sequence"},
                                {columnHeaders[1],"line_code"},
                                {columnHeaders[3],"prod_code"},
                                {columnHeaders[4],"Quantity"},
                                {columnHeaders[5],"order_code"}
                                };
                                int ordernum = 0;
                                // 获取实际的行数和列数
                                int rowCount = worksheet.Dimension.Rows;
                                int colCount = worksheet.Dimension.Columns;
                                // 遍历 Excel 数据行
                                for (int row = 2; row <= rowCount; row++)
                                {
                                    // 创建 SQL 插入语句
                                    //string insertCommand = $"INSERT INTO YourTableName ({string.Join(", ", columnMappings.Values)}) VALUES (";
                                    List<string> values = new();
                                    // 遍历 Excel 数据列
                                    for (int col = 1; col <= colCount; col++)
                                    {
                                        string columnName = columnHeaders[col - 1];
                                        string databaseColumnName;
                                        // 映射 Excel 列名到数据库列名
                                        if (columnMappings.TryGetValue(columnName, out databaseColumnName))
                                        {
                                            // 获取 Excel 单元格的值
                                            var cellValue = worksheet.Cells[row, col].Text;
                                            // 添加值到插入语句
                                            values.Add(cellValue);
                                            //values.Add($"'{cellValue.Replace("'", "''")}'");
                                            //if (!string.IsNullOrWhiteSpace(cellValue))
                                            //{
                                            //    values.Add(cellValue);
                                            //}
                                        }
                                    }
                                    // 使用 LINQ 查询空值
                                    bool containsNull = values.Any(item => item == "" || item == null);
                                    if (containsNull)
                                    {
                                        //MessageBox.Show("Excel表格中存在空值,不执行导入操作!", "订单导入操作提示!");
                                        //LogManager.Info($"订单导入按钮事件错误 >>> Excel表格中存在空值!不执行导入操作!");
                                        break;
                                    }
                                    // 获得插入语句
                                    //string fullInsertCommand = $"{insertCommand} {string.Join(", ", values)} )";
                                    var xianbiename = Char.GetNumericValue(values[1][values[1].Length - 1]).ToString();
                                    int orderSequence = int.Parse(values[0].Trim());
                                    using var scope = _host.Services.CreateScope();
                                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                                    // var orderModel = dbContext.BaseProductionOrderSplit.OrderBy(t => t.productionSequence).ToList();
                                    //var data = orderModel.Find(t => t.orderCode == values[4].Trim().ToUpper());
                                    //if (data == null)
                                    //{
                                    //    BaseProductionOrderSplit InserOrderModel = new()
                                    //    {
                                    //        id = Guid.NewGuid().ToString(),
                                    //        lineCode = values[1].Trim(),
                                    //        lineName = xianbiename == "1" ? "二线" : "一线",
                                    //        orderCode = values[4].Trim().ToUpper(),
                                    //        prodCode = values[2].Trim(),
                                    //        prodDesc = values[2].Trim(),
                                    //        productionSequence = orderSequence,
                                    //        est = DateTime.Now,
                                    //        isover = 0,
                                    //        quantity = 1,
                                    //        createBy = "ExcelInsert"
                                    //    };
                                    //    dbContext.Add(InserOrderModel);
                                    //    dbContext.SaveChanges();
                                    //    ordernum++;
                                    //}
                                }

                                MessageBox.Show($"{ordernum}条订单导入系统!", "订单导入操作提示!");
                                this.LoadMaterial.ItemsSource = null;
                                LoadMaterial_GetMessage("");
                            }
                        }
                    }
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show($"订单导入失败 >>> {ex.Message}", "订单导入操作提示!");
                LogManager.Info($"按钮订单导入事件报错 >>> {ex.Message}");
            }
        }
        /// <summary>
        /// 接收到载具号后,清空残留信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CarNo_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(this.tBoxMessage.Text) && this.tBoxMessage.Text.Length == 17)
            {
                //清空缓存信息
                this.CarNo.Clear();
                this.tBoxMessage.Clear();
                this.tbx_CheLiangChangDu.Clear();
                this.lba_ThrifTtitle.Content = string.Empty;
            }
        }
        /// <summary>
        /// 订单清空按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ClearOrder_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var data = this.LoadMaterial.ItemsSource;
                if (data == null)
                {
                    MessageBox.Show($"当前订单信息为空,无需清空操作!", "订单手动清空提示!");
                    return;
                }
                if (MessageBox.Show("确认是否清空当前预存订单?",
                    "订单手动清空提示",
                    MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                {
                    using var scope = _host.Services.CreateScope();
                    using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                    string sqlQuery = @"INSERT INTO 
                                        base_production_order_split_bak 
                                        (id,site_code, line_code, line_name, order_code,prod_code,prod_desc,IsOver,est,Quantity,production_sequence)
                                        SELECT 
                                        id,site_code, line_code, line_name, order_code,prod_code,prod_desc,IsOver,est,Quantity,production_sequence
                                        FROM base_production_order_split;";
                    string sqlDelete = @"Delete
                                        FROM
                                        base_production_order_split;";
                    var ret = dbContext.Database.ExecuteSqlRaw(sqlQuery);
                    dbContext.Database.ExecuteSqlRaw(sqlDelete);
                    string zhandianText = ThriftConfig.UpSite == "k46" ? "K46" : "K48";
                    string saveLog = ret == 0 ? "清空后备份任务SQL执行失败!" : "清空后备份任务SQL语句执行成功!";
                    if (ret != 0) MessageBox.Show($"{ret}条订单清空完毕!", "订单清空提示!");
                    LogManager.Info($"手动清空任务日志记录 >>> 站点:{zhandianText}{saveLog}");
                    this.LoadMaterial.ItemsSource = null;
                    LoadMaterial_GetMessage("");
                }
            }
            catch (Exception ex)
            {
                LogManager.Info($"手动清空任务方法报错 >>> {ex.Message}");
            }
        }
        /// <summary>
        /// 查询挂具绑定Vin物料点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_ChaXunByCarNo_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(this.tbx_JieBangByCarNo.Text))
                {
                    MessageBox.Show("上线挂具号输入框为空!", "查询挂具物料绑定关系操作提示!");
                    return;
                }
                if (!Regex.IsMatch(this.tbx_JieBangByCarNo.Text, @"^\d+$"))
                {
                    MessageBox.Show("挂具号输入格式有误!", "查询挂具物料绑定关系操作提示!");
                    this.tbx_JieBangByVin.Clear();
                    return;
                    //textBox.Text = textBox.Text.Replace("非数字字符", ""); // 移除非数字字符  
                }
                if (this.tbx_JieBangByCarNo.Text.Length >= 3)
                {
                    MessageBox.Show("挂具号输入长度有误!", "查询挂具物料绑定关系操作提示!");
                    this.tbx_JieBangByVin.Clear();
                    return;
                }
                int ShuRuCarNo = int.Parse(this.tbx_JieBangByCarNo.Text);
                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                //var listWaitDownLine = dbContext.BaseWaitdownline.Where(t => t.isDelete == 0 && t.carNo == ShuRuCarNo).ToList();
                //if (string.IsNullOrWhiteSpace(listWaitDownLine[0].materielNo))
                //{
                //    MessageBox.Show($"{ShuRuCarNo}号为空挂具,不存在与Vin绑定信息!", "查询挂具物料绑定关系操作提示!");
                //    return;
                //}
                // var listOrder = dbContext.BaseProductionOrderSplit.Where(t => t.orderCode == listWaitDownLine[0].materielNo).ToList();
                //var resultOrderList = (from waitdownline in listWaitDownLine
                //                       join order in listOrder on waitdownline.materielNo equals order.orderCode
                //                       select new BaseProductionOrderSplit
                //                       {
                //                           id = order.id,
                //                           lineCode = order.lineCode,
                //                           orderCode = order.orderCode
                //                       }).ToList();
                //if (resultOrderList?.Count > 0)
                //{
                //    this.tbx_JieBangByVin.Text = resultOrderList[0].orderCode;
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询挂具物料绑定关系报错 >>> {ex.Message}");
                LogManager.Info($"查询挂具物料绑定关系报错 >>> {ex.Message}");
            }
        }
        /// <summary>
        /// 解绑按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_JieBangByCarNo_Click(object sender, RoutedEventArgs e)
        {
            try
            {

            }
            catch (Exception ex)
            {
                LogManager.Info($"解绑载具物料绑定关系操作报错 >>> {ex.Message}");
            }
        }
        /// <summary>
        /// 清空输入框点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_ChaXunByCarNoClear_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.tbx_JieBangByCarNo.Clear();
                this.tbx_JieBangByVin.Clear();
            }
            catch (Exception)
            {
            }
        }
        /// <summary>
        /// 一键重置点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_JieBangAll_Click(object sender, RoutedEventArgs e)
        {
            try
            {

            }
            catch (Exception EX)
            {
                LogManager.Info($"一键重置订单、挂具状态方法报错 >>> {EX.Message}");
            }

        }
    }
}
