using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Threading; using Masuit.Tools.Logging; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; using Khd.Core.EntityFramework; using Khd.Core.Plc.S7; using Thrift.Server; using Thrift.Transport; using ThriftService; using Thrift.Protocol; using Khd.Core.Domain.Models; using Z.EntityFramework.Plus; using OfficeOpenXml; using Microsoft.Win32; using System.IO; using System.Windows; using Microsoft.EntityFrameworkCore; using System.Text.RegularExpressions; using System.Net.Http; using System.Net.Http.Json; using Khd.Core.Domain.Dto.webapi; using Newtonsoft.Json; using HandyControl.Tools.Extension; namespace Khd.Core.Wpf.Form { /// /// FormBoardT.xaml 的交互逻辑 /// public partial class FormBoardT : Window { private readonly IHost _host; private Khd.Core.Plc.S7.Plc _plc; private DispatcherTimer ShowTimer;//刷新时间 private DispatcherTimer PLCMessage;//呈现PLC机柜信息 private DispatcherTimer UPMessageTimer;//刷新上件记录 private DispatcherTimer ShowOrderMessage;//呈现PLC机柜信息 private object order_code; private int UpState;//对应上件站点的状态,0为良好 1为损坏 List basePlcpoints = new List(); object timerjilu; public class selectOrderData { public string Id { get; set; } public string orderCode { get; set; } } private string selectedId; //FormShowSelect formSelect; // public static int WeekNo = CommonHelper.WeekOfYear(DateTime.Now, new System.Globalization.CultureInfo("zh-CN")); public FormBoardT(IHost host) { InitializeComponent(); this._host = host; } /// /// 页面加载事件 /// /// /// 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; // //} // using var scope = _host.Services.CreateScope(); // using var dbContext = scope.ServiceProvider.GetRequiredService(); // basePlcpoints = dbContext.BasePlcpoint.Where(t => t.isDelete == 0).ToList(); // //var baseMaterials = dbContext.BaseMaterial.Where(t => t.IsDelete == 0).ToList(); //// // PLCMessage = new DispatcherTimer(); // PLCMessage.Tick += new EventHandler(PLCmessage); //委托获取点位方法 // PLCMessage.Interval = new TimeSpan(0, 0, 0, 0, 1000); // PLCMessage.Start(); // UPMessageTimer = new DispatcherTimer(); // UPMessageTimer.Tick += new EventHandler(UpMessage); //委托刷新上件记录 // UPMessageTimer.Interval = new TimeSpan(0, 0, 0, 0, 2000); // UPMessageTimer.Start(); // Button_Click_1(null, null); // SetTime(); // List list = new List // { // "101上件点", // "102上件点", // "103上件点" // }; } catch (Exception ex) { MessageBox.Show(ex.Message); } } /// /// 刷新日期 /// private void SetTime() { new Thread(() => { while (true) { try { Dispatcher.Invoke(new Action(delegate { LabDate.Content = DateTime.Now.ToString("yyyy年MM月dd日"); LabTime.Content = DateTime.Now.ToString("HH:mm:ss"); })); } catch (Exception ex) { } finally { Thread.Sleep(1000); } } }).Start(); } public void UpMessage(object sender, EventArgs e) { MoHuChaXunWuLiaoName_SelectionChanged(timerjilu, null); } /// /// WCS通讯方法 /// 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 { //设置图片为未到位 })); 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 { //设置图片为已到位、显示挂具号 })); } else { Application.Current.Dispatcher.Invoke(new Action( delegate { })); } } catch (Exception ex) { LogManager.Info($"客户端接收服务端推送的小车信息方法报错 >>> {ex.Message}"); } return ""; } /// /// 发车方法 /// /// /// /// 物料号 /// 三轮车辆长度 public void SendCar(List carlist, string prodCode, string bunber,string ordercodeid) { 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, prodCode, bunber, ordercodeid); if ("1" == "1")//与服务端交互成功发车时 { Application.Current.Dispatcher.Invoke(new Action( delegate { //发车成功提示反馈 this.lba_ThrifTtitle.Foreground = new SolidColorBrush(Colors.Green); this.lba_ThrifTtitle.Text = "发车成功!"; })); } else//与服务端交互失败时 { Application.Current.Dispatcher.Invoke(new Action( delegate { this.lba_ThrifTtitle.Foreground = new SolidColorBrush(Colors.Red); this.lba_ThrifTtitle.Text = $"Thrift交互失败!"; })); } } catch (Exception ex) { LogManager.Info($"发车方法报错 >>> {ex.Message}"); } finally { transport.Close(); transport.Dispose(); } } /// /// 显示序号事件 /// /// /// private void dgData_LoadingRow(object sender, DataGridRowEventArgs e) { e.Row.Header = e.Row.GetIndex() + 1; } /// /// 点击退出按钮 /// /// /// private void btnExit_Click(object sender, RoutedEventArgs e) { 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); } public int i = 0; /// /// 电气机柜信息面板定时器调用方法 /// /// /// private void PLCmessage(object sender, EventArgs e) { try { if (i == 1000) { i = 0; } foreach (var item in basePlcpoints) { //通过名称找到TextBox TextBox FoundTextBox = (TextBox)FindName(item.plcpointNo); if (FoundTextBox == null) { continue; } string value = i.ToString(); //string value = _plc.Read(item.plcpointAddress).ToString(); //if (value.IsNullOrEmpty()) //{ // continue; //} //if (FoundTextBox.IsFocused == true) //{ // continue; //} FoundTextBox.Text = value; i++; LogManager.Info(i.ToString()); } } catch (Exception ex) { LogManager.Info($"电气机柜信息面板定时器调用方法报错 >>> {ex.Message}"); } } /// /// PLC读取方法封装 /// /// plc地址位 /// plc数据类型(int类型默认为1) /// plc地址位长度(string类型默认为2) /// 载具号文本输入框 /// 载具到位文本输入框 /// PLC车辆状态文本输入框 /// 载具去向文本输入框 /// WCS处理状态文本输入框 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}"); } } /// /// 订单导入按钮点击事件 /// /// /// 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 { // 添加映射 {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 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(); // var orderModel = dbContext.BaseProductionOrderSplit.OrderBy(t => t.productionSequence).ToList(); ///var data = orderModel.Find(t => t.orderCode == values[4].Trim().ToUpper()); // } MessageBox.Show($"{ordernum}条订单导入系统!", "订单导入操作提示!"); //LoadMaterial_GetMessage(""); } } } })); } catch (Exception ex) { MessageBox.Show($"订单导入失败 >>> {ex.Message}", "订单导入操作提示!"); LogManager.Info($"按钮订单导入事件报错 >>> {ex.Message}"); } } /// /// 接收到载具号后,清空残留信息 /// /// /// 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.lba_ThrifTtitle.Text = string.Empty; //} } /// /// 订单清空按钮 /// /// /// 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(); 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}"); } } private void Button_Click_1(object sender, RoutedEventArgs e) { try { // } catch (Exception ex) { MessageBox.Show("查询订单遇到错误~>>>>>>>>>>>>>>>>>>>>" + ex); LogManager.Info("查询订单遇到错误~>>>>>>>>>>>>>>>>>>>>" + ex); } } /// /// 选择事件 /// /// /// private void MoHuChaXunWuLiaoName_SelectionChanged(object sender, SelectionChangedEventArgs e) { timerjilu = sender; ComboBox comboBox = (ComboBox)sender; var shangjiandian = comboBox.SelectedItem; string numberPart = Regex.Match(shangjiandian.ToString(), @"\d+").Value; try { using var scope = _host.Services.CreateScope(); using var dbContext = scope.ServiceProvider.GetRequiredService(); // } catch (Exception ex) { MessageBox.Show("查询订单遇到错误~>>>>>>>>>>>>>>>>>>>>" + ex); LogManager.Info("查询订单遇到错误~>>>>>>>>>>>>>>>>>>>>" + ex); } } /// /// 删除物料 /// /// /// private void Button_Click_2(object sender, RoutedEventArgs e) { if (LoadMaterial0.SelectedIndex == -1) { MessageBox.Show("请选择要删除的物料!"); } else { var quere = MessageBox.Show("确定删除吗", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Asterisk); // } } /// /// 刷新产线 /// /// /// private void Button_Click_3(object sender, RoutedEventArgs e) { // } /// /// 物料选择事件 /// /// /// private void shangjianwuliaocombox_SelectionChanged(object sender, SelectionChangedEventArgs e) { // } private void orderselect_SelectionChanged(object sender, SelectionChangedEventArgs e) { } private void Button_Click(object sender, RoutedEventArgs e) { using var scope = _host.Services.CreateScope(); using var dbContext = scope.ServiceProvider.GetRequiredService(); var data = dbContext.WcsTask.Where(t => t.useFlag == 0).ToList(); this.LoadMaterial0.ItemsSource = null; this.LoadMaterial0.ItemsSource = data; this.LoadMaterial0.Items.Refresh(); //MessageBox.Show("查询"); } } }