刘彬 7 місяців тому
батько
коміт
608ba9efb7
53 змінених файлів з 4207 додано та 2540 видалено
  1. 61 273
      LocalhostMES/Api/Controllers/MesController.cs
  2. 31 0
      LocalhostMES/Api/Hosting/OwinWebApiStartup.cs
  3. 78 0
      LocalhostMES/Api/Hosting/WebApiService.cs
  4. 43 49
      LocalhostMES/Api/Services/MesApiClient.cs
  5. 17 0
      LocalhostMES/Api/Services/MesMomHttpEndpoints.cs
  6. 8 48
      LocalhostMES/App.xaml
  7. 15 16
      LocalhostMES/App.xaml.cs
  8. 0 175
      LocalhostMES/Controller/WebApiService.cs
  9. 25 0
      LocalhostMES/Converters/ResultColorConverter.cs
  10. 7 1
      LocalhostMES/Core/Management.cs
  11. 46 0
      LocalhostMES/Core/MesDataChangedEvent.cs
  12. 56 0
      LocalhostMES/Core/ThemeManager.cs
  13. 88 0
      LocalhostMES/Core/WorkOrderNotifyTcpClient.cs
  14. 112 39
      LocalhostMES/DataBase/DatabaseHelper.cs
  15. 17 0
      LocalhostMES/Enums/KeyPartStationType.cs
  16. 171 0
      LocalhostMES/Helpers/DateCodeConverter.cs
  17. 11 27
      LocalhostMES/Infrastructure/PrismDependencyResolver.cs
  18. 97 5
      LocalhostMES/LocalhostMES.csproj
  19. 67 56
      LocalhostMES/Models/MesModel.cs
  20. 32 958
      LocalhostMES/ViewModels/MainViewModel.cs
  21. 35 0
      LocalhostMES/ViewModels/Services/IMesWorkspace.cs
  22. 193 0
      LocalhostMES/ViewModels/Services/MesWorkspace.cs
  23. 340 0
      LocalhostMES/ViewModels/Tabs/ApiTestViewModel.cs
  24. 147 0
      LocalhostMES/ViewModels/Tabs/BindRecordsViewModel.cs
  25. 157 0
      LocalhostMES/ViewModels/Tabs/KeyPartManagementViewModel.cs
  26. 205 0
      LocalhostMES/ViewModels/Tabs/PartCatalogViewModel.cs
  27. 147 0
      LocalhostMES/ViewModels/Tabs/ProcessRecordsViewModel.cs
  28. 202 0
      LocalhostMES/ViewModels/Tabs/SnManagementViewModel.cs
  29. 205 0
      LocalhostMES/ViewModels/Tabs/SystemSettingsViewModel.cs
  30. 382 0
      LocalhostMES/ViewModels/Tabs/TcpServerViewModel.cs
  31. 154 0
      LocalhostMES/ViewModels/Tabs/WorkOrderManagementViewModel.cs
  32. 35 870
      LocalhostMES/Views/MainView.xaml
  33. 130 23
      LocalhostMES/Views/MainView.xaml.cs
  34. 165 0
      LocalhostMES/Views/Resources/MesTabStyles.xaml
  35. 38 0
      LocalhostMES/Views/Tabs/ApiTestView.xaml
  36. 21 0
      LocalhostMES/Views/Tabs/ApiTestView.xaml.cs
  37. 39 0
      LocalhostMES/Views/Tabs/BindRecordsView.xaml
  38. 12 0
      LocalhostMES/Views/Tabs/BindRecordsView.xaml.cs
  39. 110 0
      LocalhostMES/Views/Tabs/KeyPartManagementView.xaml
  40. 12 0
      LocalhostMES/Views/Tabs/KeyPartManagementView.xaml.cs
  41. 155 0
      LocalhostMES/Views/Tabs/PartCatalogView.xaml
  42. 12 0
      LocalhostMES/Views/Tabs/PartCatalogView.xaml.cs
  43. 39 0
      LocalhostMES/Views/Tabs/ProcessRecordsView.xaml
  44. 12 0
      LocalhostMES/Views/Tabs/ProcessRecordsView.xaml.cs
  45. 39 0
      LocalhostMES/Views/Tabs/SnManagementView.xaml
  46. 12 0
      LocalhostMES/Views/Tabs/SnManagementView.xaml.cs
  47. 77 0
      LocalhostMES/Views/Tabs/SystemSettingsView.xaml
  48. 12 0
      LocalhostMES/Views/Tabs/SystemSettingsView.xaml.cs
  49. 69 0
      LocalhostMES/Views/Tabs/TcpServerView.xaml
  50. 15 0
      LocalhostMES/Views/Tabs/TcpServerView.xaml.cs
  51. 40 0
      LocalhostMES/Views/Tabs/WorkOrderManagementView.xaml
  52. 12 0
      LocalhostMES/Views/Tabs/WorkOrderManagementView.xaml.cs
  53. 2 0
      LocalhostMES/packages.config

+ 61 - 273
LocalhostMES/Controller/MesController.cs → LocalhostMES/Api/Controllers/MesController.cs

@@ -1,26 +1,23 @@
-using LocalhostMES.Core;
+using LocalhostMES.Core;
 using LocalhostMES.DataBase;
+using LocalhostMES.Helpers;
 using LocalhostMES.Models;
 using Newtonsoft.Json;
-using Prism.Ioc;
 using System;
-using System.Collections.Concurrent;
 using System.Collections.Generic;
 using System.Linq;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Web.Http;
-using System.Web.UI.WebControls.WebParts;
 
-namespace LocalhostMES.Controller
+namespace LocalhostMES.Api.Controllers
 {
     [RoutePrefix("api/mes")]
     public class MesController : ApiController
     {
-        private static readonly Random _random = new Random();
         private static int _snCounter = 1;
         private Management management;
-        
+
         public MesController()
         {
             management = Management.GetManagement();
@@ -34,17 +31,17 @@ namespace LocalhostMES.Controller
             {
                 LogHelper.WriteLogInfo("厂级MES下发工单信息");
                 // 验证必填字段
-                if (string.IsNullOrEmpty(request.WorkOrderNo) ||
+                if ( string.IsNullOrEmpty(request.WorkOrderNo) ||
                     string.IsNullOrEmpty(request.MaterialCode) ||
                     string.IsNullOrEmpty(request.MaterialName) ||
-                    string.IsNullOrEmpty(request.LineCode))
+                    string.IsNullOrEmpty(request.LineCode) )
                 {
                     LogHelper.WriteLogInfo("必填字段不能为空");
                     return BadRequest("必填字段不能为空");
                 }
 
                 // 工单状态验证
-                if (!IsValidStatus(request.Status))
+                if ( !IsValidStatus(request.Status) )
                 {
                     LogHelper.WriteLogInfo("无效的工单状态");
                     return BadRequest($"无效的工单状态: {request.Status}");
@@ -66,7 +63,7 @@ namespace LocalhostMES.Controller
                     EndTime = DateTime.Now.AddSeconds(5)
                 };
 
-                if (DatabaseHelper.InsertWorkOrderInfo(workOrder))
+                if ( DatabaseHelper.InsertWorkOrderInfo(workOrder) )
                 {
 
                     var response = new ApiResponse<bool>
@@ -95,7 +92,7 @@ namespace LocalhostMES.Controller
                     return Content(System.Net.HttpStatusCode.InternalServerError, errorResponse);
                 }
             }
-            catch (Exception ex)
+            catch ( Exception ex )
             {
                 var errorResponse = new ErrorResponse
                 {
@@ -128,7 +125,7 @@ namespace LocalhostMES.Controller
                 };
                 return Ok(response);
             }
-            catch (Exception ex)
+            catch ( Exception ex )
             {
                 var errorResponse = new ErrorResponse
                 {
@@ -151,23 +148,23 @@ namespace LocalhostMES.Controller
             try
             {
                 // 验证请求头
-                if (!ValidateHeaders())
+                if ( !ValidateHeaders() )
                 {
                     return Unauthorized();
                 }
                 // 验证必填字段
-                if (string.IsNullOrEmpty(request.workOrderNo) || request.count <= 0)
+                if ( string.IsNullOrEmpty(request.workOrderNo) || request.count <= 0 )
                 {
                     return BadRequest("工单号和数量为必填项且数量必须大于0");
                 }
                 var workOrder = DatabaseHelper.SelectWorkOrderInfo(request.workOrderNo);
                 // 验证工单是否存在
-                if (workOrder.Count == 0)
+                if ( workOrder.Count == 0 )
                 {
                     return BadRequest($"工单 {request.workOrderNo} 不存在");
                 }
                 // 验证打印类型
-                if (request.printType < 1 || request.printType > 4)
+                if ( request.printType < 1 || request.printType > 4 )
                 {
                     return BadRequest($"无效的打印类型: {request.printType}");
                 }
@@ -175,40 +172,37 @@ namespace LocalhostMES.Controller
 
                 LogHelper.WriteLogInfo("请求参数:");
                 LogHelper.WriteLogInfo(JsonConvert.SerializeObject(request, Formatting.Indented));
-                if (management.IsLocalhostMode)
+                if ( management.IsLocalhostMode )
                 {
                     var Manualsninfo = DatabaseHelper.SelectSnInfo(request.workOrderNo);
                     DatabaseHelper.InsertSnInfo(new SnInfo()
                     {
-                        Sn = "000001" +DateCodeConverter.GetYearCode(DateTime.Now.Year) +
+                        Sn = "000001" + DateCodeConverter.GetYearCode(DateTime.Now.Year) +
                              DateCodeConverter.GetMonthCode(DateTime.Now.Month) +
                              DateCodeConverter.GetDayCode(DateTime.Now.Day) +
                              "00000" + Manualsninfo.Count,
-                             IsUsed = false,
-                             WorkOrderNo= request.workOrderNo,
-                             GenerateTime=DateTime.Now,
-                             PrintType="1",
-
+                        IsUsed = false,
+                        WorkOrderNo = request.workOrderNo,
+                        GenerateTime = DateTime.Now,
+                        PrintType = "1",
                     });
                 }
-
-                var sninfo = DatabaseHelper.SelectSnInfo(request.workOrderNo, true, false);
-                if (sninfo.Count == 0)
+                else
                 {
                     ApiResponse<SnPrintResponseData> mesres = await management.ApiClient.RequestSnPrintAsync(request);
-                    if (mesres.success && mesres.data!=null&& mesres.data.Sn.Count != 0)
+                    if ( mesres.success && mesres.data != null && mesres.data.Sn.Count != 0 )
                     {
-                        for (int i = 0; i < mesres.data.Sn.Count; i++)
+                        for ( int i = 0; i < mesres.data.Sn.Count; i++ )
                         {
-                            if (!DatabaseHelper.InsertSnInfo(new SnInfo()
+                            if ( !DatabaseHelper.InsertSnInfo(new SnInfo()
                             {
                                 WorkOrderNo = mesres.data.WorkOrderNo,
-                                Sn = mesres.data.Sn[i].Sn,
+                                Sn = mesres.data.Sn[ i ].Sn,
                                 GenerateTime = DateTime.Now,
                                 PrintType = "1",
                                 IsUsed = false,
 
-                            }))
+                            }) )
                             {
                                 mesres.msg = "插入SN到数据库出错";
                                 mesres.success = false;
@@ -221,11 +215,12 @@ namespace LocalhostMES.Controller
                     return Content(System.Net.HttpStatusCode.InternalServerError, mesres);
 
                 }
+                var sninfo = DatabaseHelper.SelectSnInfo(request.workOrderNo, true, false);
                 // 生成SN列表
                 var snList = new List<SnItem>();
-                if (sninfo.Count != 0)
+                if ( sninfo.Count != 0 )
                 {
-                    snList.Add(new SnItem { Sn = sninfo[0].Sn });
+                    snList.Add(new SnItem { Sn = sninfo[ 0 ].Sn });
 
                     var responseData = new SnPrintResponseData
                     {
@@ -260,7 +255,7 @@ namespace LocalhostMES.Controller
                 };
                 return Content(System.Net.HttpStatusCode.InternalServerError, errorResponse);
             }
-            catch (Exception ex)
+            catch ( Exception ex )
             {
                 var errorResponse = new ErrorResponse
                 {
@@ -281,7 +276,7 @@ namespace LocalhostMES.Controller
             try
             {
                 var sninfo = DatabaseHelper.SelectSnInfo(workOrderNo, true, false);
-                if (sninfo.Count != 0)
+                if ( sninfo.Count != 0 )
                 {
                     var response = new ApiResponse<List<SnInfo>>
                     {
@@ -305,7 +300,7 @@ namespace LocalhostMES.Controller
                 };
                 return Content(System.Net.HttpStatusCode.NotFound, errorResponse);
             }
-            catch (Exception ex)
+            catch ( Exception ex )
             {
                 var errorResponse = new ErrorResponse
                 {
@@ -329,31 +324,31 @@ namespace LocalhostMES.Controller
             {
 
                 LogHelper.WriteLogInfo($"收到请求: 接收SN和关键件");
-                if (management.IsLocalhostMode)
+                if ( management.IsLocalhostMode )
                 {
                     return Ok(new ApiResponse<bool?>() { data = true });
                 }
                 // 验证请求头
-                if (!ValidateHeaders())
+                if ( !ValidateHeaders() )
                 {
                     return Unauthorized();
                 }
                 // 验证必填字段
-                if (string.IsNullOrEmpty(request.plant) ||
+                if ( string.IsNullOrEmpty(request.plant) ||
                     string.IsNullOrEmpty(request.stationCode) ||
                     string.IsNullOrEmpty(request.positionCode) ||
                     string.IsNullOrEmpty(request.sn) ||
-                    string.IsNullOrEmpty(request.scanTime))
+                    string.IsNullOrEmpty(request.scanTime) )
                 {
                     return BadRequest("必填字段不能为空");
                 }
 
                 // 处理关键件绑定
-                if (request.part != null && request.part.Count > 0)
+                if ( request.part != null && request.part.Count > 0 )
                 {
-                    foreach (var part in request.part)
+                    foreach ( var part in request.part )
                     {
-                        if (string.IsNullOrEmpty(part.partNum))
+                        if ( string.IsNullOrEmpty(part.partNum) )
                         {
                             return BadRequest("关键件条码不能为空");
                         }
@@ -367,7 +362,7 @@ namespace LocalhostMES.Controller
                             ScanType = request.scanTpye
                         };
                         DatabaseHelper.InsertBindRecord(bindRecord);
-                        if (management.IsLocalhostMode)
+                        if ( management.IsLocalhostMode )
                         {
                             //if (DatabaseHelper.GetProductProductionRecords(request.sn) == 0)
                             //{
@@ -387,7 +382,7 @@ namespace LocalhostMES.Controller
 
                     }
                 }
-                else 
+                else
                 {
                     var bindRecord = new BindRecord
                     {
@@ -401,26 +396,26 @@ namespace LocalhostMES.Controller
                     DatabaseHelper.InsertBindRecord(bindRecord);
 
                 }
-                if (management.IsLocalhostMode)
+                if ( management.IsLocalhostMode )
                 {
                     LogHelper.WriteLogInfo($"收到请求: 接收SN和关键件  成功");
-                    return Ok(new ApiResponse<bool?>() { data=true} );
+                    return Ok(new ApiResponse<bool?>() { data = true });
                 }
                 var okresponse = await management.ApiClient.SendSnComponentAsync(request);
-                if (okresponse.success && okresponse.code == "200")
+                if ( okresponse.success && okresponse.code == "200" )
                 {
-                   
+
                     LogHelper.WriteLogInfo($"收到请求: 接收SN和关键件  成功");
                     return Ok(okresponse);
                 }
                 else
                 {
-                    LogHelper.WriteLogInfo($"收到请求: 接收SN和关键件  失败\r\n"+ okresponse.ToString());
+                    LogHelper.WriteLogInfo($"收到请求: 接收SN和关键件  失败\r\n" + okresponse.ToString());
                     okresponse.success = false;
                     return Content(System.Net.HttpStatusCode.InternalServerError, okresponse);
                 }
             }
-            catch (Exception ex)
+            catch ( Exception ex )
             {
                 var errorResponse = new ErrorResponse
                 {
@@ -452,7 +447,7 @@ namespace LocalhostMES.Controller
                 };
                 return Ok(response);
             }
-            catch (Exception ex)
+            catch ( Exception ex )
             {
                 var errorResponse = new ErrorResponse
                 {
@@ -476,22 +471,22 @@ namespace LocalhostMES.Controller
             {
                 LogHelper.WriteLogInfo($"收到请求:接收工件加工参数 ");
                 // 验证请求头
-                if (!ValidateHeaders())
+                if ( !ValidateHeaders() )
                 {
                     return Unauthorized();
                 }
 
                 // 验证必填字段
-                if (string.IsNullOrEmpty(request.plant) ||
+                if ( string.IsNullOrEmpty(request.plant) ||
                     string.IsNullOrEmpty(request.station) ||
                     string.IsNullOrEmpty(request.sn) ||
-                    string.IsNullOrEmpty(request.overallResult))
+                    string.IsNullOrEmpty(request.overallResult) )
                 {
                     return BadRequest("必填字段不能为空");
                 }
 
                 // 验证总结果
-                if (request.overallResult != "OK" && request.overallResult != "NG")
+                if ( request.overallResult != "OK" && request.overallResult != "NG" )
                 {
                     return BadRequest($"无效的总结果: {request.overallResult}");
                 }
@@ -507,7 +502,7 @@ namespace LocalhostMES.Controller
                 };
 
                 DatabaseHelper.InsertProcessRecord(processRecord);
-                if (management.IsLocalhostMode)
+                if ( management.IsLocalhostMode )
                 {
                     var response = new ApiResponse<bool>
                     {
@@ -523,7 +518,7 @@ namespace LocalhostMES.Controller
                 }
                 var okresponse = await management.ApiClient.SendProcessParametersAsync(request);
 
-                if (okresponse.success && okresponse.code == "200")
+                if ( okresponse.success && okresponse.code == "200" )
                 {
                     LogHelper.WriteLogInfo($"收到请求: 接收工件加工参数  成功");
                     return Ok(okresponse);
@@ -535,9 +530,9 @@ namespace LocalhostMES.Controller
                     return Content(System.Net.HttpStatusCode.InternalServerError, okresponse);
                 }
 
-                
+
             }
-            catch (Exception ex)
+            catch ( Exception ex )
             {
                 LogHelper.WriteLogInfo("出错");
                 var errorResponse = new ErrorResponse
@@ -570,7 +565,7 @@ namespace LocalhostMES.Controller
                 };
                 return Ok(response);
             }
-            catch (Exception ex)
+            catch ( Exception ex )
             {
                 var errorResponse = new ErrorResponse
                 {
@@ -589,8 +584,8 @@ namespace LocalhostMES.Controller
         private bool ValidateHeaders()
         {
             // 简单的token验证
-            if (Request.Headers.TryGetValues("app-key", out var appKeyValues) &&
-                Request.Headers.TryGetValues("token", out var tokenValues))
+            if ( Request.Headers.TryGetValues("app-key", out var appKeyValues) &&
+                Request.Headers.TryGetValues("token", out var tokenValues) )
             {
                 var appKey = appKeyValues.FirstOrDefault();
                 var token = tokenValues.FirstOrDefault();
@@ -621,7 +616,7 @@ namespace LocalhostMES.Controller
         private string GetPrintTypePrefix(int printType)
         {
 
-            switch (printType)
+            switch ( printType )
             {
                 case 1:
                     return "P";
@@ -640,7 +635,7 @@ namespace LocalhostMES.Controller
         private string GetPrintTypeName(int printType)
         {
 
-            switch (printType)
+            switch ( printType )
             {
                 case 1:
                     return "产品码";
@@ -659,211 +654,4 @@ namespace LocalhostMES.Controller
         #endregion
 
     }
-
-    public class DateCodeConverter
-    {
-        // ============== 年份对照表 ==============
-        private static readonly Dictionary<int, string> yearToCode = new Dictionary<int, string>
-    {
-        {2018, "1"}, {2019, "2"}, {2020, "3"}, {2021, "4"}, {2022, "5"},
-        {2023, "6"}, {2024, "7"}, {2025, "8"}, {2026, "9"}, {2027, "A"},
-        {2028, "B"}, {2029, "C"}, {2030, "D"}, {2031, "E"}, {2032, "F"},
-        {2033, "G"}, {2034, "H"}, {2035, "J"}, {2036, "K"}, {2037, "L"},
-        {2038, "M"}, {2039, "N"}, {2040, "P"}, {2041, "R"}, {2042, "S"},
-        {2043, "T"}, {2044, "V"}, {2045, "W"}, {2046, "X"}, {2047, "Y"},
-        {2048, "1"}, {2049, "2"}, {2050, "3"}, {2051, "4"}, {2052, "5"},
-        {2053, "6"}, {2054, "7"}, {2055, "8"}, {2056, "9"}, {2057, "A"}
-    };
-
-        // ============== 月份对照表 ==============
-        private static readonly Dictionary<int, string> monthToCode = new Dictionary<int, string>
-    {
-        {1, "1"}, {2, "2"}, {3, "3"}, {4, "4"}, {5, "5"}, {6, "6"},
-        {7, "7"}, {8, "8"}, {9, "9"}, {10, "A"}, {11, "B"}, {12, "C"}
-    };
-
-        // ============== 日期对照表 ==============
-        private static readonly Dictionary<int, string> dayToCode = new Dictionary<int, string>
-    {
-        {1, "1"}, {2, "2"}, {3, "3"}, {4, "4"}, {5, "5"}, {6, "6"}, {7, "7"}, {8, "8"}, {9, "9"},
-        {10, "A"}, {11, "B"}, {12, "C"}, {13, "D"}, {14, "E"}, {15, "F"}, {16, "G"},
-        {17, "H"}, {18, "J"}, {19, "K"},{20,"L"},{21, "M"}, {22, "N"}, {23, "P"},  {24, "R"},
-        {25, "S"}, {26, "T"}, {27, "U"}, {28, "V"}, {29, "W"}, {30, "X"}, {31, "Y"}
-    };
-
-        // ============== 反向查找字典 ==============
-        private static readonly Dictionary<string, int> codeToYear;
-        private static readonly Dictionary<string, int> codeToMonth;
-        private static readonly Dictionary<string, int> codeToDay;
-
-        static DateCodeConverter()
-        {
-            // 初始化反向字典
-            codeToYear = yearToCode
-                .GroupBy(kv => kv.Value)
-                .ToDictionary(g => g.Key, g => g.Last().Key);
-
-            codeToMonth = monthToCode
-                .ToDictionary(kv => kv.Value, kv => kv.Key);
-
-            codeToDay = dayToCode
-                .ToDictionary(kv => kv.Value, kv => kv.Key);
-        }
-
-        // ============== 年份相关方法 ==============
-
-        /// <summary>
-        /// 根据年份获取代码
-        /// </summary>
-        public static string GetYearCode(int year)
-        {
-            return yearToCode.TryGetValue(year, out string code) ? code : "未知年份";
-        }
-
-        /// <summary>
-        /// 根据代码获取年份(返回最新的对应年份)
-        /// </summary>
-        public static int? GetYearByCode(string code)
-        {
-            return codeToYear.TryGetValue(code, out int year) ? year : (int?)null;
-        }
-
-        /// <summary>
-        /// 获取所有对应某个代码的年份
-        /// </summary>
-        public static List<int> GetAllYearsByCode(string code)
-        {
-            return yearToCode
-                .Where(kv => kv.Value == code)
-                .Select(kv => kv.Key)
-                .ToList();
-        }
-
-        // ============== 月份相关方法 ==============
-
-        /// <summary>
-        /// 根据月份获取代码
-        /// </summary>
-        public static string GetMonthCode(int month)
-        {
-            if (month < 1 || month > 12)
-                return "无效月份";
-
-            return monthToCode.TryGetValue(month, out string code) ? code : "未知月份";
-        }
-
-        /// <summary>
-        /// 根据代码获取月份
-        /// </summary>
-        public static int? GetMonthByCode(string code)
-        {
-            return codeToMonth.TryGetValue(code, out int month) ? month : (int?)null;
-        }
-
-        // ============== 日期相关方法 ==============
-
-        /// <summary>
-        /// 根据日期获取代码
-        /// </summary>
-        public static string GetDayCode(int day)
-        {
-            if (day < 1 || day > 31)
-                return "无效日期";
-
-            return dayToCode.TryGetValue(day, out string code) ? code : "未知日期";
-        }
-
-        /// <summary>
-        /// 根据代码获取日期
-        /// </summary>
-        public static int? GetDayByCode(string code)
-        {
-            return codeToDay.TryGetValue(code, out int day) ? day : (int?)null;
-        }
-
-        // ============== 完整日期转换方法 ==============
-
-        /// <summary>
-        /// 将DateTime转换为日期代码(3位字符:年份代码 + 月份代码 + 日期代码)
-        /// </summary>
-        public static string ConvertToDateCode(DateTime date)
-        {
-            string yearCode = GetYearCode(date.Year);
-            string monthCode = GetMonthCode(date.Month);
-            string dayCode = GetDayCode(date.Day);
-
-            // 检查是否有无效的代码
-            if (yearCode == "未知年份" || monthCode == "无效月份" || dayCode == "无效日期" || dayCode == "未知日期")
-            {
-                return "无效日期";
-            }
-
-            return $"{yearCode}{monthCode}{dayCode}";
-        }
-
-        /// <summary>
-        /// 将日期代码转换为DateTime(如果有多个年份对应,返回最新的)
-        /// </summary>
-        public static DateTime? ConvertFromDateCode(string dateCode)
-        {
-            if (string.IsNullOrEmpty(dateCode) || dateCode.Length != 3)
-                return null;
-
-            string yearCode = dateCode.Substring(0, 1);
-            string monthCode = dateCode.Substring(1, 1);
-            string dayCode = dateCode.Substring(2, 1);
-
-            var year = GetYearByCode(yearCode);
-            var month = GetMonthByCode(monthCode);
-            var day = GetDayByCode(dayCode);
-
-            if (!year.HasValue || !month.HasValue || !day.HasValue)
-                return null;
-
-            try
-            {
-                return new DateTime(year.Value, month.Value, day.Value);
-            }
-            catch (ArgumentOutOfRangeException)
-            {
-                return null;
-            }
-        }
-
-        /// <summary>
-        /// 将日期代码转换为所有可能的DateTime列表(考虑年份重复的情况)
-        /// </summary>
-        public static List<DateTime> ConvertAllFromDateCode(string dateCode)
-        {
-            var result = new List<DateTime>();
-
-            if (string.IsNullOrEmpty(dateCode) || dateCode.Length != 3)
-                return result;
-
-            string yearCode = dateCode.Substring(0, 1);
-            string monthCode = dateCode.Substring(1, 1);
-            string dayCode = dateCode.Substring(2, 1);
-
-            var allYears = GetAllYearsByCode(yearCode);
-            var month = GetMonthByCode(monthCode);
-            var day = GetDayByCode(dayCode);
-
-            if (allYears.Count == 0 || !month.HasValue || !day.HasValue)
-                return result;
-
-            foreach (var year in allYears)
-            {
-                try
-                {
-                    result.Add(new DateTime(year, month.Value, day.Value));
-                }
-                catch (ArgumentOutOfRangeException)
-                {
-                    // 跳过无效日期(如2月30日等)
-                }
-            }
-
-            return result;
-        }
-    }
 }

+ 31 - 0
LocalhostMES/Api/Hosting/OwinWebApiStartup.cs

@@ -0,0 +1,31 @@
+using Newtonsoft.Json;
+using Owin;
+using System.Web.Http;
+
+namespace LocalhostMES.Api.Hosting
+{
+    /// <summary>
+    /// OWIN 管道配置(与 WPF 的 App 启动逻辑分离)。
+    /// </summary>
+    public class OwinWebApiStartup
+    {
+        public void Configuration(IAppBuilder app)
+        {
+            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
+
+            var config = new HttpConfiguration();
+            config.MapHttpAttributeRoutes();
+            config.Routes.MapHttpRoute(
+                name: "DefaultApi",
+                routeTemplate: "api/{controller}/{action}/{id}",
+                defaults: new { id = RouteParameter.Optional });
+
+            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling =
+                ReferenceLoopHandling.Ignore;
+            config.Formatters.JsonFormatter.SerializerSettings.Formatting =
+                Formatting.Indented;
+
+            app.UseWebApi(config);
+        }
+    }
+}

+ 78 - 0
LocalhostMES/Api/Hosting/WebApiService.cs

@@ -0,0 +1,78 @@
+using LocalhostMES.Core;
+using Microsoft.Owin.Hosting;
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace LocalhostMES.Api.Hosting
+{
+    /// <summary>
+    /// 自托管 Web API(OWIN + Web API 2),供产线/上位机调用。
+    /// </summary>
+    public class WebApiService : IDisposable
+    {
+        private IDisposable _webApp;
+        private readonly CancellationTokenSource _cts = new CancellationTokenSource();
+        private StartOptions _startOptions;
+        private string _baseUrl = "192.168.1.26:8081";
+
+        public void Init(int port = 8081)
+        {
+            _baseUrl = $"http://192.168.1.26:{port}";
+            _startOptions = new StartOptions
+            {
+                Urls = { $"http://192.168.1.26:{port}", $"http://10.157.15.51:{port}" }
+            };
+        }
+
+        public Task StartAsync()
+        {
+            try
+            {
+                _webApp = WebApp.Start(_startOptions, app => new OwinWebApiStartup().Configuration(app));
+                InitializeTestData();
+                LogHelper.WriteLogInfo($"Web API服务已启动: {_baseUrl}");
+                Console.WriteLine($"Web API服务已启动: {_baseUrl}");
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine($"启动Web API服务失败: {ex.Message}");
+                LogHelper.WriteLogInfo($"启动Web API服务失败: {ex.Message}");
+                throw;
+            }
+
+            return Task.CompletedTask;
+        }
+
+        private static void InitializeTestData()
+        {
+            try
+            {
+                Console.WriteLine("测试数据初始化完成");
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine($"初始化测试数据失败: {ex.Message}");
+            }
+        }
+
+        public Task StopAsync()
+        {
+            _webApp?.Dispose();
+            _webApp = null;
+            Console.WriteLine("Web API服务已停止");
+            return Task.CompletedTask;
+        }
+
+        public void Dispose()
+        {
+            _cts?.Cancel();
+            _cts?.Dispose();
+            _webApp?.Dispose();
+            GC.SuppressFinalize(this);
+        }
+
+        public bool IsRunning => _webApp != null;
+        public string BaseUrl => _baseUrl;
+    }
+}

+ 43 - 49
LocalhostMES/Controller/MesApiClient.cs → LocalhostMES/Api/Services/MesApiClient.cs

@@ -1,19 +1,19 @@
-using LocalhostMES.Core;
+using LocalhostMES.Core;
 using LocalhostMES.DataBase;
 using LocalhostMES.Models;
 using Newtonsoft.Json;
 using Newtonsoft.Json.Linq;
 using System;
 using System.Collections.Generic;
-using System.Linq;
 using System.Net.Http;
-using System.Runtime.InteropServices;
 using System.Text;
-using System.Text.Json.Nodes;
 using System.Threading.Tasks;
 
-namespace LocalhostMES.Controller
+namespace LocalhostMES.Api.Services
 {
+    /// <summary>
+    /// 调用厂级 MOM/MES HTTP 接口;本地网关 URL 与云端 URL 均在此封装。
+    /// </summary>
     public class MesApiClient : IDisposable
     {
         private readonly HttpClient _httpClient;
@@ -23,7 +23,7 @@ namespace LocalhostMES.Controller
 
         public MesApiClient(string baseUrl, string appKey = "test-app-key", string token = "test-token-123")
         {
-            _baseUrl = baseUrl;
+            _baseUrl = baseUrl?.TrimEnd('/') ?? "";
             _appKey = appKey;
             _token = token;
             _httpClient = new HttpClient
@@ -33,11 +33,11 @@ namespace LocalhostMES.Controller
         }
 
         #region 2.1 厂级MES下发工单信息
+
         public async Task<ApiResponse<bool>> SendWorkOrderAsync(WorkOrderRequest request)
         {
-            // 2.1.2 Headers - 免TOKEN写入
             var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
-            var response = await _httpClient.PostAsync($"{_baseUrl}/api/mes/receiveWorkOrder", content);//http://192.168.1.26:5000/api/mes/receiveWorkOrder
+            var response = await _httpClient.PostAsync($"{_baseUrl}/api/mes/receiveWorkOrder", content);
             return await ParseResponseAsync<ApiResponse<bool>>(response);
         }
 
@@ -46,15 +46,16 @@ namespace LocalhostMES.Controller
             var response = await _httpClient.GetAsync($"{_baseUrl}/api/mes/getWorkOrders");
             return await ParseResponseAsync<ApiResponse<List<WorkOrderInfo>>>(response);
         }
+
         #endregion
 
         #region 2.2 SN打印请求
+
         public async Task<ApiResponse<SnPrintResponseData>> RequestSnPrintAsync(SnPrintRequest request)
         {
-            // 2.2.2 Headers - 需要token
             var requestJson = JsonConvert.SerializeObject(request);
             var content = new StringContent(requestJson, Encoding.UTF8, "application/json");
-            var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"https://mom-jh-annex-api.leapmotor.com/app-mom-mes/api/battery/sn/print \r\n")
+            var requestMessage = new HttpRequestMessage(HttpMethod.Post, MesMomHttpEndpoints.BatterySnPrint)
             {
                 Content = content
             };
@@ -63,12 +64,12 @@ namespace LocalhostMES.Controller
             var response = await _httpClient.SendAsync(requestMessage);
             ApiResponse<SnPrintResponseData> res = await ParseResponseAsync<ApiResponse<SnPrintResponseData>>(response);
 
-            List<SnInfo> inSn = new List<SnInfo>();
+            var inSn = new List<SnInfo>();
             if (res.data != null)
             {
                 for (int i = 0; i < res.data.Sn.Count; i++)
                 {
-                    inSn.Add(new SnInfo()
+                    inSn.Add(new SnInfo
                     {
                         WorkOrderNo = res.data.WorkOrderNo,
                         Sn = res.data.Sn[i].Sn,
@@ -78,18 +79,18 @@ namespace LocalhostMES.Controller
                     });
                 }
             }
-            if (inSn.Count != 0) 
+
+            if (inSn.Count != 0)
             {
                 if (DatabaseHelper.InsertSnInfos(inSn))
                 {
                     return res;
                 }
-                else 
-                {
-                    res.success = false;
-                    res.msg = "SN插入数据库错误";
-                }
+
+                res.success = false;
+                res.msg = "SN插入数据库错误";
             }
+
             return res;
         }
 
@@ -101,14 +102,16 @@ namespace LocalhostMES.Controller
             var response = await _httpClient.SendAsync(requestMessage);
             return await ParseResponseAsync<ApiResponse<List<SnInfo>>>(response);
         }
+
         #endregion
 
         #region 2.3 接收SN和关键件
+
         public async Task<ApiResponse<bool?>> SendSnComponentAsync(SnKeyComponentRequest request)
         {
             var requestJson = JsonConvert.SerializeObject(request);
             var content = new StringContent(requestJson, Encoding.UTF8, "application/json");
-            var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"https://mom-jh-annex-api.leapmotor.com/app-mom-mes/api/task/receive/sn/keyComponent " )
+            var requestMessage = new HttpRequestMessage(HttpMethod.Post, MesMomHttpEndpoints.ReceiveSnKeyComponent)
             {
                 Content = content
             };
@@ -128,16 +131,18 @@ namespace LocalhostMES.Controller
             var response = await _httpClient.SendAsync(requestMessage);
             return await ParseResponseAsync<ApiResponse<List<BindRecord>>>(response);
         }
+
         #endregion
 
         #region 2.4 接收工件加工参数
+
         public async Task<ApiResponse<bool?>> SendProcessParametersAsync(ProcessParameterRequest request)
         {
             request.messageTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
             var requestJson = JsonConvert.SerializeObject(request);
             var content = new StringContent(requestJson, Encoding.UTF8, "application/json");
             LogHelper.WriteLogInfo(requestJson);
-            var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"https://mom-jh-annex-api.leapmotor.com/app-mom-mes/api/task/receive/manualSave ")
+            var requestMessage = new HttpRequestMessage(HttpMethod.Post, MesMomHttpEndpoints.ManualSave)
             {
                 Content = content
             };
@@ -146,8 +151,6 @@ namespace LocalhostMES.Controller
             requestMessage.Headers.Add("token", _token);
 
             var response = await _httpClient.SendAsync(requestMessage);
-      
-           
             return await ParseResponseAsync<ApiResponse<bool?>>(response);
         }
 
@@ -160,53 +163,46 @@ namespace LocalhostMES.Controller
             var response = await _httpClient.SendAsync(requestMessage);
             return await ParseResponseAsync<ApiResponse<List<ProcessRecord>>>(response);
         }
+
         #endregion
 
-        #region 辅助方法
         private async Task<T> ParseResponseAsync<T>(HttpResponseMessage response) where T : class
         {
-          
-            if ( response.IsSuccessStatusCode)
+            if (response.IsSuccessStatusCode)
             {
                 var json = await response.Content.ReadAsStringAsync();
                 var jObject = JObject.Parse(json);
                 LogHelper.WriteLogInfo(json);
                 if (jObject.ContainsKey("data"))
                 {
-                    string str = jObject["data"].ToString();
-                    if (jObject["data"].ToString() == "null"|| jObject["data"].ToString().Length==0)
+                    if (jObject["data"].ToString() == "null" || jObject["data"].ToString().Length == 0)
                     {
-                        // 添加新属性
                         jObject["data"] = "true";
                     }
                 }
-                // 将JObject转换回字符串
+
                 string newJsonString = jObject.ToString();
-               
                 return JsonConvert.DeserializeObject<T>(newJsonString);
             }
-            else
+
+            var errorJson = await response.Content.ReadAsStringAsync();
+            try
             {
-                var errorJson = await response.Content.ReadAsStringAsync();
-                try
+                var jObject = JObject.Parse(errorJson);
+                if (jObject.ContainsKey("data"))
                 {
-                    var jObject = JObject.Parse(errorJson);
-                    if (jObject.ContainsKey("data"))
+                    if (jObject["data"].ToString() == "null" || jObject["data"].ToString().Length == 0)
                     {
-                        if (jObject["data"].ToString() == "null" || jObject["data"].ToString().Length == 0)
-                        {
-                            // 添加新属性
-                            jObject["data"] = "false";
-                        }
+                        jObject["data"] = "false";
                     }
-                    // 将JObject转换回字符串
-                    string newJsonString = jObject.ToString();
-                    return JsonConvert.DeserializeObject<T>(newJsonString);
-                }
-                catch
-                {
-                    throw new HttpRequestException($"请求失败: {response.StatusCode}");
                 }
+
+                string newJsonString = jObject.ToString();
+                return JsonConvert.DeserializeObject<T>(newJsonString);
+            }
+            catch
+            {
+                throw new HttpRequestException($"请求失败: {response.StatusCode}");
             }
         }
 
@@ -215,7 +211,5 @@ namespace LocalhostMES.Controller
             _httpClient?.Dispose();
             GC.SuppressFinalize(this);
         }
-        #endregion
     }
 }
-

+ 17 - 0
LocalhostMES/Api/Services/MesMomHttpEndpoints.cs

@@ -0,0 +1,17 @@
+namespace LocalhostMES.Api.Services
+{
+    /// <summary>
+    /// 零跑 MOM 云端接口地址(与本地 <c>/api/mes/*</c> 区分)。
+    /// </summary>
+    internal static class MesMomHttpEndpoints
+    {
+        internal const string BatterySnPrint =
+            "https://mom-jh-annex-api.leapmotor.com/app-mom-mes/api/battery/sn/print";
+
+        internal const string ReceiveSnKeyComponent =
+            "https://mom-jh-annex-api.leapmotor.com/app-mom-mes/api/task/receive/sn/keyComponent";
+
+        internal const string ManualSave =
+            "https://mom-jh-annex-api.leapmotor.com/app-mom-mes/api/task/receive/manualSave";
+    }
+}

+ 8 - 48
LocalhostMES/App.xaml

@@ -1,54 +1,14 @@
-<prism:PrismApplication x:Class="LocalhostMES.App"
+<prism:PrismApplication x:Class="LocalhostMES.App"
                         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                         xmlns:prism="http://prismlibrary.com/"
-                        xmlns:local="clr-namespace:LocalhostMES.Views">
+                        xmlns:conv="clr-namespace:LocalhostMES.Converters">
     <Application.Resources>
-        <!-- 转换器 -->
-        <local:ResultColorConverter x:Key="ResultColorConverter" />
-        <Style TargetType="Button">
-            <Setter Property="Background"
-                    Value="#007ACC" />
-            <Setter Property="Foreground"
-                    Value="White" />
-            <Setter Property="BorderThickness"
-                    Value="0" />
-            <Setter Property="Padding"
-                    Value="10,5" />
-            <Setter Property="Cursor"
-                    Value="Hand" />
-            <Style.Triggers>
-                <Trigger Property="IsMouseOver"
-                         Value="True">
-                    <Setter Property="Background"
-                            Value="#005A9E" />
-                </Trigger>
-                <Trigger Property="IsEnabled"
-                         Value="False">
-                    <Setter Property="Background"
-                            Value="#CCCCCC" />
-                </Trigger>
-            </Style.Triggers>
-        </Style>
-
-        <Style TargetType="TextBox">
-            <Setter Property="BorderThickness"
-                    Value="1" />
-            <Setter Property="BorderBrush"
-                    Value="#CCCCCC" />
-            <Setter Property="Padding"
-                    Value="5" />
-        </Style>
-
-        <Style TargetType="DataGrid">
-            <Setter Property="BorderThickness"
-                    Value="1" />
-            <Setter Property="BorderBrush"
-                    Value="#CCCCCC" />
-            <Setter Property="RowBackground"
-                    Value="White" />
-            <Setter Property="AlternatingRowBackground"
-                    Value="#F5F5F5" />
-        </Style>
+        <ResourceDictionary>
+            <ResourceDictionary.MergedDictionaries>
+                <ResourceDictionary Source="pack://application:,,,/Views/Resources/MesTabStyles.xaml" />
+            </ResourceDictionary.MergedDictionaries>
+            <conv:ResultColorConverter x:Key="ResultColorConverter" />
+        </ResourceDictionary>
     </Application.Resources>
 </prism:PrismApplication>

+ 15 - 16
LocalhostMES/App.xaml.cs

@@ -1,21 +1,13 @@
-using LocalhostMES.Controller;
+using LocalhostMES.Api.Hosting;
 using LocalhostMES.Core;
 using LocalhostMES.ViewModels;
+using LocalhostMES.ViewModels.Services;
+using LocalhostMES.ViewModels.Tabs;
 using LocalhostMES.Views;
-using Microsoft.Owin.Hosting;
 using Prism.Ioc;
-using Prism.Regions;
 using Prism.Unity;
 using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Configuration;
-using System.Data;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
 using System.Windows;
-using Unity;
 
 namespace LocalhostMES
 {
@@ -37,16 +29,23 @@ namespace LocalhostMES
         }
         protected override void RegisterTypes(IContainerRegistry containerRegistry)
         {
-            
-
+            containerRegistry.RegisterSingleton<IMesWorkspace, MesWorkspace>();
+            containerRegistry.RegisterSingleton<WebApiService>();
             containerRegistry.Register<MainViewModel>();
-
-
+            containerRegistry.Register<ApiTestViewModel>();
+            containerRegistry.Register<WorkOrderManagementViewModel>();
+            containerRegistry.Register<SnManagementViewModel>();
+            containerRegistry.Register<KeyPartManagementViewModel>();
+            containerRegistry.Register<PartCatalogViewModel>();
+            containerRegistry.Register<BindRecordsViewModel>();
+            containerRegistry.Register<ProcessRecordsViewModel>();
+            containerRegistry.Register<TcpServerViewModel>();
+            containerRegistry.Register<SystemSettingsViewModel>();
         }
         protected override void OnInitialized()
         {
             base.OnInitialized();
-            
+            ThemeManager.ApplyTheme(ThemeMode.Light);
         }
         private static System.Threading.Mutex mutex;
         protected override void OnStartup(StartupEventArgs e)

+ 0 - 175
LocalhostMES/Controller/WebApiService.cs

@@ -1,175 +0,0 @@
-using LocalhostMES.Core;
-using LocalhostMES.DataBase;
-using Microsoft.Owin.Hosting;
-using Org.BouncyCastle.Asn1.Ocsp;
-using Owin;
-using Prism.Ioc;
-using System;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Web.Http;
-using Unity;
-using Unity.Lifetime;
-using Unity.WebApi;
-
-
-namespace LocalhostMES.Controller
-{
-    public class WebApiService : IDisposable
-    {
-        private IDisposable _webApp;
-        private  CancellationTokenSource _cts = new CancellationTokenSource();
-        private  int _port;
-        private  StartOptions _startOptions;
-        private  string _baseUrl="192.168.1.26:8081";
-
-        public WebApiService()
-        {
-          
-        }
-        public void Init(int port = 8081) 
-        {
-            _port = port;
-            _baseUrl = $"http://192.168.1.26:{port}";
-            _startOptions = new StartOptions { Urls = { $"http://192.168.1.26:{port}",$"http://10.157.15.51:{port}" } };//", 
-
-        }
-        public async Task StartAsync()
-        {
-            try
-            {
-               
-
-                // 创建 Startup 实例并传入容器提供者
-                var startup = new Startup();
-
-                // 启动 Web App
-                _webApp = WebApp.Start(_startOptions, startup.Configuration);
-                // 启动Web API服务
-                // 初始化测试数据
-                InitializeTestData();
-                LogHelper.WriteLogInfo($"Web API服务已启动: {_baseUrl}");
-                Console.WriteLine($"Web API服务已启动: {_baseUrl}");
-            }
-            catch ( Exception ex )
-            {
-                Console.WriteLine($"启动Web API服务失败: {ex.Message}");
-                LogHelper.WriteLogInfo($"启动Web API服务失败: {ex.Message}");
-                throw;
-            }
-        }
-
-        private void InitializeTestData()
-        {
-            try
-            {
-                //// 添加一些测试工单
-                //var testWorkOrder = new Models.WorkOrderInfo
-                //{
-                //    WorkOrderNo = "GD-001",
-                //    MaterialCode = "T03GCD",
-                //    MaterialName = "T03贯穿灯",
-                //    PlannedQuantity = 100,
-                //    CompletedQuantity = 0,
-                //    Status = "2", // 已发布
-                //    LineCode = "RSC01",
-                //    CreateTime = DateTime.Now.AddDays(-1),
-                //    StartTime = DateTime.Now.AddHours(-2),
-                //    EndTime = DateTime.Now.AddHours(1),
-                //};
-
-                //DatabaseHelper.InsertWorkOrderInfo(testWorkOrder);
-
-                //// 生成测试SN
-                //for ( int i = 1; i <= 10; i++ )
-                //{
-                //    DatabaseHelper.InsertSnInfo(new Models.SnInfo
-                //    {
-                //        Sn = $"P-T03GCD-{DateTime.Now:yyMMddHHmm}-{i:D4}-{Guid.NewGuid().ToString("N").Substring(0, 6).ToUpper()}",
-                //        GenerateTime = DateTime.Now.AddMinutes(-i * 5),
-                //        WorkOrderNo = "GD-001",
-                //        PrintType = "产品码",
-                //        IsUsed = i > 5 // 前5个已使用
-                //    });
-                //}
-               
-
-                Console.WriteLine("测试数据初始化完成");
-            }
-            catch ( Exception ex )
-            {
-                Console.WriteLine($"初始化测试数据失败: {ex.Message}");
-            }
-        }
-
-        public Task StopAsync()
-        {
-            _webApp?.Dispose();
-            _webApp = null;
-            Console.WriteLine("Web API服务已停止");
-            return Task.CompletedTask;
-        }
-
-        public void Dispose()
-        {
-            _cts?.Cancel();
-            _cts?.Dispose();
-            _webApp?.Dispose();
-            GC.SuppressFinalize(this);
-        }
-
-        public bool IsRunning => _webApp != null;
-        public string BaseUrl => _baseUrl;
-    }
-
-    // OWIN Startup类
-    public class Startup
-    {
-       
-        public void Configuration(IAppBuilder app)
-        {
-            // 创建 Unity 容器
-            var container = new UnityContainer();
-
-
-            // 启用CORS
-            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
-
-            // 配置Web API
-            var config = new HttpConfiguration();
-
-            // 启用属性路由
-            config.MapHttpAttributeRoutes();
-
-            // 配置默认路由
-            config.Routes.MapHttpRoute(
-                name: "DefaultApi",
-                routeTemplate: "api/{controller}/{action}/{id}",
-                defaults: new { id = RouteParameter.Optional }
-            );
-
-            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling =
-                Newtonsoft.Json.ReferenceLoopHandling.Ignore;
-            config.Formatters.JsonFormatter.SerializerSettings.Formatting =
-                Newtonsoft.Json.Formatting.Indented;
-
-            // 使用Web API
-            app.UseWebApi(config);
-        }
-    }
-
-    // 辅助类,用于跨控制器共享数据
-    //public static class ConcurrentStorage
-    //{
-    //    //public static readonly System.Collections.Concurrent.ConcurrentDictionary<string, Models.WorkOrderInfo> WorkOrders
-    //    //    = new System.Collections.Concurrent.ConcurrentDictionary<string, Models.WorkOrderInfo>();
-    //    //public static readonly System.Collections.Concurrent.ConcurrentDictionary<string, System.Collections.Generic.List<Models.SnInfo>> WorkOrderSns
-    //    //    = new System.Collections.Concurrent.ConcurrentDictionary<string, System.Collections.Generic.List<Models.SnInfo>>();
-    //    //public static readonly System.Collections.Concurrent.ConcurrentBag<Models.BindRecord> BindRecords
-    //    //    = new System.Collections.Concurrent.ConcurrentBag<Models.BindRecord>();
-    //    //public static readonly System.Collections.Concurrent.ConcurrentBag<Models.ProcessRecord> ProcessRecords
-    //    //    = new System.Collections.Concurrent.ConcurrentBag<Models.ProcessRecord>();
-    //}
-}
-

+ 25 - 0
LocalhostMES/Converters/ResultColorConverter.cs

@@ -0,0 +1,25 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using System.Windows.Media;
+
+namespace LocalhostMES.Converters
+{
+    public class ResultColorConverter : IValueConverter
+    {
+        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+        {
+            if (value is string result)
+            {
+                return result == "OK" ? Brushes.Green : Brushes.Red;
+            }
+
+            return Brushes.Black;
+        }
+
+        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+        {
+            throw new NotImplementedException();
+        }
+    }
+}

+ 7 - 1
LocalhostMES/Core/Management.cs

@@ -1,4 +1,6 @@
-using LocalhostMES.Controller;
+using LocalhostMES.Api.Hosting;
+using LocalhostMES.Api.Services;
+using LocalhostMES.Models;
 using Prism.Ioc;
 using System;
 using System.Collections.Generic;
@@ -16,11 +18,15 @@ namespace LocalhostMES.Core
 
         private  WebApiService _webApiService;
         private MesApiClient _apiClient;
+        private WorkOrderNotifyTcpClient _workOrderNotifyTcpClient;
+        private List<WorkOrderInfo> _getOrderInfo = new List<WorkOrderInfo>();
 
         private bool _IsLocalhostMode = false;
 
         public MesApiClient ApiClient { get => _apiClient; set => _apiClient = value; }
         public WebApiService WebApiService { get => _webApiService; set => _webApiService = value; }
+        public WorkOrderNotifyTcpClient WorkOrderNotifyTcpClient { get => _workOrderNotifyTcpClient; set => _workOrderNotifyTcpClient = value; }
+        public List<WorkOrderInfo> GetOrderInfo { get => _getOrderInfo; set => _getOrderInfo = value; }
         public bool IsLocalhostMode { get => _IsLocalhostMode; set => _IsLocalhostMode = value; }
 
         public static Management management = new Management();

+ 46 - 0
LocalhostMES/Core/MesDataChangedEvent.cs

@@ -0,0 +1,46 @@
+using System;
+
+namespace LocalhostMES.Core
+{
+    [Flags]
+    public enum MesDataScope
+    {
+        None = 0,
+        WorkOrder = 1 << 0,
+        Sn = 1 << 1,
+        KeyPart = 1 << 2,
+        ParkingLot = 1 << 3,
+        BindRecord = 1 << 4,
+        ProcessRecord = 1 << 5
+    }
+
+    public sealed class MesDataChangedEventArgs : EventArgs
+    {
+        public MesDataChangedEventArgs(MesDataScope scope)
+        {
+            Scope = scope;
+        }
+
+        public MesDataScope Scope { get; }
+
+        public bool Has(MesDataScope target) => (Scope & target) == target;
+    }
+
+    /// <summary>
+    /// 统一的数据变更通知入口,供各业务写库后广播,界面按需订阅刷新。
+    /// </summary>
+    public static class MesDataChangedNotifier
+    {
+        public static event EventHandler<MesDataChangedEventArgs> Changed;
+
+        public static void Raise(MesDataScope scope)
+        {
+            if (scope == MesDataScope.None)
+            {
+                return;
+            }
+
+            Changed?.Invoke(null, new MesDataChangedEventArgs(scope));
+        }
+    }
+}

+ 56 - 0
LocalhostMES/Core/ThemeManager.cs

@@ -0,0 +1,56 @@
+using System.Windows;
+using System.Windows.Media;
+
+namespace LocalhostMES.Core
+{
+    public enum ThemeMode
+    {
+        Light,
+        Dark
+    }
+
+    public static class ThemeManager
+    {
+        public static ThemeMode CurrentTheme { get; private set; } = ThemeMode.Light;
+
+        public static void ApplyTheme(ThemeMode mode)
+        {
+            var app = Application.Current;
+            if (app == null)
+            {
+                return;
+            }
+
+            CurrentTheme = mode;
+            if (mode == ThemeMode.Dark)
+            {
+                SetBrush(app, "Win11WindowBrush", "#0F1115");
+                SetBrush(app, "Win11CardBrush", "#1A1D24");
+                SetBrush(app, "Win11BorderBrush", "#2C3340");
+                SetBrush(app, "Win11PrimaryBrush", "#3B82F6");
+                SetBrush(app, "Win11PrimaryHoverBrush", "#2563EB");
+                SetBrush(app, "Win11TextBrush", "#E5E7EB");
+                SetBrush(app, "Win11SubTextBrush", "#9CA3AF");
+                SetBrush(app, "Win11DangerBrush", "#EF4444");
+                SetBrush(app, "Win11SuccessBrush", "#22C55E");
+            }
+            else
+            {
+                SetBrush(app, "Win11WindowBrush", "#F5F6F8");
+                SetBrush(app, "Win11CardBrush", "#FFFFFF");
+                SetBrush(app, "Win11BorderBrush", "#DEE2E8");
+                SetBrush(app, "Win11PrimaryBrush", "#2563EB");
+                SetBrush(app, "Win11PrimaryHoverBrush", "#1D4ED8");
+                SetBrush(app, "Win11TextBrush", "#111827");
+                SetBrush(app, "Win11SubTextBrush", "#6B7280");
+                SetBrush(app, "Win11DangerBrush", "#DC2626");
+                SetBrush(app, "Win11SuccessBrush", "#16A34A");
+            }
+        }
+
+        private static void SetBrush(Application app, string key, string colorHex)
+        {
+            app.Resources[key] = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colorHex));
+        }
+    }
+}

+ 88 - 0
LocalhostMES/Core/WorkOrderNotifyTcpClient.cs

@@ -0,0 +1,88 @@
+using System;
+using System.Net;
+using System.Text;
+using System.Threading.Tasks;
+using TouchSocket.Core;
+using TouchSocket.Sockets;
+
+namespace LocalhostMES.Core
+{
+    public class WorkOrderNotifyTcpClient : IDisposable
+    {
+        private readonly TcpClient _tcpClient;
+        private readonly string _host;
+        private readonly int _port;
+
+        public event Action<string> MessageReceived;
+        public event Action<string> LogReceived;
+
+        public WorkOrderNotifyTcpClient(string host, int port)
+        {
+            _host = host;
+            _port = port;
+            _tcpClient = new TcpClient();
+
+            var config = new TouchSocketConfig();
+            config.SetRemoteIPHost(new IPHost(IPAddress.Parse(_host), _port));
+            config.SetTcpDataHandlingAdapter(() => new NormalDataHandlingAdapter());
+            config.ConfigurePlugins(a => { a.UseTcpReconnection(); });
+
+            _tcpClient.Setup(config);
+            _tcpClient.Connected = OnConnected;
+            _tcpClient.Closed = OnClosed;
+            _tcpClient.Received = OnReceived;
+        }
+
+        public bool IsConnected => _tcpClient.Online;
+
+        public async Task ConnectAsync()
+        {
+            if (_tcpClient.Online)
+            {
+                return;
+            }
+
+            await _tcpClient.ConnectAsync();
+        }
+
+        public void Disconnect()
+        {
+            if (_tcpClient.Online)
+            {
+                _tcpClient.Close();
+            }
+        }
+
+        private Task OnConnected(ITcpClient client, ConnectedEventArgs e)
+        {
+            LogReceived?.Invoke($"TCP客户端已连接 {_host}:{_port}");
+            return EasyTask.CompletedTask;
+        }
+
+        private Task OnClosed(ITcpClient client, ClosedEventArgs e)
+        {
+            LogReceived?.Invoke("TCP客户端已断开");
+            return EasyTask.CompletedTask;
+        }
+
+        private Task OnReceived(ITcpClient client, ReceivedDataEventArgs e)
+        {
+            var text = e.ByteBlock.Span.ToString(Encoding.UTF8);
+            LogReceived?.Invoke($"TCP收到消息: {text}");
+            MessageReceived?.Invoke(text);
+            return EasyTask.CompletedTask;
+        }
+
+        public void Dispose()
+        {
+            try
+            {
+                Disconnect();
+            }
+            catch
+            {
+            }
+            _tcpClient.Dispose();
+        }
+    }
+}

+ 112 - 39
LocalhostMES/DataBase/DatabaseHelper.cs

@@ -1,4 +1,4 @@
-using LocalhostMES.Core;
+using LocalhostMES.Core;
 using LocalhostMES.Enums;
 using LocalhostMES.Models;
 using SqlSugar;
@@ -15,10 +15,15 @@ namespace LocalhostMES.DataBase
 {
     public class DatabaseHelper
     {
+        private static void NotifyChanged(MesDataScope scope)
+        {
+            MesDataChangedNotifier.Raise(scope);
+        }
+
         public static SqlSugarScope Db = new SqlSugarScope(new ConnectionConfig()
         {
             //192.168.1.100
-            ConnectionString = "Database=LingPaoProject; Data Source=192.168.1.26; Port=3306;User Id=root; Password=root;Charset=utf8;AllowPublicKeyRetrieval=True;SslMode=None;",//连接符字串
+            ConnectionString = "Database=LingPaoProject; Data Source=127.0.0.1; Port=3306;User Id=root; Password=root;Charset=utf8;AllowPublicKeyRetrieval=True;SslMode=None;",//连接符字串
             DbType = SqlSugar.DbType.MySql,//数据库类型
             IsAutoCloseConnection = true //不设成true要手动close
         },
@@ -42,6 +47,7 @@ namespace LocalhostMES.DataBase
                 Db.CodeFirst.InitTables<ProcessRecord>();
                 Db.CodeFirst.InitTables<ParkingLot>();
                 Db.CodeFirst.InitTables<WorkOrderInfo>();
+                Db.CodeFirst.InitTables<LocalhostPartInfo>();
                 // 您的数据库操作代码
             }
             catch (AggregateException ex)
@@ -87,17 +93,31 @@ namespace LocalhostMES.DataBase
         }
         public static List<WorkOrderInfo> SelectWorkOrderInfo(string workOrderNo = null,bool islocalhost=false)
         {
-
-
-            
-
             if ( workOrderNo != null )
             {
-                return Db.Queryable<WorkOrderInfo>().Where(it => it.WorkOrderNo == workOrderNo).ToList();
+                var single = Db.Queryable<WorkOrderInfo>()
+                    .Where(it => it.WorkOrderNo == workOrderNo)
+                    .Select(it => new WorkOrderInfo
+                    {
+                        OrderNo = it.OrderNo,
+                        LineCode = it.LineCode,
+                        CreateTime = it.CreateTime,
+                        EndTime = it.EndTime,
+                        IsLocalhost = it.IsLocalhost,
+                        MaterialCode = it.MaterialCode,
+                        MaterialName = it.MaterialName,
+                        PlannedQuantity = it.PlannedQuantity,
+                        StartTime = it.StartTime,
+                        Status = it.Status,
+                        WorkOrderNo = it.WorkOrderNo,
+                        CompletedQuantity = SqlFunc.Subqueryable<SnInfo>().Where(s => s.WorkOrderNo == it.WorkOrderNo).Count()
+                    }).ToList();
+                NormalizeWorkOrderStatus(single);
+                return single;
             }
             else
             {
-                return Db.Queryable<WorkOrderInfo>().
+                var list = Db.Queryable<WorkOrderInfo>().
                     Select(it=>new WorkOrderInfo 
                     {OrderNo=it.OrderNo,
                         LineCode=it.LineCode,
@@ -111,6 +131,37 @@ namespace LocalhostMES.DataBase
                         Status=it.Status,
                         WorkOrderNo=it.WorkOrderNo, 
                         CompletedQuantity=SqlFunc.Subqueryable<SnInfo>().Where(s=>s.WorkOrderNo==it.WorkOrderNo).Count() }).ToList();
+                NormalizeWorkOrderStatus(list);
+                return list;
+            }
+        }
+
+        private static void NormalizeWorkOrderStatus(List<WorkOrderInfo> workOrders)
+        {
+            if (workOrders == null || workOrders.Count == 0)
+            {
+                return;
+            }
+
+            var changed = false;
+            foreach (var workOrder in workOrders)
+            {
+                if (workOrder.PlannedQuantity > 0 &&
+                    workOrder.CompletedQuantity >= workOrder.PlannedQuantity &&
+                    workOrder.Status != "6")
+                {
+                    workOrder.Status = "6";
+                    Db.Updateable<WorkOrderInfo>()
+                        .SetColumns(it => new WorkOrderInfo { Status = "6" })
+                        .Where(it => it.WorkOrderNo == workOrder.WorkOrderNo)
+                        .ExecuteCommand();
+                    changed = true;
+                }
+            }
+
+            if (changed)
+            {
+                NotifyChanged(MesDataScope.WorkOrder);
             }
         }
 
@@ -119,6 +170,7 @@ namespace LocalhostMES.DataBase
 
             if ( Db.Storageable(info).ExecuteCommand() == 1 )
             {
+                NotifyChanged(MesDataScope.WorkOrder);
                 return true;
             }
             return false;
@@ -129,6 +181,7 @@ namespace LocalhostMES.DataBase
 
             if ( Db.Updateable(info).Where(it => it.WorkOrderNo == info.WorkOrderNo).ExecuteCommand() == 1 )
             {
+                NotifyChanged(MesDataScope.WorkOrder);
                 return true;
             }
             return false;
@@ -139,6 +192,7 @@ namespace LocalhostMES.DataBase
 
             if ( Db.Deleteable(info).Where(it => it.WorkOrderNo == info.WorkOrderNo).ExecuteCommand() == 1 )
             {
+                NotifyChanged(MesDataScope.WorkOrder);
                 return true;
             }
             return false;
@@ -166,6 +220,7 @@ namespace LocalhostMES.DataBase
 
             if ( Db.Storageable(info).ExecuteCommand() == 1 )
             {
+                NotifyChanged(MesDataScope.Sn);
                 return true;
             }
             return false;
@@ -176,6 +231,7 @@ namespace LocalhostMES.DataBase
 
             if (Db.Storageable(info).ExecuteCommand() == info.Count)
             {
+                NotifyChanged(MesDataScope.Sn);
                 return true;
             }
             return false;
@@ -186,6 +242,7 @@ namespace LocalhostMES.DataBase
 
             if ( Db.Updateable(info).Where(it => it.Sn == info.Sn).ExecuteCommand() == 1 )
             {
+                NotifyChanged(MesDataScope.Sn);
                 return true;
             }
             return false;
@@ -196,6 +253,7 @@ namespace LocalhostMES.DataBase
 
             if ( Db.Deleteable(info).Where(it => it.Sn == info.Sn).ExecuteCommand() == 1 )
             {
+                NotifyChanged(MesDataScope.Sn);
                 return true;
             }
             return false;
@@ -228,6 +286,7 @@ namespace LocalhostMES.DataBase
 
             if ( Db.Storageable(info).ExecuteCommand() == 1 )
             {
+                NotifyChanged(MesDataScope.BindRecord);
                 return true;
             }
             return false;
@@ -238,6 +297,7 @@ namespace LocalhostMES.DataBase
 
             if ( Db.Updateable(info).Where(it => it.Sn == info.Sn).ExecuteCommand() == 1 )
             {
+                NotifyChanged(MesDataScope.BindRecord);
                 return true;
             }
             return false;
@@ -249,6 +309,7 @@ namespace LocalhostMES.DataBase
             {
                 if ( Db.Deleteable<BindRecord>().Where(it => it.Sn == sn).ExecuteCommand() == 1 )
                 {
+                    NotifyChanged(MesDataScope.BindRecord);
                     return true;
                 }
             }
@@ -256,6 +317,7 @@ namespace LocalhostMES.DataBase
             {
                 if ( Db.Deleteable<BindRecord>().ExecuteCommand() != 0 )
                 {
+                    NotifyChanged(MesDataScope.BindRecord);
                     return true;
                 }
             }
@@ -287,6 +349,7 @@ namespace LocalhostMES.DataBase
 
             if ( Db.Storageable(info).ExecuteCommand() == 1 )
             {
+                NotifyChanged(MesDataScope.ProcessRecord);
                 return true;
             }
             return false;
@@ -297,6 +360,7 @@ namespace LocalhostMES.DataBase
 
             if ( Db.Updateable(info).Where(it => it.Sn == info.Sn).ExecuteCommand() == 1 )
             {
+                NotifyChanged(MesDataScope.ProcessRecord);
                 return true;
             }
             return false;
@@ -307,69 +371,78 @@ namespace LocalhostMES.DataBase
 
             if ( Db.Deleteable<ProcessRecord>().Where(it => it.Sn == sn).ExecuteCommand() == 1 )
             {
+                NotifyChanged(MesDataScope.ProcessRecord);
                 return true;
             }
             return false;
         }
 
 
-        public static List<LocalhostPartInfo> SelectPartInfo(StationType StationCode =  StationType.OP10)
+        public static List<LocalhostPartInfo> SelectPartInfo(KeyPartStationType stationType)
         {
-            var query = Db.Queryable<LocalhostPartInfo>().Where(it => it.FormulaType == StationCode); ;
-            return query.ToList();
-
+            return Db.Queryable<LocalhostPartInfo>().Where(it => it.StationType == stationType).ToList();
         }
+
         public static bool InsertPartInfo(LocalhostPartInfo info)
         {
-
-            if (Db.Storageable(info).ExecuteCommand() == 1)
+            var ok = Db.Storageable(info).ExecuteCommand() > 0;
+            if (ok)
             {
-                return true;
+                NotifyChanged(MesDataScope.KeyPart);
             }
-            return false;
-        }
 
-    
+            return ok;
+        }
 
-        public static bool DeletePartInfo(StationType StationCode, string MaterialCode)
+        public static bool DeletePartInfo(KeyPartStationType stationType, string partNum)
         {
-
-            if (Db.Deleteable<LocalhostPartInfo>().Where(it => it.FormulaType == StationCode&&it.MaterialCode==MaterialCode).ExecuteCommand() == 1)
+            var ok = Db.Deleteable<LocalhostPartInfo>()
+                .Where(it => it.StationType == stationType && it.PartNum == partNum)
+                .ExecuteCommand() >= 1;
+            if (ok)
             {
-                return true;
+                NotifyChanged(MesDataScope.KeyPart);
             }
-            return false;
-        }
-
-    
 
+            return ok;
+        }
 
-        public static List<ParkingLot> SelectParkingLot(StationType StationCode = StationType.OP10)
+        public static List<ParkingLot> SelectParkingLot()
         {
-            var query = Db.Queryable<ParkingLot>().Where(it => it.FormulaType == StationCode); ;
-            return query.ToList();
-
+            return Db.Queryable<ParkingLot>().OrderBy(it => it.Id).ToList();
         }
+
         public static bool InsertParkingLot(ParkingLot info)
         {
-
-            if (Db.Storageable(info).ExecuteCommand() == 1)
+            var ok = Db.Storageable(info).ExecuteCommand() > 0;
+            if (ok)
             {
-                return true;
+                NotifyChanged(MesDataScope.ParkingLot);
             }
-            return false;
+
+            return ok;
         }
 
+        public static bool UpdateParkingLot(ParkingLot info)
+        {
+            var ok = Db.Updateable(info).Where(it => it.Id == info.Id).ExecuteCommand() == 1;
+            if (ok)
+            {
+                NotifyChanged(MesDataScope.ParkingLot);
+            }
 
+            return ok;
+        }
 
-        public static bool DeleteParkingLot(StationType StationCode, int id)
+        public static bool DeleteParkingLot(int id)
         {
-
-            if (Db.Deleteable<ParkingLot>().Where(it => it.FormulaType == StationCode && it.Id == id).ExecuteCommand() == 1)
+            var ok = Db.Deleteable<ParkingLot>().Where(it => it.Id == id).ExecuteCommand() == 1;
+            if (ok)
             {
-                return true;
+                NotifyChanged(MesDataScope.ParkingLot);
             }
-            return false;
+
+            return ok;
         }
         
 

+ 17 - 0
LocalhostMES/Enums/KeyPartStationType.cs

@@ -0,0 +1,17 @@
+namespace LocalhostMES.Enums
+{
+    /// <summary>
+    /// 关键件维护用简化工站类型(与产线详细左右工位枚举区分)。
+    /// </summary>
+    public enum KeyPartStationType
+    {
+        OP10,
+        OP20,
+        OP30,
+        OP40,
+        OP50,
+        OP60,
+        OP70,
+        OP80
+    }
+}

+ 171 - 0
LocalhostMES/Helpers/DateCodeConverter.cs

@@ -0,0 +1,171 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace LocalhostMES.Helpers
+{
+    /// <summary>
+    /// 年/月/日与单字符编码互转(用于本地 SN 等场景)。
+    /// </summary>
+    public static class DateCodeConverter
+    {
+        private static readonly Dictionary<int, string> yearToCode = new Dictionary<int, string>
+        {
+            {2018, "1"}, {2019, "2"}, {2020, "3"}, {2021, "4"}, {2022, "5"},
+            {2023, "6"}, {2024, "7"}, {2025, "8"}, {2026, "9"}, {2027, "A"},
+            {2028, "B"}, {2029, "C"}, {2030, "D"}, {2031, "E"}, {2032, "F"},
+            {2033, "G"}, {2034, "H"}, {2035, "J"}, {2036, "K"}, {2037, "L"},
+            {2038, "M"}, {2039, "N"}, {2040, "P"}, {2041, "R"}, {2042, "S"},
+            {2043, "T"}, {2044, "V"}, {2045, "W"}, {2046, "X"}, {2047, "Y"},
+            {2048, "1"}, {2049, "2"}, {2050, "3"}, {2051, "4"}, {2052, "5"},
+            {2053, "6"}, {2054, "7"}, {2055, "8"}, {2056, "9"}, {2057, "A"}
+        };
+
+        private static readonly Dictionary<int, string> monthToCode = new Dictionary<int, string>
+        {
+            {1, "1"}, {2, "2"}, {3, "3"}, {4, "4"}, {5, "5"}, {6, "6"},
+            {7, "7"}, {8, "8"}, {9, "9"}, {10, "A"}, {11, "B"}, {12, "C"}
+        };
+
+        private static readonly Dictionary<int, string> dayToCode = new Dictionary<int, string>
+        {
+            {1, "1"}, {2, "2"}, {3, "3"}, {4, "4"}, {5, "5"}, {6, "6"}, {7, "7"}, {8, "8"}, {9, "9"},
+            {10, "A"}, {11, "B"}, {12, "C"}, {13, "D"}, {14, "E"}, {15, "F"}, {16, "G"},
+            {17, "H"}, {18, "J"}, {19, "K"}, {20, "L"}, {21, "M"}, {22, "N"}, {23, "P"}, {24, "R"},
+            {25, "S"}, {26, "T"}, {27, "U"}, {28, "V"}, {29, "W"}, {30, "X"}, {31, "Y"}
+        };
+
+        private static readonly Dictionary<string, int> codeToYear;
+        private static readonly Dictionary<string, int> codeToMonth;
+        private static readonly Dictionary<string, int> codeToDay;
+
+        static DateCodeConverter()
+        {
+            codeToYear = yearToCode
+                .GroupBy(kv => kv.Value)
+                .ToDictionary(g => g.Key, g => g.Last().Key);
+
+            codeToMonth = monthToCode
+                .ToDictionary(kv => kv.Value, kv => kv.Key);
+
+            codeToDay = dayToCode
+                .ToDictionary(kv => kv.Value, kv => kv.Key);
+        }
+
+        public static string GetYearCode(int year)
+        {
+            return yearToCode.TryGetValue(year, out string code) ? code : "未知年份";
+        }
+
+        public static int? GetYearByCode(string code)
+        {
+            return codeToYear.TryGetValue(code, out int year) ? year : (int?)null;
+        }
+
+        public static List<int> GetAllYearsByCode(string code)
+        {
+            return yearToCode
+                .Where(kv => kv.Value == code)
+                .Select(kv => kv.Key)
+                .ToList();
+        }
+
+        public static string GetMonthCode(int month)
+        {
+            if (month < 1 || month > 12)
+                return "无效月份";
+
+            return monthToCode.TryGetValue(month, out string code) ? code : "未知月份";
+        }
+
+        public static int? GetMonthByCode(string code)
+        {
+            return codeToMonth.TryGetValue(code, out int month) ? month : (int?)null;
+        }
+
+        public static string GetDayCode(int day)
+        {
+            if (day < 1 || day > 31)
+                return "无效日期";
+
+            return dayToCode.TryGetValue(day, out string code) ? code : "未知日期";
+        }
+
+        public static int? GetDayByCode(string code)
+        {
+            return codeToDay.TryGetValue(code, out int day) ? day : (int?)null;
+        }
+
+        public static string ConvertToDateCode(DateTime date)
+        {
+            string yearCode = GetYearCode(date.Year);
+            string monthCode = GetMonthCode(date.Month);
+            string dayCode = GetDayCode(date.Day);
+
+            if (yearCode == "未知年份" || monthCode == "无效月份" || dayCode == "无效日期" || dayCode == "未知日期")
+            {
+                return "无效日期";
+            }
+
+            return $"{yearCode}{monthCode}{dayCode}";
+        }
+
+        public static DateTime? ConvertFromDateCode(string dateCode)
+        {
+            if (string.IsNullOrEmpty(dateCode) || dateCode.Length != 3)
+                return null;
+
+            string yearCode = dateCode.Substring(0, 1);
+            string monthCode = dateCode.Substring(1, 1);
+            string dayCode = dateCode.Substring(2, 1);
+
+            var year = GetYearByCode(yearCode);
+            var month = GetMonthByCode(monthCode);
+            var day = GetDayByCode(dayCode);
+
+            if (!year.HasValue || !month.HasValue || !day.HasValue)
+                return null;
+
+            try
+            {
+                return new DateTime(year.Value, month.Value, day.Value);
+            }
+            catch (ArgumentOutOfRangeException)
+            {
+                return null;
+            }
+        }
+
+        public static List<DateTime> ConvertAllFromDateCode(string dateCode)
+        {
+            var result = new List<DateTime>();
+
+            if (string.IsNullOrEmpty(dateCode) || dateCode.Length != 3)
+                return result;
+
+            string yearCode = dateCode.Substring(0, 1);
+            string monthCode = dateCode.Substring(1, 1);
+            string dayCode = dateCode.Substring(2, 1);
+
+            var allYears = GetAllYearsByCode(yearCode);
+            var month = GetMonthByCode(monthCode);
+            var day = GetDayByCode(dayCode);
+
+            if (allYears.Count == 0 || !month.HasValue || !day.HasValue)
+                return result;
+
+            foreach (var year in allYears)
+            {
+                try
+                {
+                    result.Add(new DateTime(year, month.Value, day.Value));
+                }
+                catch (ArgumentOutOfRangeException)
+                {
+                }
+            }
+
+            return result;
+        }
+    }
+}

+ 11 - 27
LocalhostMES/Controller/PrismDependencyResolver.cs → LocalhostMES/Infrastructure/PrismDependencyResolver.cs

@@ -1,15 +1,15 @@
-using Prism.Ioc;
+using Prism.Ioc;
 using System;
 using System.Collections.Generic;
 using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
 using System.Web.Http.Controllers;
 using System.Web.Http.Dependencies;
 
-namespace LocalhostMES.Controller
+namespace LocalhostMES.Infrastructure
 {
-    // 自定义的依赖解析器
+    /// <summary>
+    /// Web API 与 Prism 容器桥接(需要时可在此扩展从容器解析的类型)。
+    /// </summary>
     public class PrismDependencyResolver : IDependencyResolver
     {
         private readonly IContainerProvider _containerProvider;
@@ -21,7 +21,6 @@ namespace LocalhostMES.Controller
 
         public IDependencyScope BeginScope()
         {
-            // 返回同一个作用域,因为 Prism 容器通常不支持作用域
             return this;
         }
 
@@ -29,25 +28,20 @@ namespace LocalhostMES.Controller
         {
             try
             {
-                // 尝试从 Prism 容器解析
-                // 1. 如果是控制器,从 Prism 容器解析
                 if (typeof(IHttpController).IsAssignableFrom(serviceType))
                 {
                     return _containerProvider.Resolve(serviceType);
                 }
 
-                // 2. 如果是我们自己注册的类型,从 Prism 容器解析
-                if (IsCustomType(serviceType))
+                if (IsRegisteredCustomType(serviceType))
                 {
                     return _containerProvider.Resolve(serviceType);
                 }
 
-                // 3. 其他类型(Web API 内置服务)返回 null,让 Web API 使用默认解析器
                 return null;
             }
             catch (ContainerResolutionException)
             {
-                // 如果类型未注册,返回 null(Web API 会使用默认构造函数)
                 return null;
             }
             catch
@@ -55,26 +49,17 @@ namespace LocalhostMES.Controller
                 return null;
             }
         }
-        private bool IsCustomType(Type serviceType)
-        {
-            // 检查是否是我们自定义的类型
-            var typeName = serviceType.FullName ?? "";
-
-            // 添加我们需要处理的类型
-            var customTypes = new[]
-            {
-                "LocalhostMES.Controller.Management",
-                "LocalhostMES.Controller.ApiClient",
-                // 添加其他需要从 Prism 容器解析的类型
-            };
 
-            return Array.Exists(customTypes, t => typeName.Contains(t));
+        private static bool IsRegisteredCustomType(Type serviceType)
+        {
+            // 当前控制器均使用无参构造;若后续有需注入单例,在此按类型或命名空间登记。
+            return false;
         }
+
         public IEnumerable<object> GetServices(Type serviceType)
         {
             try
             {
-                // 对于集合类型,尝试解析 IEnumerable<T>
                 var enumerableType = typeof(IEnumerable<>).MakeGenericType(serviceType);
                 var services = _containerProvider.Resolve(enumerableType);
                 return (IEnumerable<object>)services;
@@ -87,7 +72,6 @@ namespace LocalhostMES.Controller
 
         public void Dispose()
         {
-            // 清理资源
         }
     }
 }

+ 97 - 5
LocalhostMES/LocalhostMES.csproj

@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="utf-8"?>
+<?xml version="1.0" encoding="utf-8"?>
 <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
   <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
   <PropertyGroup>
@@ -277,6 +277,12 @@
     <Reference Include="SqlSugar, Version=5.1.4.207, Culture=neutral, processorArchitecture=MSIL">
       <HintPath>..\packages\SqlSugar.5.1.4.207\lib\SqlSugar.dll</HintPath>
     </Reference>
+    <Reference Include="TouchSocket, Version=3.1.17.0, Culture=neutral, PublicKeyToken=5f39d7da98dac6a9, processorArchitecture=MSIL">
+      <HintPath>..\packages\TouchSocket.3.1.17\lib\net472\TouchSocket.dll</HintPath>
+    </Reference>
+    <Reference Include="TouchSocket.Core, Version=3.1.17.0, Culture=neutral, PublicKeyToken=d6c415a2f58eda72, processorArchitecture=MSIL">
+      <HintPath>..\packages\TouchSocket.Core.3.1.17\lib\net472\TouchSocket.Core.dll</HintPath>
+    </Reference>
     <Reference Include="System" />
     <Reference Include="System.Buffers, Version=4.0.5.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
       <HintPath>..\packages\System.Buffers.4.6.1\lib\net462\System.Buffers.dll</HintPath>
@@ -406,21 +412,67 @@
       <DependentUpon>App.xaml</DependentUpon>
       <SubType>Code</SubType>
     </Compile>
-    <Compile Include="Controller\MesApiClient.cs" />
-    <Compile Include="Controller\MesController.cs" />
-    <Compile Include="Controller\PrismDependencyResolver.cs" />
-    <Compile Include="Controller\WebApiService.cs" />
+    <Compile Include="Api\Controllers\MesController.cs" />
+    <Compile Include="Api\Hosting\OwinWebApiStartup.cs" />
+    <Compile Include="Api\Hosting\WebApiService.cs" />
+    <Compile Include="Api\Services\MesApiClient.cs" />
+    <Compile Include="Api\Services\MesMomHttpEndpoints.cs" />
+    <Compile Include="Helpers\DateCodeConverter.cs" />
+    <Compile Include="Infrastructure\PrismDependencyResolver.cs" />
     <Compile Include="Core\LogHelper.cs" />
+    <Compile Include="Core\MesDataChangedEvent.cs" />
+    <Compile Include="Core\ThemeManager.cs" />
     <Compile Include="Core\Management.cs" />
+    <Compile Include="Core\WorkOrderNotifyTcpClient.cs" />
     <Compile Include="Core\TrayIconManager.cs" />
     <Compile Include="DataBase\DatabaseHelper.cs" />
     <Compile Include="Enums\FormulaPartType.cs" />
+    <Compile Include="Enums\KeyPartStationType.cs" />
     <Compile Include="Enums\StationType.cs" />
     <Compile Include="Models\MesModel.cs" />
+    <Compile Include="Converters\ResultColorConverter.cs" />
     <Compile Include="ViewModels\MainViewModel.cs" />
+    <Compile Include="ViewModels\Services\IMesWorkspace.cs" />
+    <Compile Include="ViewModels\Services\MesWorkspace.cs" />
+    <Compile Include="ViewModels\Tabs\ApiTestViewModel.cs" />
+    <Compile Include="ViewModels\Tabs\BindRecordsViewModel.cs" />
+    <Compile Include="ViewModels\Tabs\KeyPartManagementViewModel.cs" />
+    <Compile Include="ViewModels\Tabs\PartCatalogViewModel.cs" />
+    <Compile Include="ViewModels\Tabs\ProcessRecordsViewModel.cs" />
+    <Compile Include="ViewModels\Tabs\SnManagementViewModel.cs" />
+    <Compile Include="ViewModels\Tabs\SystemSettingsViewModel.cs" />
+    <Compile Include="ViewModels\Tabs\TcpServerViewModel.cs" />
+    <Compile Include="ViewModels\Tabs\WorkOrderManagementViewModel.cs" />
     <Compile Include="Views\MainView.xaml.cs">
       <DependentUpon>MainView.xaml</DependentUpon>
     </Compile>
+    <Compile Include="Views\Tabs\ApiTestView.xaml.cs">
+      <DependentUpon>ApiTestView.xaml</DependentUpon>
+    </Compile>
+    <Compile Include="Views\Tabs\BindRecordsView.xaml.cs">
+      <DependentUpon>BindRecordsView.xaml</DependentUpon>
+    </Compile>
+    <Compile Include="Views\Tabs\KeyPartManagementView.xaml.cs">
+      <DependentUpon>KeyPartManagementView.xaml</DependentUpon>
+    </Compile>
+    <Compile Include="Views\Tabs\PartCatalogView.xaml.cs">
+      <DependentUpon>PartCatalogView.xaml</DependentUpon>
+    </Compile>
+    <Compile Include="Views\Tabs\ProcessRecordsView.xaml.cs">
+      <DependentUpon>ProcessRecordsView.xaml</DependentUpon>
+    </Compile>
+    <Compile Include="Views\Tabs\SnManagementView.xaml.cs">
+      <DependentUpon>SnManagementView.xaml</DependentUpon>
+    </Compile>
+    <Compile Include="Views\Tabs\SystemSettingsView.xaml.cs">
+      <DependentUpon>SystemSettingsView.xaml</DependentUpon>
+    </Compile>
+    <Compile Include="Views\Tabs\TcpServerView.xaml.cs">
+      <DependentUpon>TcpServerView.xaml</DependentUpon>
+    </Compile>
+    <Compile Include="Views\Tabs\WorkOrderManagementView.xaml.cs">
+      <DependentUpon>WorkOrderManagementView.xaml</DependentUpon>
+    </Compile>
   </ItemGroup>
   <ItemGroup>
     <Compile Include="Properties\AssemblyInfo.cs">
@@ -455,6 +507,46 @@
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>
     </Page>
+    <Page Include="Views\Resources\MesTabStyles.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
+    <Page Include="Views\Tabs\ApiTestView.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
+    <Page Include="Views\Tabs\BindRecordsView.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
+    <Page Include="Views\Tabs\KeyPartManagementView.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
+    <Page Include="Views\Tabs\PartCatalogView.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
+    <Page Include="Views\Tabs\ProcessRecordsView.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
+    <Page Include="Views\Tabs\SnManagementView.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
+    <Page Include="Views\Tabs\SystemSettingsView.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
+    <Page Include="Views\Tabs\TcpServerView.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
+    <Page Include="Views\Tabs\WorkOrderManagementView.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
   </ItemGroup>
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
   <Import Project="..\packages\System.ValueTuple.4.6.1\build\net471\System.ValueTuple.targets" Condition="Exists('..\packages\System.ValueTuple.4.6.1\build\net471\System.ValueTuple.targets')" />

+ 67 - 56
LocalhostMES/Models/MesModel.cs

@@ -1,4 +1,4 @@
-using LocalhostMES.Enums;
+using LocalhostMES.Enums;
 using Prism.Mvvm;
 using System;
 using System.Collections.Generic;
@@ -54,21 +54,61 @@ namespace LocalhostMES.Models
     {
 
         private string _WorkOrderNo;
+        private string _status;
 
         [SqlSugar.SugarColumn(IsPrimaryKey = true)]
         public string WorkOrderNo { get => _WorkOrderNo; set { SetProperty(ref _WorkOrderNo, value); } }
 
-        public bool IsLocalhost { get; set;}
+        public bool IsLocalhost { get; set;}=false;
         public string OrderNo { get; set; } = "0";
         public string MaterialCode { get; set; }
         public string MaterialName { get; set; }
         public int PlannedQuantity { get; set; }
         public int CompletedQuantity { get; set; }
-        public string Status { get; set; }
+        public string Status
+        {
+            get => _status;
+            set
+            {
+                if (SetProperty(ref _status, value))
+                {
+                    RaisePropertyChanged(nameof(StatusDisplay));
+                }
+            }
+        }
+
+        [SqlSugar.SugarColumn(IsIgnore = true)]
+        public string StatusDisplay => GetStatusDisplay(Status);
+
         public string LineCode { get; set; }
         public DateTime CreateTime { get; set; }
         public DateTime? StartTime { get; set; }
         public DateTime? EndTime { get; set; }
+
+        public static string GetStatusDisplay(string status)
+        {
+            switch (status)
+            {
+                case "0":
+                    return "已创建";
+                case "1":
+                    return "已排产";
+                case "2":
+                    return "已发布";
+                case "3":
+                    return "关闭";
+                case "4":
+                    return "已锁定";
+                case "5":
+                    return "已开工";
+                case "6":
+                    return "已完成";
+                case "7":
+                    return "异常完工";
+                default:
+                    return status;
+            }
+        }
     }
     #endregion
 
@@ -144,27 +184,22 @@ namespace LocalhostMES.Models
         public string materialType { get; set; }                 // 关键件类型
         public string positionNo { get; set; }                   // 位置序号
     }
+    /// <summary>
+    /// 本地维护的关键件清单(工站类型 + 关键件号 + 数量)。
+    /// </summary>
     public class LocalhostPartInfo : BindableBase
     {
+        private KeyPartStationType _stationType;
+        private string _partNum;
+        private decimal _partQty;
 
+        [SqlSugar.SugarColumn(IsPrimaryKey = true)]
+        public KeyPartStationType StationType { get => _stationType; set => SetProperty(ref _stationType, value); }
 
-        private StationType _FormulaType;
-        private string _PartNum;                   // 关键件条码
-        private decimal _PartQty;                   // 关键件数量
-        private string _MaterialCode;              // 关键件物料
-        private string _OldPartNum;               // 原关键件条码
-        private string _MaterialType="1";         // 关键件类型
-        private string _PositionNo="";                // 位置序号
-
-        public StationType FormulaType { get => _FormulaType; set { SetProperty(ref _FormulaType, value); } }
+        [SqlSugar.SugarColumn(IsPrimaryKey = true, Length = 128)]
+        public string PartNum { get => _partNum; set => SetProperty(ref _partNum, value); }
 
-        public string PartNum { get => _PartNum; set { SetProperty(ref _PartNum, value); } }
-        public decimal PartQty { get => _PartQty; set { SetProperty(ref _PartQty, value); } }
-        [SqlSugar.SugarColumn(IsPrimaryKey = true)]
-        public string MaterialCode { get => _MaterialCode; set { SetProperty(ref _MaterialCode, value); } }
-        public string OldPartNum { get => _OldPartNum; set { SetProperty(ref _OldPartNum, value); } }
-        public string MaterialType { get => _MaterialType; set { SetProperty(ref _MaterialType, value); } }
-        public string PositionNo { get => _PositionNo; set { SetProperty(ref _PositionNo, value); } }
+        public decimal PartQty { get => _partQty; set => SetProperty(ref _partQty, value); }
     }
     public class BindRecord
     {
@@ -272,46 +307,22 @@ namespace LocalhostMES.Models
         public string PartNum { get => _PartNum; set { SetProperty(ref _PartNum, value); } }
     }
 
+    /// <summary>
+    /// 本地零件目录(名称 + 数量)。
+    /// </summary>
     public class ParkingLot : BindableBase
     {
-        private int _id = 0;
-        private StationType _FormulaType;
-        private string _SerialNumber;
-        private string _PartNumber;
-        private string _PartName;
-        private string _PlanNum;
-        private string _UseNum;
-        private int _CompletedNum;
-
-
-        public StationType FormulaType { get => _FormulaType; set { SetProperty(ref _FormulaType, value); } }
-        /// <summary>
-        /// 序号
-        /// </summary>
-        public string SerialNumber { get => _SerialNumber; set { SetProperty(ref _SerialNumber, value); } }
-        /// <summary>
-        /// 零件号
-        /// </summary>
-        public string PartNumber { get => _PartNumber; set { SetProperty(ref _PartNumber, value); } }
-        /// <summary>
-        /// 零件名称
-        /// </summary>
-        public string PartName { get => _PartName; set { SetProperty(ref _PartName, value); } }
-        /// <summary>
-        /// 计划数量
-        /// </summary>
-        public string PlanNum { get => _PlanNum; set { SetProperty(ref _PlanNum, value); } }
-        /// <summary>
-        /// 使用数量
-        /// </summary>
-        public string UseNum { get => _UseNum; set { SetProperty(ref _UseNum, value); } }
-        /// <summary>
-        /// 已完成数量
-        /// </summary>
-        public int CompletedNum { get => _CompletedNum; set { SetProperty(ref _CompletedNum, value); } }
+        private int _id;
+        private string _partName;
+        private decimal _quantity;
 
-        [SqlSugar.SugarColumn(IsPrimaryKey = true,IsIdentity =true)]
-        public int Id { get => _id; set { SetProperty(ref _id, value); } }
+        [SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
+        public int Id { get => _id; set => SetProperty(ref _id, value); }
+
+        [SqlSugar.SugarColumn(Length = 200)]
+        public string PartName { get => _partName; set => SetProperty(ref _partName, value); }
+
+        public decimal Quantity { get => _quantity; set => SetProperty(ref _quantity, value); }
     }
     public class ResultInfo : BindableBase
     {

+ 32 - 958
LocalhostMES/ViewModels/MainViewModel.cs

@@ -1,1001 +1,75 @@
-using LocalhostMES.Controller;
-using LocalhostMES.Core;
 using LocalhostMES.DataBase;
-using LocalhostMES.Models;
-using LocalhostMES.Views;
-using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
+using LocalhostMES.ViewModels.Services;
 using Prism.Commands;
-using Prism.Ioc;
 using Prism.Mvvm;
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
 using System.ComponentModel;
-using System.ComponentModel.Composition.Primitives;
-using System.Drawing;
-using System.Linq;
-using System.Net;
-using System.Text;
-using System.Threading.Tasks;
-using System.Web.UI.WebControls;
-using System.Windows;
-using System.Windows.Threading;
-using System.Xml.Linq;
-
 namespace LocalhostMES.ViewModels
 {
-    public class MainViewModel:BindableBase
+    /// <summary>
+    /// 主窗口壳:初始化/释放共享会话与 Web API 宿主。
+    /// </summary>
+    public class MainViewModel : BindableBase
     {
-        IContainerProvider _container;
-        private Management management;
-
-        private bool _isServiceRunning = false;
-
-        #region 属性
-        private int _ServerPort=8081;
-        public int ServerPort { get => _ServerPort; set { SetProperty(ref _ServerPort, value); } }
-
-        private string  _ApiUrl ="http://localhost:5000";
-        public string ApiUrl { get => _ApiUrl; set { SetProperty(ref _ApiUrl, value); } }
-        private string  _AppKey = "API_XXM";
-        public string AppKey { get => _AppKey; set { SetProperty(ref _AppKey, value); } }
-        private string _Token = "7c5766afa3ca82f8a21af120f9b1cca6d";
-        public string Token { get => _Token; set { SetProperty(ref _Token, value); } }
-
-
-        private ObservableCollection<string> _Logs=new ObservableCollection<string>();
-        public ObservableCollection<string> Logs { get => _Logs; set { SetProperty(ref _Logs, value); } }
-
-
-        private  ObservableCollection<WorkOrderInfo> _dgWorkOrders =new ObservableCollection<WorkOrderInfo>();
-        public ObservableCollection<WorkOrderInfo> DgWorkOrders { get => _dgWorkOrders; set { SetProperty(ref _dgWorkOrders, value); } }
-
-        private WorkOrderInfo _SelectWorkOrderInfo;
-        public WorkOrderInfo SelectWorkOrderInfo { get => _SelectWorkOrderInfo; set { SetProperty(ref _SelectWorkOrderInfo, value); } }
-
-        private  ObservableCollection<SnInfo> _dgSns =new ObservableCollection<SnInfo>();
-        public ObservableCollection<SnInfo> DgSns { get => _dgSns; set { SetProperty(ref _dgSns, value); } }
-
-        private SnInfo _SelectSnInfo;
-        public SnInfo SelectSnInfo { get => _SelectSnInfo; set { SetProperty(ref _SelectSnInfo, value); } }
-
-        private  ObservableCollection<BindRecord> _dgBindRecords =new ObservableCollection<BindRecord>();
-        public ObservableCollection<BindRecord> DgBindRecords { get => _dgBindRecords; set { SetProperty(ref _dgBindRecords, value); } }
-
-        private BindRecord _SelectBindRecord;
-        public BindRecord SelectBindRecord { get => _SelectBindRecord; set { SetProperty(ref _SelectBindRecord, value); } }
-
-        private  ObservableCollection<ProcessRecord> _dgProcessRecords =new ObservableCollection<ProcessRecord>();
-        public ObservableCollection<ProcessRecord> DgProcessRecords { get => _dgProcessRecords; set { SetProperty(ref _dgProcessRecords, value); } }
-
-        private ProcessRecord _SelectProcessRecord;
-        public ProcessRecord SelectProcessRecord { get => _SelectProcessRecord; set { SetProperty(ref _SelectProcessRecord, value); } }
-
-        private ObservableCollection<LocalhostPartInfo> _PartInfos = new ObservableCollection<LocalhostPartInfo>();
-        public ObservableCollection<LocalhostPartInfo> PartInfos { get => _PartInfos; set { SetProperty(ref _PartInfos, value); } }
-
-        private LocalhostPartInfo _NewPart = new LocalhostPartInfo();
-        public LocalhostPartInfo NewPart { get => _NewPart; set { SetProperty(ref _NewPart, value); } }
-
-        private LocalhostPartInfo _SelectPart = new LocalhostPartInfo();
-        public LocalhostPartInfo SelectPart { get => _SelectPart; set { SetProperty(ref _SelectPart, value); } }
-
-
-        private string _SearchWorkOrder;
-        public string  SearchWorkOrder { get => _SearchWorkOrder; set { SetProperty(ref _SearchWorkOrder, value); } }
-
-
-        private string _ServiceStatus="服务状态: 已停止";
-
-        private Brush _Servicebrushes = Brushes.Green;
-
-
-        private bool _StartServiceEnable=true;
-
-        private bool _StopServiceEnable=true;
-
-        public string ServiceStatus { get => _ServiceStatus; set { SetProperty(ref _ServiceStatus, value); } }
-        public Brush Servicebrushes { get => _Servicebrushes; set { SetProperty(ref _Servicebrushes, value); } }
-        public bool StartServiceEnable { get => _StartServiceEnable; set { SetProperty(ref _StartServiceEnable, value); } }
-        public bool StopServiceEnable { get => _StopServiceEnable; set { SetProperty(ref _StopServiceEnable, value); } }
-
-        private string _StatusTxt; 
-        public string StatusTxt { get => _StatusTxt; set { SetProperty(ref _StatusTxt, value); } }
-
-        private Brush _StatusForeground=Brushes.Green;
-        public Brush StatusForeground { get => _StatusForeground; set { SetProperty(ref _StatusForeground, value); } }
-
-
-        #region 零件
-
-        private ObservableCollection<ParkingLot> _parkingLots=new ObservableCollection<ParkingLot>();
-        public ObservableCollection<ParkingLot> ParkingLots
-        {
-            get => _parkingLots;
-            set => SetProperty(ref _parkingLots, value);
-        }
-
-        private ParkingLot _currentParkingLot=new ParkingLot();
-        public ParkingLot CurrentParkingLot
-        {
-            get => _currentParkingLot;
-            set => SetProperty(ref _currentParkingLot, value);
-        }
-
-        private ParkingLot _selectedParkingLot;
-        public ParkingLot SelectedParkingLot
-        {
-            get => _selectedParkingLot;
-            set => SetProperty(ref _selectedParkingLot, value);
-        }
-
-        private bool _isEditMode;
-        public bool IsEditMode
-        {
-            get => _isEditMode;
-            set => SetProperty(ref _isEditMode, value);
-        }
-        // 命令
-        public DelegateCommand AddCommand { get; private set; }
-        public DelegateCommand UpdateCommand { get; private set; }
-        public DelegateCommand<ParkingLot> DeleteCommand { get; private set; }
-        public DelegateCommand<ParkingLot> EditCommand { get; private set; }
-        public DelegateCommand ClearFormCommand { get; private set; }
-        public DelegateCommand CancelEditCommand { get; private set; }
-
-
-
-
-        #endregion
-        #endregion
-        #region 命令
-        private DelegateCommand _LoadedCommand;
-        public DelegateCommand LoadedCommand =>
-            _LoadedCommand ?? ( _LoadedCommand = new DelegateCommand(ExecuteLoadedCommand) );
-
-        private DelegateCommand _ClosedCommand;
-        public DelegateCommand ClosedCommand =>
-            _ClosedCommand ?? ( _ClosedCommand = new DelegateCommand(ExecuteClosedCommand) );
-
-        private DelegateCommand _TestSnPrintCommand;
-        public DelegateCommand TestSnPrintCommand =>
-            _TestSnPrintCommand ?? ( _TestSnPrintCommand = new DelegateCommand(TestSnPrint) );
-
-
-
-        private DelegateCommand _TestSnComponentCommand;
-        public DelegateCommand TestSnComponentCommand =>
-            _TestSnComponentCommand ?? ( _TestSnComponentCommand = new DelegateCommand(TestSnComponent) );
-
-        private DelegateCommand _TestProcessParamsCommand;
-        public DelegateCommand TestProcessParamsCommand =>
-            _TestProcessParamsCommand ?? ( _TestProcessParamsCommand = new DelegateCommand(TestProcessParams) );
-
-
-        private DelegateCommand _ClearLogCommand;
-        public DelegateCommand ClearLogCommand =>
-            _ClearLogCommand ?? ( _ClearLogCommand = new DelegateCommand(ClearLog) );
-
-
-
-
-      
-        private DelegateCommand _RefreshWorkOrdersCommand;
-        public DelegateCommand RefreshWorkOrdersCommand =>
-            _RefreshWorkOrdersCommand ?? ( _RefreshWorkOrdersCommand = new DelegateCommand(RefreshWorkOrders) );
-
-        private DelegateCommand _AddWorkOrderCommand;
-        public DelegateCommand AddWorkOrderCommand =>
-            _AddWorkOrderCommand ?? ( _AddWorkOrderCommand = new DelegateCommand(AddWorkOrder) );
-        private DelegateCommand _DeleteWorkOrderCommand;
-        public DelegateCommand DeleteWorkOrderCommand =>
-            _DeleteWorkOrderCommand ?? ( _DeleteWorkOrderCommand = new DelegateCommand(DeleteWorkOrder) );
-
-
-        private DelegateCommand _SearchSnsCommand;
-        public DelegateCommand SearchSnsCommand =>
-            _SearchSnsCommand ?? ( _SearchSnsCommand = new DelegateCommand(SearchSns) );
-
+        private readonly IMesWorkspace _workspace;
 
-        private DelegateCommand _RefreshBindRecordsCommand;
-        public DelegateCommand RefreshBindRecordsCommand =>
-            _RefreshBindRecordsCommand ?? ( _RefreshBindRecordsCommand = new DelegateCommand(RefreshBindRecords) );
-        private DelegateCommand _ClearBindRecordsCommand;
-        public DelegateCommand ClearBindRecordsCommand =>
-            _ClearBindRecordsCommand ?? ( _ClearBindRecordsCommand = new DelegateCommand(ClearBindRecords) );
-
-        private DelegateCommand _RefreshProcessRecordsCommand;
-        public DelegateCommand RefreshProcessRecordsCommand =>
-            _RefreshProcessRecordsCommand ?? ( _RefreshProcessRecordsCommand = new DelegateCommand(RefreshProcessRecords) );
-        private DelegateCommand _ClearProcessRecordsCommand;
-        public DelegateCommand ClearProcessRecordsCommand =>
-            _ClearProcessRecordsCommand ?? ( _ClearProcessRecordsCommand = new DelegateCommand(ClearProcessRecords) );
-        private DelegateCommand _StartServiceCommand;
-        public DelegateCommand StartServiceCommand =>
-            _StartServiceCommand ?? ( _StartServiceCommand = new DelegateCommand(StartService) );
-
-        private DelegateCommand _StopServiceCommand;
-        public DelegateCommand StopServiceCommand =>
-            _StopServiceCommand ?? ( _StopServiceCommand = new DelegateCommand(StopService) );
-        private DelegateCommand _SaveSettingsCommand;
-        public DelegateCommand SaveSettingsCommand =>
-            _SaveSettingsCommand ?? ( _SaveSettingsCommand = new DelegateCommand(SaveSettings) );
-
-        private DelegateCommand _AddPartInfoCommand;
-        public DelegateCommand AddPartInfoCommand =>
-            _AddPartInfoCommand ?? (_AddPartInfoCommand = new DelegateCommand(AddPartInfo));
-
-        private DelegateCommand _RefPartInfoCommand;
-        public DelegateCommand RefPartInfoCommand =>
-            _RefPartInfoCommand ?? (_RefPartInfoCommand = new DelegateCommand(RefPartInfo));
-
-
-        private DelegateCommand _DeletePartInfoCommand;
-        public DelegateCommand DeletePartInfoCommand =>
-            _DeletePartInfoCommand ?? (_DeletePartInfoCommand = new DelegateCommand(DeletePartInfo));
-
-        
-
-        public Management Management { get => management; set { SetProperty(ref management, value); } }
-        #endregion
-        public MainViewModel(IContainerProvider container) 
+        public MainViewModel(IMesWorkspace workspace)
         {
-            _container= container;
-            Management = Management.GetManagement();
-            AddCommand = new DelegateCommand(AddParkingLot);
-            UpdateCommand = new DelegateCommand(UpdateParkingLot, CanUpdate)
-                .ObservesProperty(() => IsEditMode);
-
-            DeleteCommand = new DelegateCommand<ParkingLot>(DeleteParkingLot);
-
-
-            EditCommand = new DelegateCommand<ParkingLot>(EditParkingLot);
-            ClearFormCommand = new DelegateCommand(ClearForm);
-            CancelEditCommand = new DelegateCommand(CancelEdit);
-            //// 初始化服务
-            //management.WebApiService = new WebApiService();
-            //management.WebApiService.Init(8081);
-            //management.WebApiService.StartAsync();
-            // 初始化数据
-
-            InitializeDataGrids();
-
-            LogHelper.logChangHandler += AddLog;
-        }
-
-        private void ExecuteLoadedCommand()
-        {
-            UpdateServiceStatus();
-        }
-
-        private async void ExecuteClosedCommand()
-        {
-            if ( _isServiceRunning )
-            {
-                await Management.WebApiService.StopAsync();
-            }
-        }
-        private async void TestSnPrint()
-        {
-            try
-            {
-                if (Management.ApiClient == null )
-                {
-                    ShowMessage("请先启动服务并配置API客户端", true);
-                    return;
-                }
-
-                AddLog("=== 测试SN打印请求接口 ===");
-                
-                var request = new SnPrintRequest
-                {
-                    plant = "1211",
-                    workShop = "附件工厂",
-                    line = DgWorkOrders[0].LineCode,
-                    station = "ST01",
-                    site = "ST01-01",
-                    equipment = "PRINTER001",
-                    orderNo = null,
-                    workOrderNo = DgWorkOrders[0].WorkOrderNo,
-                    count = 2,
-                    printType = 1,
-                    messageTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
-                };
-
-                AddLog("请求参数:");
-                AddLog(JsonConvert.SerializeObject(request, Formatting.Indented));
-                var response = await Management.ApiClient.RequestSnPrintAsync(request);
-                AddLog("响应结果:");
-                LogHelper.WriteLogInfo(JsonConvert.SerializeObject(response, Formatting.Indented));
-               // AddLog(JsonConvert.SerializeObject(response, Formatting.Indented));
-                ShowMessage("SN打印请求测试完成", false);
-            }
-            catch ( Exception ex )
-            {
-                AddLog($"错误: {ex.Message}");
-                ShowMessage($"测试失败: {ex.Message}", true);
-            }
-        }
-
-        private async void TestSnComponent()
-        {
-            try
-            {
-                if (Management.ApiClient== null )
-                {
-                    ShowMessage("请先启动服务并配置API客户端", true);
-                    return;
-                }
-
-                AddLog("=== 测试SN关键件绑定接口 ===");
-                List<SnInfo> infos = new List<SnInfo>();
-
-                infos = DatabaseHelper.SelectSnInfo(DgWorkOrders[0].WorkOrderNo,true,false);
-
-                if (infos.Count != 0)
-                {
-                    var request = new SnKeyComponentRequest
-                    {
-                        businessTpye = "SCAN_TASK",
-                        plant = "1",
-                        workShop = "ZPCJ",
-                        lineCode = "ZPX-01",
-                        stationCode = "ZPX-01-01",
-                        positionCode = "ZPX-01-01-01",
-                        barcodeBoundProcInfo = "1",
-                        equipment = "SCANNER001",
-                        scanTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
-                        taskCode = "TASK-001",
-                        scanTpye = "1",
-                        sn = infos[0].Sn,
-                        gbCode = "GB123456",
-                        snStatus = "1",
-                        employee = "张三",
-                        part = new List<PartInfo>
-                    {
-                        new PartInfo
-                        {
-                            partNum = "5120101-ZE02-001",
-                            partQty = 1,
-                            materialCode = "MAT-001",
-                            oldPartNum = "",
-                            materialType = "1",
-                            positionNo = "P001"
-                        }
-                    }
-                    };
-
-                    AddLog("请求参数:");
-                    AddLog(JsonConvert.SerializeObject(request, Formatting.Indented));
-
-                    var response = await Management.ApiClient.SendSnComponentAsync(request);
-
-                    AddLog("响应结果:");
-                    AddLog(JsonConvert.SerializeObject(response, Formatting.Indented));
-                    
-                }
-                else 
-                {
-                    AddLog("无可用SN");
-                }
-                ShowMessage("SN关键件绑定测试完成", false);
-            }
-            catch ( Exception ex )
-            {
-                AddLog($"错误: {ex.Message}");
-                ShowMessage($"测试失败: {ex.Message}", true);
-            }
-        }
-        private async void TestProcessParams()
-        {
-            try
-            {
-                if ( Management.ApiClient == null )
-                {
-                    ShowMessage("请先启动服务并配置API客户端", true);
-                    return;
-                }
-
-                AddLog("=== 测试加工参数上报接口 ===");
-                List<SnInfo> infos = new List<SnInfo>();
-
-                infos = DatabaseHelper.SelectSnInfo(DgWorkOrders[0].WorkOrderNo, true, false);
-
-                if (infos.Count != 0)
-                {
-                    var request = new ProcessParameterRequest
-                    {
-                        businessTpye = "SCAN_TASK",
-                        plant = "1211",
-                        workShop = "ZPCJ",
-                        line = "ZPX-01",
-                        station = "ZPX-01-01",
-                        site = "ZPX-01-01-01",
-                        sn = infos[0].Sn,
-                        barcode = "PART-001",
-                        materialCode = "T03GCD",
-                        equipment = "EQUIP001",
-                        overallResult = "OK",
-                        tightenResultDetail = new List<TightenResult>
-                    {
-                        new TightenResult
-                        {
-                            point_num = 1,
-                            pset = 1,
-                            torque = 45.08m,
-                            angle = 44.0m,
-                            tighten_status = "OK",
-                            tighten_dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
-                        }
-                    },
-                        stepResultDetail = new List<StepResult>
-                    {
-                        new StepResult
-                        {
-                            tagCode = "TEST_PRESSURE",
-                            tagValue = "3.0",
-                            tagRage = "2.7-3.3",
-                            tagResult = "OK",
-                            tagUnit = "kg",
-                            ngCode = new List<NgCodeInfo>()
-                        }
-                    },
-                        reservedField1 = "",
-                        reservedField2 = "",
-                        reservedField3 = "",
-                        messageTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
-                    };
-
-                    AddLog("请求参数:");
-                    AddLog(JsonConvert.SerializeObject(request, Formatting.Indented));
-
-                    var response = await Management.ApiClient.SendProcessParametersAsync(request);
-
-                    AddLog("响应结果:");
-                    AddLog(JsonConvert.SerializeObject(response, Formatting.Indented));
-                    infos[0].IsUsed = true;
-                    DatabaseHelper.UpdateSnInfo(infos[0]);
-                }
-                else
-                {
-                    AddLog("无可用SN");
-                    var request = new ProcessParameterRequest
-                    {
-                        businessTpye = "SCAN_TASK",
-                        plant = "1211",
-                        workShop = "ZPCJ",
-                        line = "ZPX-01",
-                        station = "ZPX-01-01",
-                        site = "ZPX-01-01-01",
-                        sn = "LingPao",
-                        barcode = "PART-001",
-                        materialCode = "T03GCD",
-                        equipment = "EQUIP001",
-                        overallResult = "OK",
-                        tightenResultDetail = new List<TightenResult>
-                    {
-                        new TightenResult
-                        {
-                            point_num = 1,
-                            pset = 1,
-                            torque = 45.08m,
-                            angle = 44.0m,
-                            tighten_status = "OK",
-                            tighten_dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
-                        }
-                    },
-                        stepResultDetail = new List<StepResult>
-                    {
-                        new StepResult
-                        {
-                            tagCode = "TEST_PRESSURE",
-                            tagValue = "3.0",
-                            tagRage = "2.7-3.3",
-                            tagResult = "OK",
-                            tagUnit = "kg",
-                            ngCode = new List<NgCodeInfo>()
-                        }
-                    },
-                        reservedField1 = "",
-                        reservedField2 = "",
-                        reservedField3 = "",
-                        messageTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
-                    };
-                    AddLog("请求参数:");
-                    AddLog(JsonConvert.SerializeObject(request, Formatting.Indented));
-
-                    var response = await Management.ApiClient.SendProcessParametersAsync(request);
-
-                    AddLog("响应结果:");
-                    AddLog(JsonConvert.SerializeObject(response, Formatting.Indented));
-              
-                }
-                ShowMessage("加工参数上报测试完成", false);
-            }
-            catch ( Exception ex )
-            {
-                AddLog($"错误: {ex.Message}");
-                ShowMessage($"测试失败: {ex.Message}", true);
-            }
-        }
-        private void ClearLog()
-        {
-            Logs.Clear();
-        }
-        
-        #region Tab 2: 工单管理
-
-
-
-        private async void RefreshWorkOrders()
-        {
-            try
-            {
-                DgWorkOrders =new ObservableCollection<WorkOrderInfo>( DatabaseHelper.SelectWorkOrderInfo()) ;
-                ShowMessage($"已加载 {DgWorkOrders.Count} 个工单", false);
-            }
-            catch ( Exception ex )
-            {
-                ShowMessage($"刷新失败: {ex.Message}", true);
-            }
-        }
-
-        private async void AddWorkOrder()
-        {
-            try
-            {
-                // 创建新工单对话框
-                var dialog = new WorkOrderDialog();
-                if ( dialog.ShowDialog() == true )
-                {
-                    // 创建或更新工单信息
-                    var workOrder = dialog.WorkOrder;
-                    if ( DatabaseHelper.InsertWorkOrderInfo(workOrder) )
-                    {
-                        ShowMessage("工单创建成功", false);
-                        RefreshWorkOrders();
-                    }
-                    else
-                    {
-                        ShowMessage($"创建失败", true);
-                    }
-                }
-            }
-            catch ( Exception ex )
-            {
-                ShowMessage($"创建失败: {ex.Message}", true);
-            }
-        }
-       
-
-        private void DeleteWorkOrder()
-        {
-            
-            if ( SelectWorkOrderInfo == null )
-            {
-                ShowMessage("请先选择要删除的工单", true);
-                return;
-            }
-
-            var result = MessageBox.Show($"确定要删除工单 {SelectWorkOrderInfo.WorkOrderNo} 吗?",
-                "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Warning);
-
-            if ( result == MessageBoxResult.Yes )
+            _workspace = workspace;
+            LoadedCommand = new DelegateCommand(OnLoaded);
+            ClosedCommand = new DelegateCommand(OnClosed);
+            if (_workspace is INotifyPropertyChanged npc)
             {
-                try
-                {
-                    // 从内存中删除(实际应该调用API)
-                    DatabaseHelper.DeleteWorkOrderInfo(SelectWorkOrderInfo);
-                    ShowMessage("工单已删除", false);
-                    RefreshWorkOrders();
-                }
-                catch ( Exception ex )
-                {
-                    ShowMessage($"删除失败: {ex.Message}", true);
-                }
+                npc.PropertyChanged += OnWorkspacePropertyChanged;
             }
         }
-        #endregion
 
-        #region Tab 3: SN管理
+        public DelegateCommand LoadedCommand { get; }
 
+        public DelegateCommand ClosedCommand { get; }
 
-        private async void SearchSns()
+        public int SelectedTabIndex
         {
-            try
+            get => _workspace.SelectedTabIndex;
+            set
             {
-                DgSns.Clear();
-                var workOrderNo = SearchWorkOrder.Trim();
-                if ( string.IsNullOrEmpty(workOrderNo) )
+                if (_workspace.SelectedTabIndex == value)
                 {
-                    ShowMessage("请输入工单号", true);
                     return;
                 }
-                var response = DatabaseHelper.SelectSnInfo(workOrderNo);
-                if ( response.Count != 0 )
-                {
-                    DgSns =new ObservableCollection<SnInfo>(response);
-                    ShowMessage($"已加载 {response.Count} 个SN", false);
-                }
-                else
-                {
-                    ShowMessage($"加载失败: {response.Count}", true);
-                }
-            }
-            catch ( Exception ex )
-            {
-                ShowMessage($"查询失败: {ex.Message}", true);
-            }
-        }
-        #endregion
-
-        #region Tab 4: 绑定记录
-        private async void RefreshBindRecords()
-        {
-            try
-            {
-                var response = DatabaseHelper.SelectBindRecord();
-                if ( response.Count!=0 )
-                {
-                    DgBindRecords=new ObservableCollection<BindRecord>(response);
-                    ShowMessage($"已加载 {response.Count} 条绑定记录", false);
-                }
-                else
-                {
-                    ShowMessage($"加载失败: {response.Count}", true);
-                }
-            }
-            catch ( Exception ex )
-            {
-                ShowMessage($"刷新失败: {ex.Message}", true);
-            }
-        }
 
-
-        private void ClearBindRecords()
-        {
-            var result = MessageBox.Show("确定要清空所有绑定记录吗?",
-                "确认清空", MessageBoxButton.YesNo, MessageBoxImage.Warning);
-
-            if ( result == MessageBoxResult.Yes )
-            {
-                try
-                {
-                    DatabaseHelper.DeleteBindRecord();
-                    DgBindRecords.Clear();
-                    ShowMessage("绑定记录已清空", false);
-                }
-                catch ( Exception ex )
-                {
-                    ShowMessage($"清空失败: {ex.Message}", true);
-                }
-            }
-        }
-        #endregion
-
-        #region Tab 5: 加工记录
-        private async void RefreshProcessRecords()
-        {
-            try
-            {
-                var response =  DatabaseHelper.SelectProcessRecord();
-                if ( response.Count!=0 )
-                {
-                    DgProcessRecords=new ObservableCollection<ProcessRecord>(response);
-                    ShowMessage($"已加载 {response.Count} 条加工记录", false);
-                }
-                else
-                {
-                    ShowMessage($"加载失败: {response.Count}", true);
-                }
-            }
-            catch ( Exception ex )
-            {
-                ShowMessage($"刷新失败: {ex.Message}", true);
+                _workspace.SelectedTabIndex = value;
+                RaisePropertyChanged();
             }
         }
 
-
-        private void ClearProcessRecords()
+        private void OnLoaded()
         {
-            var result = MessageBox.Show("确定要清空所有加工记录吗?",
-                "确认清空", MessageBoxButton.YesNo, MessageBoxImage.Warning);
-
-            if ( result == MessageBoxResult.Yes )
-            {
-                try
-                {
-                    DatabaseHelper.DeleteProcessRecord();
-                    DgProcessRecords.Clear();
-                    ShowMessage("加工记录已清空", false);
-                }
-                catch ( Exception ex )
-                {
-                    ShowMessage($"清空失败: {ex.Message}", true);
-                }
-            }
+            _workspace.Initialize();
         }
-        #endregion
-
-        #region Tab 6: 系统设置
 
-
-        private async void StartService()
+        private async void OnClosed()
         {
+            _workspace.Shutdown();
             try
             {
-                if ( ServerPort < 1 || ServerPort > 65535 )
-                {
-                    ShowMessage("请输入有效的端口号(1-65535)", true);
-                    return;
-                }
-                if (Management.WebApiService == null) 
+                var svc = _workspace.MesManagement.WebApiService;
+                if (svc?.IsRunning == true)
                 {
-                    Management.WebApiService = _container.Resolve<WebApiService>();
+                    await svc.StopAsync();
                 }
-                if (Management.WebApiService.IsRunning )
-                    Management.WebApiService.Dispose();
-
-               
-                Management.WebApiService.Init(ServerPort);
-                await Management.WebApiService.StartAsync();
-
-                _isServiceRunning = true;
-                UpdateServiceStatus();
-                ShowMessage($"Web API服务已启动,端口: {ServerPort}", false);
             }
-            catch ( Exception ex )
+            catch
             {
-                ShowMessage($"服务启动失败: {ex.Message}", true);
+                // 忽略关闭时异常
             }
         }
-        private async void StopService()
-        {
-            try
-            {
-                await Management.WebApiService.StopAsync();
-                _isServiceRunning = false;
-                UpdateServiceStatus();
 
-                ShowMessage("Web API服务已停止", false);
-            }
-            catch ( Exception ex )
-            {
-                ShowMessage($"服务停止失败: {ex.Message}", true);
-            }
-        }
-        private void SaveSettings()
+        private void OnWorkspacePropertyChanged(object sender, PropertyChangedEventArgs e)
         {
-            try
+            if (e.PropertyName == nameof(IMesWorkspace.SelectedTabIndex))
             {
-                var apiUrl = ApiUrl.Trim();
-                var appKey = AppKey.Trim();
-                var token = Token.Trim();
-
-                if ( string.IsNullOrEmpty(apiUrl) )
-                {
-                    ShowMessage("请输入API地址", true);
-                    return;
-                }
-
-                Management.ApiClient = new MesApiClient(apiUrl, appKey, token);
-                ShowMessage("API客户端配置已保存", false);
-            }
-            catch ( Exception ex )
-            {
-                ShowMessage($"保存失败: {ex.Message}", true);
+                RaisePropertyChanged(nameof(SelectedTabIndex));
             }
         }
-        #endregion
-
-        #region 零件
-
-        private void AddParkingLot()
-        {
-            if (!ValidateParkingLot())
-                return;
-
-            // 创建新对象(避免引用问题)
-            var newParkingLot = new ParkingLot
-            {
-                FormulaType = CurrentParkingLot.FormulaType,
-                SerialNumber = CurrentParkingLot.SerialNumber,
-                PartNumber = CurrentParkingLot.PartNumber,
-                PartName = CurrentParkingLot.PartName,
-                PlanNum = CurrentParkingLot.PlanNum,
-                UseNum = CurrentParkingLot.UseNum,
-                CompletedNum = CurrentParkingLot.CompletedNum
-            };
-            DatabaseHelper.InsertParkingLot(newParkingLot);
-            ParkingLots = new ObservableCollection<ParkingLot>(DatabaseHelper.SelectParkingLot(CurrentParkingLot.FormulaType));
-            MessageBox.Show("添加成功!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
-        }
-
-        private void EditParkingLot(ParkingLot parkingLot)
-        {
-            if (parkingLot == null)
-                return;
-
-            // 复制数据到表单
-            CurrentParkingLot = new ParkingLot
-            {
-                FormulaType = parkingLot.FormulaType,
-                SerialNumber = parkingLot.SerialNumber,
-                PartNumber = parkingLot.PartNumber,
-                PartName = parkingLot.PartName,
-                PlanNum = parkingLot.PlanNum,
-                UseNum = parkingLot.UseNum,
-                CompletedNum = parkingLot.CompletedNum
-            };
-
-            IsEditMode = true;
-            SelectedParkingLot = parkingLot;
-
-        }
-
-        private void UpdateParkingLot()
-        {
-            if (!ValidateParkingLot() || SelectedParkingLot == null)
-                return;
-
-            // 更新选中项的数据
-            SelectedParkingLot.FormulaType = CurrentParkingLot.FormulaType;
-            SelectedParkingLot.SerialNumber = CurrentParkingLot.SerialNumber;
-            SelectedParkingLot.PartNumber = CurrentParkingLot.PartNumber;
-            SelectedParkingLot.PartName = CurrentParkingLot.PartName;
-            SelectedParkingLot.PlanNum = CurrentParkingLot.PlanNum;
-            SelectedParkingLot.UseNum = CurrentParkingLot.UseNum;
-            SelectedParkingLot.CompletedNum = CurrentParkingLot.CompletedNum;
-
-            CancelEdit();
-            MessageBox.Show("更新成功!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
-        }
-
-        private bool CanUpdate()
-        {
-            return IsEditMode;
-        }
-
-        private void DeleteParkingLot(ParkingLot parkingLot)
-        {
-            if (parkingLot == null)
-                return;
-
-            var result = MessageBox.Show($"确定要删除站点 '{parkingLot.FormulaType}' 的记录吗?",
-                "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Warning);
-
-            if (result == MessageBoxResult.Yes)
-            {
-                ParkingLots.Remove(parkingLot);
-
-                if (IsEditMode && SelectedParkingLot == parkingLot)
-                {
-                    CancelEdit();
-                }
-            }
-        }
-
-        private void ClearForm()
-        {
-            CurrentParkingLot = new ParkingLot();
-        }
-
-        private void CancelEdit()
-        {
-            IsEditMode = false;
-            ClearForm();
-            SelectedParkingLot = null;
-        }
-
-        private bool ValidateParkingLot()
-        {
-            //if (CurrentParkingLot.FormulaType)
-            //{
-            //    MessageBox.Show("站点名称不能为空!", "验证错误", MessageBoxButton.OK, MessageBoxImage.Warning);
-            //    return false;
-            //}
-
-            // 验证已完成数量是否为数字
-            if (!int.TryParse(CurrentParkingLot.PlanNum, out _) && !string.IsNullOrWhiteSpace(CurrentParkingLot.PlanNum))
-            {
-                MessageBox.Show("计划数量必须为数字!", "验证错误", MessageBoxButton.OK, MessageBoxImage.Warning);
-                return false;
-            }
-
-            if (!int.TryParse(CurrentParkingLot.UseNum, out _) && !string.IsNullOrWhiteSpace(CurrentParkingLot.UseNum))
-            {
-                MessageBox.Show("使用数量必须为数字!", "验证错误", MessageBoxButton.OK, MessageBoxImage.Warning);
-                return false;
-            }
-
-            return true;
-        }
-
-
-        #endregion
-
-        #region 辅助方法
-        private void UpdateServiceStatus()
-        {
-            if ( _isServiceRunning )
-            {
-                ServiceStatus = "服务状态: 运行中";
-                Servicebrushes = Brushes.Green;
-                StartServiceEnable = false;
-                StopServiceEnable = true;
-            }
-            else
-            {
-                ServiceStatus = "服务状态: 已停止";
-                Servicebrushes = Brushes.Red;
-                StartServiceEnable = true;
-                StopServiceEnable = false;
-            }
-        }
-
-        private void AddLog(string message)
-        {
-            System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
-            {
-
-                Logs.Add($"[{DateTime.Now:HH:mm:ss}] {message}\n");
-            }));
-        }
-
-        private void ShowMessage(string message, bool isError)
-        {
-            System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
-            {
-                StatusTxt = message;
-                StatusForeground = isError ? Brushes.Red : Brushes.Green;
-            }));
-        }
-
-        private void InitializeDataGrids()
-        {
-            DatabaseHelper.CreataDataTable();
-            // 初始化工单列表
-            DgWorkOrders=new ObservableCollection<WorkOrderInfo>( DatabaseHelper.SelectWorkOrderInfo());
-            // 初始化绑定记录
-            DgBindRecords = new ObservableCollection<BindRecord>(DatabaseHelper.SelectBindRecord());
-            // 初始化加工记录
-            DgProcessRecords = new ObservableCollection<ProcessRecord>(DatabaseHelper.SelectProcessRecord());
-        }
-        #endregion
-
-
-
-
-        public void AddPartInfo() 
-        {
-
-            if (DatabaseHelper.InsertPartInfo(NewPart))
-            {
-                ShowMessage("工单创建成功", false);
-                RefreshWorkOrders();
-            }
-            else
-            {
-                ShowMessage($"创建失败", true);
-            }
-
-        }
-
-        public void RefPartInfo()
-        {
-
-            PartInfos = new ObservableCollection<LocalhostPartInfo>(DatabaseHelper.SelectPartInfo(NewPart.FormulaType));
-
-        }
-        public void DeletePartInfo() 
-        {
-            DatabaseHelper.DeletePartInfo(SelectPart.FormulaType, SelectPart.MaterialCode);
-        }
-
-        public void SetMesState()
-        {
-            Management.IsLocalhostMode = true;
-        }
     }
 }

+ 35 - 0
LocalhostMES/ViewModels/Services/IMesWorkspace.cs

@@ -0,0 +1,35 @@
+using LocalhostMES.Core;
+using LocalhostMES.Models;
+using System.Collections.ObjectModel;
+using System.Windows.Media;
+
+namespace LocalhostMES.ViewModels.Services
+{
+    /// <summary>
+    /// 跨 Tab 共享的会话状态(工单列表、日志、状态提示、Management 单例)。
+    /// </summary>
+    public interface IMesWorkspace
+    {
+        Management MesManagement { get; }
+
+        ObservableCollection<WorkOrderInfo> WorkOrders { get; }
+
+        ObservableCollection<string> Logs { get; }
+
+        string StatusLine { get; }
+
+        Brush StatusForeground { get; }
+
+        int SelectedTabIndex { get; set; }
+
+        string CrossPageSn { get; set; }
+
+        void Initialize();
+
+        void Shutdown();
+
+        void ReloadWorkOrders();
+
+        void ShowStatus(string message, bool isError);
+    }
+}

+ 193 - 0
LocalhostMES/ViewModels/Services/MesWorkspace.cs

@@ -0,0 +1,193 @@
+using LocalhostMES.Core;
+using LocalhostMES.DataBase;
+using LocalhostMES.Models;
+using Prism.Mvvm;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Linq;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Media;
+
+namespace LocalhostMES.ViewModels.Services
+{
+    public sealed class MesWorkspace : BindableBase, IMesWorkspace
+    {
+        private LogHelper.LogChangHandler _logHandler;
+        private bool _initialized;
+        private string _statusLine;
+        private Brush _statusForeground = Brushes.Green;
+        private int _selectedTabIndex = 0;
+        private string _crossPageSn;
+
+        public Management MesManagement => Management.GetManagement();
+
+        public ObservableCollection<WorkOrderInfo> WorkOrders { get; } = new ObservableCollection<WorkOrderInfo>();
+
+        public ObservableCollection<string> Logs { get; } = new ObservableCollection<string>();
+
+        public string StatusLine
+        {
+            get => _statusLine;
+            private set => SetProperty(ref _statusLine, value);
+        }
+
+        public Brush StatusForeground
+        {
+            get => _statusForeground;
+            private set => SetProperty(ref _statusForeground, value);
+        }
+
+        public int SelectedTabIndex
+        {
+            get => _selectedTabIndex;
+            set => SetProperty(ref _selectedTabIndex, value);
+        }
+
+        public string CrossPageSn
+        {
+            get => _crossPageSn;
+            set => SetProperty(ref _crossPageSn, value);
+        }
+
+        public void Initialize()
+        {
+            if (_initialized)
+            {
+                return;
+            }
+
+            _initialized = true;
+            DatabaseHelper.CreataDataTable();
+            ReloadWorkOrders();
+            EnsureOrderNotifyClient();
+
+            _logHandler = msg =>
+            {
+                Application.Current?.Dispatcher.Invoke(() =>
+                {
+                    Logs.Add($"[{DateTime.Now:HH:mm:ss}] {msg}\n");
+                });
+            };
+            LogHelper.logChangHandler += _logHandler;
+        }
+
+        public void Shutdown()
+        {
+            if (MesManagement.WorkOrderNotifyTcpClient != null)
+            {
+                MesManagement.WorkOrderNotifyTcpClient.MessageReceived -= OnOrderNotifyMessage;
+                MesManagement.WorkOrderNotifyTcpClient.LogReceived -= OnOrderNotifyLog;
+                MesManagement.WorkOrderNotifyTcpClient.Dispose();
+                MesManagement.WorkOrderNotifyTcpClient = null;
+            }
+
+            if (_logHandler != null)
+            {
+                LogHelper.logChangHandler -= _logHandler;
+                _logHandler = null;
+            }
+        }
+
+        public void ReloadWorkOrders()
+        {
+            WorkOrders.Clear();
+            foreach (var w in DatabaseHelper.SelectWorkOrderInfo())
+            {
+                WorkOrders.Add(w);
+            }
+        }
+
+        public void ShowStatus(string message, bool isError)
+        {
+            Application.Current?.Dispatcher.Invoke(() =>
+            {
+                StatusLine = message;
+                StatusForeground = isError ? Brushes.Red : Brushes.Green;
+            });
+        }
+
+        private void EnsureOrderNotifyClient()
+        {
+            if (MesManagement.WorkOrderNotifyTcpClient != null)
+            {
+                return;
+            }
+
+            var client = new WorkOrderNotifyTcpClient("127.0.0.1", 9000);
+            client.MessageReceived += OnOrderNotifyMessage;
+            client.LogReceived += OnOrderNotifyLog;
+            MesManagement.WorkOrderNotifyTcpClient = client;
+
+            Task.Run(async () =>
+            {
+                try
+                {
+                    await client.ConnectAsync();
+                }
+                catch (Exception ex)
+                {
+                    ShowStatus($"TCP客户端连接失败: {ex.Message}", true);
+                }
+            });
+        }
+
+        private void OnOrderNotifyLog(string message)
+        {
+            Application.Current?.Dispatcher.Invoke(() =>
+            {
+                Logs.Add($"[{DateTime.Now:HH:mm:ss}] {message}\n");
+            });
+        }
+
+        private async void OnOrderNotifyMessage(string message)
+        {
+            if (string.IsNullOrWhiteSpace(message))
+            {
+                return;
+            }
+
+            if (!message.StartsWith("OrderRef|", StringComparison.OrdinalIgnoreCase))
+            {
+                return;
+            }
+
+            try
+            {
+                var httpHelper = MesManagement.ApiClient;
+                if (httpHelper == null)
+                {
+                    ShowStatus("未配置API客户端,无法自动刷新工单", true);
+                    return;
+                }
+
+                ApiResponse<List<WorkOrderInfo>> apiResponse = await httpHelper.GetWorkOrdersAsync();
+                if (!apiResponse.success)
+                {
+                    return;
+                }
+                if (apiResponse.data == null || apiResponse.data.Count == 0)
+                {
+                    return;
+                }
+
+                MesManagement.GetOrderInfo = apiResponse.data;
+
+                foreach (var item in apiResponse.data.Where(it => !string.IsNullOrWhiteSpace(it.WorkOrderNo)))
+                {
+                    if (!DatabaseHelper.UpdateWorkOrderInfo(item))
+                    {
+                        DatabaseHelper.InsertWorkOrderInfo(item);
+                    }
+                }
+
+                ReloadWorkOrders();
+                ShowStatus($"收到{message},工单已自动刷新", false);
+            }
+            catch
+            {
+            }
+        }
+    }
+}

+ 340 - 0
LocalhostMES/ViewModels/Tabs/ApiTestViewModel.cs

@@ -0,0 +1,340 @@
+using LocalhostMES.Core;
+using LocalhostMES.DataBase;
+using LocalhostMES.Models;
+using LocalhostMES.ViewModels.Services;
+using Newtonsoft.Json;
+using Prism.Commands;
+using Prism.Mvvm;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Linq;
+using System.Windows.Media;
+
+namespace LocalhostMES.ViewModels.Tabs
+{
+    public class ApiTestViewModel : BindableBase, IDisposable
+    {
+        private readonly IMesWorkspace _workspace;
+
+        public ApiTestViewModel(IMesWorkspace workspace)
+        {
+            _workspace = workspace;
+            _workspace.Initialize();
+            if (_workspace is INotifyPropertyChanged npc)
+            {
+                npc.PropertyChanged += OnWorkspacePropertyChanged;
+            }
+        }
+
+        public ObservableCollection<string> Logs => _workspace.Logs;
+
+        public string StatusTxt => _workspace.StatusLine;
+
+        public Brush StatusForeground => _workspace.StatusForeground;
+
+        private void OnWorkspacePropertyChanged(object sender, PropertyChangedEventArgs e)
+        {
+            if (e.PropertyName == nameof(IMesWorkspace.StatusLine))
+            {
+                RaisePropertyChanged(nameof(StatusTxt));
+            }
+
+            if (e.PropertyName == nameof(IMesWorkspace.StatusForeground))
+            {
+                RaisePropertyChanged(nameof(StatusForeground));
+            }
+        }
+
+        private DelegateCommand _testSnPrintCommand;
+        public DelegateCommand TestSnPrintCommand =>
+            _testSnPrintCommand ?? (_testSnPrintCommand = new DelegateCommand(TestSnPrint));
+
+        private DelegateCommand _testSnComponentCommand;
+        public DelegateCommand TestSnComponentCommand =>
+            _testSnComponentCommand ?? (_testSnComponentCommand = new DelegateCommand(TestSnComponent));
+
+        private DelegateCommand _testProcessParamsCommand;
+        public DelegateCommand TestProcessParamsCommand =>
+            _testProcessParamsCommand ?? (_testProcessParamsCommand = new DelegateCommand(TestProcessParams));
+
+        private DelegateCommand _clearLogCommand;
+        public DelegateCommand ClearLogCommand =>
+            _clearLogCommand ?? (_clearLogCommand = new DelegateCommand(() => Logs.Clear()));
+
+        private async void TestSnPrint()
+        {
+            try
+            {
+                if (_workspace.MesManagement.ApiClient == null)
+                {
+                    _workspace.ShowStatus("请先启动服务并配置API客户端", true);
+                    return;
+                }
+
+                var first = _workspace.WorkOrders.FirstOrDefault();
+                if (first == null)
+                {
+                    _workspace.ShowStatus("请先在「工单管理」中添加工单", true);
+                    return;
+                }
+
+                AddLog("=== 测试SN打印请求接口 ===");
+
+                var request = new SnPrintRequest
+                {
+                    plant = "1211",
+                    workShop = "附件工厂",
+                    line = first.LineCode,
+                    station = "ST01",
+                    site = "ST01-01",
+                    equipment = "PRINTER001",
+                    orderNo = null,
+                    workOrderNo = first.WorkOrderNo,
+                    count = 2,
+                    printType = 1,
+                    messageTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
+                };
+
+                AddLog("请求参数:");
+                AddLog(JsonConvert.SerializeObject(request, Formatting.Indented));
+                var response = await _workspace.MesManagement.ApiClient.RequestSnPrintAsync(request);
+                AddLog("响应结果:");
+                LogHelper.WriteLogInfo(JsonConvert.SerializeObject(response, Formatting.Indented));
+                _workspace.ShowStatus("SN打印请求测试完成", false);
+            }
+            catch (Exception ex)
+            {
+                AddLog($"错误: {ex.Message}");
+                _workspace.ShowStatus($"测试失败: {ex.Message}", true);
+            }
+        }
+
+        private async void TestSnComponent()
+        {
+            try
+            {
+                if (_workspace.MesManagement.ApiClient == null)
+                {
+                    _workspace.ShowStatus("请先启动服务并配置API客户端", true);
+                    return;
+                }
+
+                var first = _workspace.WorkOrders.FirstOrDefault();
+                if (first == null)
+                {
+                    _workspace.ShowStatus("请先在「工单管理」中添加工单", true);
+                    return;
+                }
+
+                AddLog("=== 测试SN关键件绑定接口 ===");
+                var infos = DatabaseHelper.SelectSnInfo(first.WorkOrderNo, true, false);
+
+                if (infos.Count != 0)
+                {
+                    var request = new SnKeyComponentRequest
+                    {
+                        businessTpye = "SCAN_TASK",
+                        plant = "1",
+                        workShop = "ZPCJ",
+                        lineCode = "ZPX-01",
+                        stationCode = "ZPX-01-01",
+                        positionCode = "ZPX-01-01-01",
+                        barcodeBoundProcInfo = "1",
+                        equipment = "SCANNER001",
+                        scanTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
+                        taskCode = "TASK-001",
+                        scanTpye = "1",
+                        sn = infos[0].Sn,
+                        gbCode = "GB123456",
+                        snStatus = "1",
+                        employee = "张三",
+                        part = new List<PartInfo>
+                        {
+                            new PartInfo
+                            {
+                                partNum = "5120101-ZE02-001",
+                                partQty = 1,
+                                materialCode = "MAT-001",
+                                oldPartNum = "",
+                                materialType = "1",
+                                positionNo = "P001"
+                            }
+                        }
+                    };
+
+                    AddLog("请求参数:");
+                    AddLog(JsonConvert.SerializeObject(request, Formatting.Indented));
+
+                    var response = await _workspace.MesManagement.ApiClient.SendSnComponentAsync(request);
+
+                    AddLog("响应结果:");
+                    AddLog(JsonConvert.SerializeObject(response, Formatting.Indented));
+                }
+                else
+                {
+                    AddLog("无可用SN");
+                }
+
+                _workspace.ShowStatus("SN关键件绑定测试完成", false);
+            }
+            catch (Exception ex)
+            {
+                AddLog($"错误: {ex.Message}");
+                _workspace.ShowStatus($"测试失败: {ex.Message}", true);
+            }
+        }
+
+        private async void TestProcessParams()
+        {
+            try
+            {
+                if (_workspace.MesManagement.ApiClient == null)
+                {
+                    _workspace.ShowStatus("请先启动服务并配置API客户端", true);
+                    return;
+                }
+
+                var first = _workspace.WorkOrders.FirstOrDefault();
+                if (first == null)
+                {
+                    _workspace.ShowStatus("请先在「工单管理」中添加工单", true);
+                    return;
+                }
+
+                AddLog("=== 测试加工参数上报接口 ===");
+                var infos = DatabaseHelper.SelectSnInfo(first.WorkOrderNo, true, false);
+
+                if (infos.Count != 0)
+                {
+                    var request = new ProcessParameterRequest
+                    {
+                        businessTpye = "SCAN_TASK",
+                        plant = "1211",
+                        workShop = "ZPCJ",
+                        line = "ZPX-01",
+                        station = "ZPX-01-01",
+                        site = "ZPX-01-01-01",
+                        sn = infos[0].Sn,
+                        barcode = "PART-001",
+                        materialCode = "T03GCD",
+                        equipment = "EQUIP001",
+                        overallResult = "OK",
+                        tightenResultDetail = new List<TightenResult>
+                        {
+                            new TightenResult
+                            {
+                                point_num = 1,
+                                pset = 1,
+                                torque = 45.08m,
+                                angle = 44.0m,
+                                tighten_status = "OK",
+                                tighten_dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
+                            }
+                        },
+                        stepResultDetail = new List<StepResult>
+                        {
+                            new StepResult
+                            {
+                                tagCode = "TEST_PRESSURE",
+                                tagValue = "3.0",
+                                tagRage = "2.7-3.3",
+                                tagResult = "OK",
+                                tagUnit = "kg",
+                                ngCode = new List<NgCodeInfo>()
+                            }
+                        },
+                        reservedField1 = "",
+                        reservedField2 = "",
+                        reservedField3 = "",
+                        messageTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
+                    };
+
+                    AddLog("请求参数:");
+                    AddLog(JsonConvert.SerializeObject(request, Formatting.Indented));
+
+                    var response = await _workspace.MesManagement.ApiClient.SendProcessParametersAsync(request);
+
+                    AddLog("响应结果:");
+                    AddLog(JsonConvert.SerializeObject(response, Formatting.Indented));
+                    infos[0].IsUsed = true;
+                    DatabaseHelper.UpdateSnInfo(infos[0]);
+                }
+                else
+                {
+                    AddLog("无可用SN");
+                    var request = new ProcessParameterRequest
+                    {
+                        businessTpye = "SCAN_TASK",
+                        plant = "1211",
+                        workShop = "ZPCJ",
+                        line = "ZPX-01",
+                        station = "ZPX-01-01",
+                        site = "ZPX-01-01-01",
+                        sn = "LingPao",
+                        barcode = "PART-001",
+                        materialCode = "T03GCD",
+                        equipment = "EQUIP001",
+                        overallResult = "OK",
+                        tightenResultDetail = new List<TightenResult>
+                        {
+                            new TightenResult
+                            {
+                                point_num = 1,
+                                pset = 1,
+                                torque = 45.08m,
+                                angle = 44.0m,
+                                tighten_status = "OK",
+                                tighten_dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
+                            }
+                        },
+                        stepResultDetail = new List<StepResult>
+                        {
+                            new StepResult
+                            {
+                                tagCode = "TEST_PRESSURE",
+                                tagValue = "3.0",
+                                tagRage = "2.7-3.3",
+                                tagResult = "OK",
+                                tagUnit = "kg",
+                                ngCode = new List<NgCodeInfo>()
+                            }
+                        },
+                        reservedField1 = "",
+                        reservedField2 = "",
+                        reservedField3 = "",
+                        messageTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
+                    };
+                    AddLog("请求参数:");
+                    AddLog(JsonConvert.SerializeObject(request, Formatting.Indented));
+
+                    var response = await _workspace.MesManagement.ApiClient.SendProcessParametersAsync(request);
+
+                    AddLog("响应结果:");
+                    AddLog(JsonConvert.SerializeObject(response, Formatting.Indented));
+                }
+
+                _workspace.ShowStatus("加工参数上报测试完成", false);
+            }
+            catch (Exception ex)
+            {
+                AddLog($"错误: {ex.Message}");
+                _workspace.ShowStatus($"测试失败: {ex.Message}", true);
+            }
+        }
+
+        private void AddLog(string message)
+        {
+            _workspace.Logs.Add($"[{DateTime.Now:HH:mm:ss}] {message}\n");
+        }
+
+        public void Dispose()
+        {
+            if (_workspace is INotifyPropertyChanged npc)
+            {
+                npc.PropertyChanged -= OnWorkspacePropertyChanged;
+            }
+        }
+    }
+}

+ 147 - 0
LocalhostMES/ViewModels/Tabs/BindRecordsViewModel.cs

@@ -0,0 +1,147 @@
+using LocalhostMES.DataBase;
+using LocalhostMES.Core;
+using LocalhostMES.Models;
+using LocalhostMES.ViewModels.Services;
+using Prism.Commands;
+using Prism.Mvvm;
+using System;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Windows;
+
+namespace LocalhostMES.ViewModels.Tabs
+{
+    public class BindRecordsViewModel : BindableBase
+    {
+        private readonly IMesWorkspace _workspace;
+
+        public BindRecordsViewModel(IMesWorkspace workspace)
+        {
+            _workspace = workspace;
+            _workspace.Initialize();
+            RefreshBindRecords();
+            MesDataChangedNotifier.Changed += OnDataChanged;
+            if (_workspace is INotifyPropertyChanged npc)
+            {
+                npc.PropertyChanged += OnWorkspacePropertyChanged;
+            }
+        }
+
+        private ObservableCollection<BindRecord> _dgBindRecords = new ObservableCollection<BindRecord>();
+        public ObservableCollection<BindRecord> DgBindRecords
+        {
+            get => _dgBindRecords;
+            set => SetProperty(ref _dgBindRecords, value);
+        }
+
+        private BindRecord _selectBindRecord;
+        public BindRecord SelectBindRecord
+        {
+            get => _selectBindRecord;
+            set
+            {
+                if (SetProperty(ref _selectBindRecord, value) && value != null)
+                {
+                    SearchSn = value.Sn;
+                }
+            }
+        }
+
+        private DelegateCommand _refreshBindRecordsCommand;
+        public DelegateCommand RefreshBindRecordsCommand =>
+            _refreshBindRecordsCommand ?? (_refreshBindRecordsCommand = new DelegateCommand(RefreshBindRecords));
+
+        private DelegateCommand _clearBindRecordsCommand;
+        public DelegateCommand ClearBindRecordsCommand =>
+            _clearBindRecordsCommand ?? (_clearBindRecordsCommand = new DelegateCommand(ClearBindRecords));
+
+        private string _searchSn;
+        public string SearchSn
+        {
+            get => _searchSn;
+            set => SetProperty(ref _searchSn, value);
+        }
+
+        private DelegateCommand _searchBySnCommand;
+        public DelegateCommand SearchBySnCommand =>
+            _searchBySnCommand ?? (_searchBySnCommand = new DelegateCommand(SearchBySn));
+
+        private void RefreshBindRecords()
+        {
+            try
+            {
+                var sn = (SearchSn ?? string.Empty).Trim();
+                var response = string.IsNullOrEmpty(sn)
+                    ? DatabaseHelper.SelectBindRecord()
+                    : DatabaseHelper.SelectBindRecord(sn);
+                if (response.Count != 0)
+                {
+                    DgBindRecords = new ObservableCollection<BindRecord>(response);
+                    _workspace.ShowStatus(string.IsNullOrEmpty(sn)
+                        ? $"已加载 {response.Count} 条绑定记录"
+                        : $"按SN查询到 {response.Count} 条绑定记录", false);
+                }
+                else
+                {
+                    _workspace.ShowStatus(string.IsNullOrEmpty(sn) ? "暂无绑定记录" : $"未查询到SN={sn}的绑定记录", true);
+                }
+            }
+            catch (Exception ex)
+            {
+                _workspace.ShowStatus($"刷新失败: {ex.Message}", true);
+            }
+        }
+
+        private void SearchBySn()
+        {
+            RefreshBindRecords();
+        }
+
+        private void ClearBindRecords()
+        {
+            var result = MessageBox.Show("确定要清空所有绑定记录吗?",
+                "确认清空", MessageBoxButton.YesNo, MessageBoxImage.Warning);
+
+            if (result == MessageBoxResult.Yes)
+            {
+                try
+                {
+                    DatabaseHelper.DeleteBindRecord();
+                    DgBindRecords.Clear();
+                    _workspace.ShowStatus("绑定记录已清空", false);
+                }
+                catch (Exception ex)
+                {
+                    _workspace.ShowStatus($"清空失败: {ex.Message}", true);
+                }
+            }
+        }
+
+        private void OnDataChanged(object sender, MesDataChangedEventArgs e)
+        {
+            if (!e.Has(MesDataScope.BindRecord))
+            {
+                return;
+            }
+
+            Application.Current?.Dispatcher.Invoke(RefreshBindRecords);
+        }
+
+        private void OnWorkspacePropertyChanged(object sender, PropertyChangedEventArgs e)
+        {
+            if (e.PropertyName == nameof(IMesWorkspace.CrossPageSn) ||
+                e.PropertyName == nameof(IMesWorkspace.SelectedTabIndex))
+            {
+                if (_workspace.SelectedTabIndex == 5)
+                {
+                    var sn = (_workspace.CrossPageSn ?? string.Empty).Trim();
+                    if (!string.IsNullOrEmpty(sn))
+                    {
+                        SearchSn = sn;
+                        Application.Current?.Dispatcher.Invoke(RefreshBindRecords);
+                    }
+                }
+            }
+        }
+    }
+}

+ 157 - 0
LocalhostMES/ViewModels/Tabs/KeyPartManagementViewModel.cs

@@ -0,0 +1,157 @@
+using LocalhostMES.DataBase;
+using LocalhostMES.Enums;
+using LocalhostMES.Core;
+using LocalhostMES.Models;
+using LocalhostMES.ViewModels.Services;
+using Prism.Commands;
+using Prism.Mvvm;
+using System.Collections.ObjectModel;
+using System.Windows;
+
+namespace LocalhostMES.ViewModels.Tabs
+{
+    public class KeyPartManagementViewModel : BindableBase
+    {
+        private readonly IMesWorkspace _workspace;
+
+        public KeyPartManagementViewModel(IMesWorkspace workspace)
+        {
+            _workspace = workspace;
+            _workspace.Initialize();
+            MesDataChangedNotifier.Changed += OnDataChanged;
+        }
+
+        private ObservableCollection<LocalhostPartInfo> _partInfos = new ObservableCollection<LocalhostPartInfo>();
+        public ObservableCollection<LocalhostPartInfo> PartInfos
+        {
+            get => _partInfos;
+            set => SetProperty(ref _partInfos, value);
+        }
+
+        private LocalhostPartInfo _newPart = new LocalhostPartInfo();
+        public LocalhostPartInfo NewPart
+        {
+            get => _newPart;
+            set => SetProperty(ref _newPart, value);
+        }
+
+        private LocalhostPartInfo _selectPart;
+        public LocalhostPartInfo SelectPart
+        {
+            get => _selectPart;
+            set => SetProperty(ref _selectPart, value);
+        }
+
+        private string _statusMessage = string.Empty;
+        public string StatusMessage
+        {
+            get => _statusMessage;
+            set => SetProperty(ref _statusMessage, value);
+        }
+
+        private DelegateCommand _addPartInfoCommand;
+        public DelegateCommand AddPartInfoCommand =>
+            _addPartInfoCommand ?? (_addPartInfoCommand = new DelegateCommand(AddPartInfo));
+
+        private DelegateCommand _refPartInfoCommand;
+        public DelegateCommand RefPartInfoCommand =>
+            _refPartInfoCommand ?? (_refPartInfoCommand = new DelegateCommand(RefPartInfo));
+
+        private DelegateCommand _deletePartInfoCommand;
+        public DelegateCommand DeletePartInfoCommand =>
+            _deletePartInfoCommand ?? (_deletePartInfoCommand = new DelegateCommand(DeletePartInfo));
+
+        private DelegateCommand<LocalhostPartInfo> _deletePartRowCommand;
+        public DelegateCommand<LocalhostPartInfo> DeletePartRowCommand =>
+            _deletePartRowCommand ?? (_deletePartRowCommand = new DelegateCommand<LocalhostPartInfo>(DeletePartRow, p => p != null));
+
+        private void AddPartInfo()
+        {
+            var pn = (NewPart.PartNum ?? string.Empty).Trim();
+            if (string.IsNullOrEmpty(pn))
+            {
+                _workspace.ShowStatus("请填写关键件号", true);
+                return;
+            }
+
+            if (NewPart.PartQty < 0)
+            {
+                _workspace.ShowStatus("数量不能为负数", true);
+                return;
+            }
+
+            var st = NewPart.StationType;
+            var toSave = new LocalhostPartInfo
+            {
+                StationType = st,
+                PartNum = pn,
+                PartQty = NewPart.PartQty
+            };
+
+            if (DatabaseHelper.InsertPartInfo(toSave))
+            {
+                NewPart = new LocalhostPartInfo { StationType = st };
+                _workspace.ShowStatus("关键件已保存", false);
+                RefPartInfo();
+            }
+            else
+            {
+                _workspace.ShowStatus("保存失败(可能已存在相同工站类型+关键件号)", true);
+            }
+        }
+
+        private void RefPartInfo()
+        {
+            var st = NewPart.StationType;
+            PartInfos = new ObservableCollection<LocalhostPartInfo>(DatabaseHelper.SelectPartInfo(st));
+            StatusMessage = $"工站 {st},共 {PartInfos.Count} 条";
+        }
+
+        private void DeletePartInfo()
+        {
+            if (SelectPart == null)
+            {
+                _workspace.ShowStatus("请先选择要删除的关键件行", true);
+                return;
+            }
+
+            if (DatabaseHelper.DeletePartInfo(SelectPart.StationType, SelectPart.PartNum))
+            {
+                RefPartInfo();
+                _workspace.ShowStatus("已删除", false);
+            }
+            else
+            {
+                _workspace.ShowStatus("删除失败", true);
+            }
+        }
+
+        private void DeletePartRow(LocalhostPartInfo part)
+        {
+            if (part == null)
+            {
+                return;
+            }
+
+            if (DatabaseHelper.DeletePartInfo(part.StationType, part.PartNum))
+            {
+                PartInfos.Remove(part);
+                _workspace.ShowStatus("已删除", false);
+            }
+            else
+            {
+                _workspace.ShowStatus("删除失败", true);
+            }
+        }
+
+        private void OnDataChanged(object sender, MesDataChangedEventArgs e)
+        {
+            if (!e.Has(MesDataScope.KeyPart))
+            {
+                return;
+            }
+
+            Application.Current?.Dispatcher.Invoke(RefPartInfo);
+        }
+    }
+}

+ 205 - 0
LocalhostMES/ViewModels/Tabs/PartCatalogViewModel.cs

@@ -0,0 +1,205 @@
+using LocalhostMES.DataBase;
+using LocalhostMES.Core;
+using LocalhostMES.Models;
+using Prism.Commands;
+using Prism.Mvvm;
+using System;
+using System.Collections.ObjectModel;
+using System.Windows;
+
+namespace LocalhostMES.ViewModels.Tabs
+{
+    public class PartCatalogViewModel : BindableBase
+    {
+        public PartCatalogViewModel()
+        {
+            LoadedCommand = new DelegateCommand(OnLoaded);
+            AddCommand = new DelegateCommand(AddParkingLot);
+            UpdateCommand = new DelegateCommand(UpdateParkingLot, CanUpdate).ObservesProperty(() => IsEditMode);
+            DeleteCommand = new DelegateCommand<ParkingLot>(DeleteParkingLot);
+            EditCommand = new DelegateCommand<ParkingLot>(EditParkingLot);
+            ClearFormCommand = new DelegateCommand(ClearForm);
+            CancelEditCommand = new DelegateCommand(CancelEdit);
+            MesDataChangedNotifier.Changed += OnDataChanged;
+        }
+        public DelegateCommand LoadedCommand { get; }
+        public DelegateCommand AddCommand { get; }
+        public DelegateCommand UpdateCommand { get; }
+        public DelegateCommand<ParkingLot> DeleteCommand { get; }
+        public DelegateCommand<ParkingLot> EditCommand { get; }
+        public DelegateCommand ClearFormCommand { get; }
+        public DelegateCommand CancelEditCommand { get; }
+
+        private ObservableCollection<ParkingLot> _parkingLots = new ObservableCollection<ParkingLot>();
+        public ObservableCollection<ParkingLot> ParkingLots
+        {
+            get => _parkingLots;
+            set => SetProperty(ref _parkingLots, value);
+        }
+
+        private ParkingLot _currentParkingLot = new ParkingLot();
+        public ParkingLot CurrentParkingLot
+        {
+            get => _currentParkingLot;
+            set => SetProperty(ref _currentParkingLot, value);
+        }
+
+        private ParkingLot _selectedParkingLot;
+        public ParkingLot SelectedParkingLot
+        {
+            get => _selectedParkingLot;
+            set => SetProperty(ref _selectedParkingLot, value);
+        }
+
+        private bool _isEditMode;
+        public bool IsEditMode
+        {
+            get => _isEditMode;
+            set => SetProperty(ref _isEditMode, value);
+        }
+        private void OnLoaded()
+        {
+            ReloadParkingLots();
+        }
+        private void ReloadParkingLots()
+        {
+            ParkingLots = new ObservableCollection<ParkingLot>(DatabaseHelper.SelectParkingLot());
+        }
+
+        private void AddParkingLot()
+        {
+            if (!ValidateParkingLot())
+            {
+                return;
+            }
+
+            var row = new ParkingLot
+            {
+                PartName = CurrentParkingLot.PartName?.Trim(),
+                Quantity = CurrentParkingLot.Quantity
+            };
+
+            if (DatabaseHelper.InsertParkingLot(row))
+            {
+                MessageBox.Show("添加成功!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
+                ReloadParkingLots();
+                ClearForm();
+            }
+            else
+            {
+                MessageBox.Show("添加失败(可能已存在相同记录)。", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
+            }
+        }
+
+        private void EditParkingLot(ParkingLot parkingLot)
+        {
+            if (parkingLot == null)
+            {
+                return;
+            }
+
+            CurrentParkingLot = new ParkingLot
+            {
+                Id = parkingLot.Id,
+                PartName = parkingLot.PartName,
+                Quantity = parkingLot.Quantity
+            };
+
+            IsEditMode = true;
+            SelectedParkingLot = parkingLot;
+        }
+
+        private void UpdateParkingLot()
+        {
+            if (!ValidateParkingLot() || SelectedParkingLot == null)
+            {
+                return;
+            }
+
+            SelectedParkingLot.PartName = CurrentParkingLot.PartName?.Trim();
+            SelectedParkingLot.Quantity = CurrentParkingLot.Quantity;
+
+            if (DatabaseHelper.UpdateParkingLot(SelectedParkingLot))
+            {
+                MessageBox.Show("更新成功!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
+                CancelEdit();
+                ReloadParkingLots();
+            }
+            else
+            {
+                MessageBox.Show("更新失败。", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
+            }
+        }
+
+        private bool CanUpdate() => IsEditMode;
+
+        private void DeleteParkingLot(ParkingLot parkingLot)
+        {
+            if (parkingLot == null)
+            {
+                return;
+            }
+
+            var result = MessageBox.Show($"确定要删除零件「{parkingLot.PartName}」吗?",
+                "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Warning);
+
+            if (result != MessageBoxResult.Yes)
+            {
+                return;
+            }
+
+            if (DatabaseHelper.DeleteParkingLot(parkingLot.Id))
+            {
+                if (IsEditMode && SelectedParkingLot == parkingLot)
+                {
+                    CancelEdit();
+                }
+
+                ReloadParkingLots();
+            }
+            else
+            {
+                MessageBox.Show("删除失败。", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
+            }
+        }
+
+        private void ClearForm()
+        {
+            CurrentParkingLot = new ParkingLot();
+        }
+
+        private void CancelEdit()
+        {
+            IsEditMode = false;
+            ClearForm();
+            SelectedParkingLot = null;
+        }
+
+        private bool ValidateParkingLot()
+        {
+            if (string.IsNullOrWhiteSpace(CurrentParkingLot.PartName))
+            {
+                MessageBox.Show("名称不能为空。", "验证", MessageBoxButton.OK, MessageBoxImage.Warning);
+                return false;
+            }
+
+            if (CurrentParkingLot.Quantity < 0)
+            {
+                MessageBox.Show("数量不能为负数。", "验证", MessageBoxButton.OK, MessageBoxImage.Warning);
+                return false;
+            }
+
+            return true;
+        }
+
+        private void OnDataChanged(object sender, MesDataChangedEventArgs e)
+        {
+            if (!e.Has(MesDataScope.ParkingLot))
+            {
+                return;
+            }
+
+            Application.Current?.Dispatcher.Invoke(ReloadParkingLots);
+        }
+    }
+}

+ 147 - 0
LocalhostMES/ViewModels/Tabs/ProcessRecordsViewModel.cs

@@ -0,0 +1,147 @@
+using LocalhostMES.DataBase;
+using LocalhostMES.Core;
+using LocalhostMES.Models;
+using LocalhostMES.ViewModels.Services;
+using Prism.Commands;
+using Prism.Mvvm;
+using System;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Windows;
+
+namespace LocalhostMES.ViewModels.Tabs
+{
+    public class ProcessRecordsViewModel : BindableBase
+    {
+        private readonly IMesWorkspace _workspace;
+
+        public ProcessRecordsViewModel(IMesWorkspace workspace)
+        {
+            _workspace = workspace;
+            _workspace.Initialize();
+            RefreshProcessRecords();
+            MesDataChangedNotifier.Changed += OnDataChanged;
+            if (_workspace is INotifyPropertyChanged npc)
+            {
+                npc.PropertyChanged += OnWorkspacePropertyChanged;
+            }
+        }
+
+        private ObservableCollection<ProcessRecord> _dgProcessRecords = new ObservableCollection<ProcessRecord>();
+        public ObservableCollection<ProcessRecord> DgProcessRecords
+        {
+            get => _dgProcessRecords;
+            set => SetProperty(ref _dgProcessRecords, value);
+        }
+
+        private ProcessRecord _selectProcessRecord;
+        public ProcessRecord SelectProcessRecord
+        {
+            get => _selectProcessRecord;
+            set
+            {
+                if (SetProperty(ref _selectProcessRecord, value) && value != null)
+                {
+                    SearchSn = value.Sn;
+                }
+            }
+        }
+
+        private DelegateCommand _refreshProcessRecordsCommand;
+        public DelegateCommand RefreshProcessRecordsCommand =>
+            _refreshProcessRecordsCommand ?? (_refreshProcessRecordsCommand = new DelegateCommand(RefreshProcessRecords));
+
+        private DelegateCommand _clearProcessRecordsCommand;
+        public DelegateCommand ClearProcessRecordsCommand =>
+            _clearProcessRecordsCommand ?? (_clearProcessRecordsCommand = new DelegateCommand(ClearProcessRecords));
+
+        private string _searchSn;
+        public string SearchSn
+        {
+            get => _searchSn;
+            set => SetProperty(ref _searchSn, value);
+        }
+
+        private DelegateCommand _searchBySnCommand;
+        public DelegateCommand SearchBySnCommand =>
+            _searchBySnCommand ?? (_searchBySnCommand = new DelegateCommand(SearchBySn));
+
+        private void RefreshProcessRecords()
+        {
+            try
+            {
+                var sn = (SearchSn ?? string.Empty).Trim();
+                var response = string.IsNullOrEmpty(sn)
+                    ? DatabaseHelper.SelectProcessRecord()
+                    : DatabaseHelper.SelectProcessRecord(sn);
+                if (response.Count != 0)
+                {
+                    DgProcessRecords = new ObservableCollection<ProcessRecord>(response);
+                    _workspace.ShowStatus(string.IsNullOrEmpty(sn)
+                        ? $"已加载 {response.Count} 条加工记录"
+                        : $"按SN查询到 {response.Count} 条加工记录", false);
+                }
+                else
+                {
+                    _workspace.ShowStatus(string.IsNullOrEmpty(sn) ? "暂无加工记录" : $"未查询到SN={sn}的加工记录", true);
+                }
+            }
+            catch (Exception ex)
+            {
+                _workspace.ShowStatus($"刷新失败: {ex.Message}", true);
+            }
+        }
+
+        private void SearchBySn()
+        {
+            RefreshProcessRecords();
+        }
+
+        private void ClearProcessRecords()
+        {
+            var result = MessageBox.Show("确定要清空所有加工记录吗?",
+                "确认清空", MessageBoxButton.YesNo, MessageBoxImage.Warning);
+
+            if (result == MessageBoxResult.Yes)
+            {
+                try
+                {
+                    DatabaseHelper.DeleteProcessRecord();
+                    DgProcessRecords.Clear();
+                    _workspace.ShowStatus("加工记录已清空", false);
+                }
+                catch (Exception ex)
+                {
+                    _workspace.ShowStatus($"清空失败: {ex.Message}", true);
+                }
+            }
+        }
+
+        private void OnDataChanged(object sender, MesDataChangedEventArgs e)
+        {
+            if (!e.Has(MesDataScope.ProcessRecord))
+            {
+                return;
+            }
+
+            Application.Current?.Dispatcher.Invoke(RefreshProcessRecords);
+        }
+
+        private void OnWorkspacePropertyChanged(object sender, PropertyChangedEventArgs e)
+        {
+            if (e.PropertyName == nameof(IMesWorkspace.CrossPageSn) ||
+                e.PropertyName == nameof(IMesWorkspace.SelectedTabIndex))
+            {
+                if (_workspace.SelectedTabIndex == 6)
+                {
+                    var sn = (_workspace.CrossPageSn ?? string.Empty).Trim();
+                    if (!string.IsNullOrEmpty(sn))
+                    {
+                        SearchSn = sn;
+                        Application.Current?.Dispatcher.Invoke(RefreshProcessRecords);
+                    }
+                }
+            }
+        }
+    }
+}

+ 202 - 0
LocalhostMES/ViewModels/Tabs/SnManagementViewModel.cs

@@ -0,0 +1,202 @@
+using LocalhostMES.DataBase;
+using LocalhostMES.Core;
+using LocalhostMES.Models;
+using LocalhostMES.ViewModels.Services;
+using LocalhostMES.Views;
+using Prism.Commands;
+using Prism.Mvvm;
+using System;
+using System.Collections.ObjectModel;
+using System.Linq;
+using System.Windows;
+
+namespace LocalhostMES.ViewModels.Tabs
+{
+    public class SnManagementViewModel : BindableBase
+    {
+        private readonly IMesWorkspace _workspace;
+        private bool _skipNextSnRefresh;
+
+        public SnManagementViewModel(IMesWorkspace workspace)
+        {
+            _workspace = workspace;
+            _workspace.Initialize();
+            MesDataChangedNotifier.Changed += OnDataChanged;
+        }
+
+        public ObservableCollection<WorkOrderInfo> DgWorkOrders => _workspace.WorkOrders;
+
+        private ObservableCollection<SnInfo> _dgSns = new ObservableCollection<SnInfo>();
+        public ObservableCollection<SnInfo> DgSns
+        {
+            get => _dgSns;
+            set => SetProperty(ref _dgSns, value);
+        }
+
+        private SnInfo _selectSnInfo;
+        public SnInfo SelectSnInfo
+        {
+            get => _selectSnInfo;
+            set => SetProperty(ref _selectSnInfo, value);
+        }
+
+        private string _searchWorkOrder;
+        public string SearchWorkOrder
+        {
+            get => _searchWorkOrder;
+            set => SetProperty(ref _searchWorkOrder, value);
+        }
+
+        private DelegateCommand _searchSnsCommand;
+        public DelegateCommand SearchSnsCommand =>
+            _searchSnsCommand ?? (_searchSnsCommand = new DelegateCommand(SearchSns));
+
+        private DelegateCommand _editSnCommand;
+        public DelegateCommand EditSnCommand =>
+            _editSnCommand ?? (_editSnCommand = new DelegateCommand(EditSn));
+
+        private DelegateCommand _gotoBindRecordsCommand;
+        public DelegateCommand GotoBindRecordsCommand =>
+            _gotoBindRecordsCommand ?? (_gotoBindRecordsCommand = new DelegateCommand(GotoBindRecords));
+
+        private DelegateCommand _gotoProcessRecordsCommand;
+        public DelegateCommand GotoProcessRecordsCommand =>
+            _gotoProcessRecordsCommand ?? (_gotoProcessRecordsCommand = new DelegateCommand(GotoProcessRecords));
+
+        private void SearchSns()
+        {
+            try
+            {
+                DgSns.Clear();
+                var workOrderNo = (SearchWorkOrder ?? string.Empty).Trim();
+                if (string.IsNullOrEmpty(workOrderNo))
+                {
+                    _workspace.ShowStatus("请输入工单号", true);
+                    return;
+                }
+
+                var response = DatabaseHelper.SelectSnInfo(workOrderNo);
+                if (response.Count != 0)
+                {
+                    DgSns = new ObservableCollection<SnInfo>(response);
+                    _workspace.ShowStatus($"已加载 {response.Count} 个SN", false);
+                }
+                else
+                {
+                    _workspace.ShowStatus($"加载失败: {response.Count}", true);
+                }
+            }
+            catch (Exception ex)
+            {
+                _workspace.ShowStatus($"查询失败: {ex.Message}", true);
+            }
+        }
+
+        private void OnDataChanged(object sender, MesDataChangedEventArgs e)
+        {
+            if (!e.Has(MesDataScope.Sn))
+            {
+                return;
+            }
+
+            if (_skipNextSnRefresh)
+            {
+                _skipNextSnRefresh = false;
+                return;
+            }
+
+            var workOrderNo = (SearchWorkOrder ?? string.Empty).Trim();
+            if (string.IsNullOrEmpty(workOrderNo))
+            {
+                return;
+            }
+
+            Application.Current?.Dispatcher.Invoke(SearchSns);
+        }
+
+        private void EditSn()
+        {
+            if (SelectSnInfo == null)
+            {
+                _workspace.ShowStatus("请先选择要修改的SN", true);
+                return;
+            }
+
+            try
+            {
+                var dialog = new SnDialog(SelectSnInfo) { Owner = Application.Current?.MainWindow };
+                if (dialog.ShowDialog() == true)
+                {
+                    _skipNextSnRefresh = true;
+                    if (DatabaseHelper.UpdateSnInfo(dialog.SnInfo))
+                    {
+                        var edited = dialog.SnInfo;
+                        var index = DgSns.IndexOf(SelectSnInfo);
+                        if (index >= 0)
+                        {
+                            var updatedRow = new SnInfo
+                            {
+                                Sn = edited.Sn,
+                                WorkOrderNo = edited.WorkOrderNo,
+                                PrintType = edited.PrintType,
+                                GenerateTime = edited.GenerateTime,
+                                IsUsed = edited.IsUsed
+                            };
+
+                            DgSns[index] = updatedRow;
+                            SelectSnInfo = updatedRow;
+                        }
+
+                        var selectedWorkOrderNo = (edited.WorkOrderNo ?? string.Empty).Trim();
+                        if (!string.IsNullOrEmpty(selectedWorkOrderNo) &&
+                            !_workspace.WorkOrders.Any(w => w.WorkOrderNo == selectedWorkOrderNo))
+                        {
+                            _workspace.WorkOrders.Add(new WorkOrderInfo
+                            {
+                                WorkOrderNo = selectedWorkOrderNo
+                            });
+                        }
+
+                        SearchWorkOrder = selectedWorkOrderNo;
+                        _workspace.ShowStatus("SN信息修改成功", false);
+                    }
+                    else
+                    {
+                        _skipNextSnRefresh = false;
+                        _workspace.ShowStatus("修改失败", true);
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                _workspace.ShowStatus($"修改失败: {ex.Message}", true);
+            }
+        }
+
+        private void GotoBindRecords()
+        {
+            var sn = (SelectSnInfo?.Sn ?? string.Empty).Trim();
+            if (string.IsNullOrEmpty(sn))
+            {
+                _workspace.ShowStatus("请先选择一条SN记录", true);
+                return;
+            }
+
+            _workspace.CrossPageSn = sn;
+            _workspace.SelectedTabIndex = 5;
+        }
+
+        private void GotoProcessRecords()
+        {
+            var sn = (SelectSnInfo?.Sn ?? string.Empty).Trim();
+            if (string.IsNullOrEmpty(sn))
+            {
+                _workspace.ShowStatus("请先选择一条SN记录", true);
+                return;
+            }
+
+            _workspace.CrossPageSn = sn;
+            _workspace.SelectedTabIndex = 6;
+        }
+    }
+}

+ 205 - 0
LocalhostMES/ViewModels/Tabs/SystemSettingsViewModel.cs

@@ -0,0 +1,205 @@
+using LocalhostMES.Api.Hosting;
+using LocalhostMES.Api.Services;
+using LocalhostMES.Core;
+using LocalhostMES.ViewModels.Services;
+using Prism.Commands;
+using Prism.Ioc;
+using Prism.Mvvm;
+using System;
+using System.Windows.Media;
+
+namespace LocalhostMES.ViewModels.Tabs
+{
+    public class SystemSettingsViewModel : BindableBase
+    {
+        private readonly IMesWorkspace _workspace;
+        private readonly IContainerProvider _container;
+
+        public SystemSettingsViewModel(IMesWorkspace workspace, IContainerProvider container)
+        {
+            _workspace = workspace;
+            _container = container;
+            ViewLoadedCommand = new DelegateCommand(UpdateServiceStatus);
+            _isDarkTheme = ThemeManager.CurrentTheme == ThemeMode.Dark;
+        }
+
+        public DelegateCommand ViewLoadedCommand { get; }
+
+        private bool _isDarkTheme;
+        public bool IsDarkTheme
+        {
+            get => _isDarkTheme;
+            set
+            {
+                if (SetProperty(ref _isDarkTheme, value))
+                {
+                    ThemeManager.ApplyTheme(value ? ThemeMode.Dark : ThemeMode.Light);
+                    _workspace.ShowStatus(value ? "已切换到深色主题" : "已切换到浅色主题", false);
+                }
+            }
+        }
+
+        public Management Management => _workspace.MesManagement;
+
+        private int _serverPort = 8081;
+        public int ServerPort
+        {
+            get => _serverPort;
+            set => SetProperty(ref _serverPort, value);
+        }
+
+        private string _apiUrl = "http://localhost:5000";
+        public string ApiUrl
+        {
+            get => _apiUrl;
+            set => SetProperty(ref _apiUrl, value);
+        }
+
+        private string _appKey = "API_XXM";
+        public string AppKey
+        {
+            get => _appKey;
+            set => SetProperty(ref _appKey, value);
+        }
+
+        private string _token = "7c5766afa3ca82f8a21af120f9b1cca6d";
+        public string Token
+        {
+            get => _token;
+            set => SetProperty(ref _token, value);
+        }
+
+        private string _serviceStatus = "服务状态: 已停止";
+        public string ServiceStatus
+        {
+            get => _serviceStatus;
+            set => SetProperty(ref _serviceStatus, value);
+        }
+
+        private Brush _serviceBrushes = Brushes.Green;
+        public Brush Servicebrushes
+        {
+            get => _serviceBrushes;
+            set => SetProperty(ref _serviceBrushes, value);
+        }
+
+        private bool _startServiceEnable = true;
+        public bool StartServiceEnable
+        {
+            get => _startServiceEnable;
+            set => SetProperty(ref _startServiceEnable, value);
+        }
+
+        private bool _stopServiceEnable = true;
+        public bool StopServiceEnable
+        {
+            get => _stopServiceEnable;
+            set => SetProperty(ref _stopServiceEnable, value);
+        }
+
+        private DelegateCommand _startServiceCommand;
+        public DelegateCommand StartServiceCommand =>
+            _startServiceCommand ?? (_startServiceCommand = new DelegateCommand(StartService));
+
+        private DelegateCommand _stopServiceCommand;
+        public DelegateCommand StopServiceCommand =>
+            _stopServiceCommand ?? (_stopServiceCommand = new DelegateCommand(StopService));
+
+        private DelegateCommand _saveSettingsCommand;
+        public DelegateCommand SaveSettingsCommand =>
+            _saveSettingsCommand ?? (_saveSettingsCommand = new DelegateCommand(SaveSettings));
+
+        private async void StartService()
+        {
+            try
+            {
+                _workspace.Initialize();
+                if (ServerPort < 1 || ServerPort > 65535)
+                {
+                    _workspace.ShowStatus("请输入有效的端口号(1-65535)", true);
+                    return;
+                }
+
+                if (Management.WebApiService == null)
+                {
+                    Management.WebApiService = _container.Resolve<WebApiService>();
+                }
+
+                if (Management.WebApiService.IsRunning)
+                {
+                    await Management.WebApiService.StopAsync();
+                }
+
+                Management.WebApiService.Init(ServerPort);
+                await Management.WebApiService.StartAsync();
+
+                UpdateServiceStatus();
+                _workspace.ShowStatus($"Web API服务已启动,端口: {ServerPort}", false);
+            }
+            catch (Exception ex)
+            {
+                _workspace.ShowStatus($"服务启动失败: {ex.Message}", true);
+            }
+        }
+
+        private async void StopService()
+        {
+            try
+            {
+                if (Management.WebApiService != null)
+                {
+                    await Management.WebApiService.StopAsync();
+                }
+
+                UpdateServiceStatus();
+                _workspace.ShowStatus("Web API服务已停止", false);
+            }
+            catch (Exception ex)
+            {
+                _workspace.ShowStatus($"服务停止失败: {ex.Message}", true);
+            }
+        }
+
+        private void SaveSettings()
+        {
+            try
+            {
+                var apiUrl = ApiUrl.Trim();
+                var appKey = AppKey.Trim();
+                var token = Token.Trim();
+
+                if (string.IsNullOrEmpty(apiUrl))
+                {
+                    _workspace.ShowStatus("请输入API地址", true);
+                    return;
+                }
+
+                Management.ApiClient = new MesApiClient(apiUrl, appKey, token);
+                _workspace.ShowStatus("API客户端配置已保存", false);
+            }
+            catch (Exception ex)
+            {
+                _workspace.ShowStatus($"保存失败: {ex.Message}", true);
+            }
+        }
+
+        private void UpdateServiceStatus()
+        {
+            var running = Management.WebApiService?.IsRunning == true;
+            if (running)
+            {
+                ServiceStatus = "服务状态: 运行中";
+                Servicebrushes = Brushes.Green;
+                StartServiceEnable = false;
+                StopServiceEnable = true;
+            }
+            else
+            {
+                ServiceStatus = "服务状态: 已停止";
+                Servicebrushes = Brushes.Red;
+                StartServiceEnable = true;
+                StopServiceEnable = false;
+            }
+        }
+    }
+}

+ 382 - 0
LocalhostMES/ViewModels/Tabs/TcpServerViewModel.cs

@@ -0,0 +1,382 @@
+using LocalhostMES.Core;
+using LocalhostMES.DataBase;
+using LocalhostMES.ViewModels.Services;
+using Prism.Commands;
+using Prism.Mvvm;
+using System;
+using System.Collections.Concurrent;
+using System.Collections.ObjectModel;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+
+namespace LocalhostMES.ViewModels.Tabs
+{
+    public class TcpServerViewModel : BindableBase
+    {
+        private readonly IMesWorkspace _workspace;
+        private readonly ConcurrentDictionary<string, TcpClient> _clientMap = new ConcurrentDictionary<string, TcpClient>();
+        private readonly object _workOrderSync = new object();
+        private HashSet<string> _knownWorkOrderNos = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
+        private TcpListener _listener;
+        private CancellationTokenSource _cts;
+
+        public TcpServerViewModel(IMesWorkspace workspace)
+        {
+            _workspace = workspace;
+            _workspace.Initialize();
+            RefreshKnownWorkOrders();
+            MesDataChangedNotifier.Changed += OnDataChanged;
+        }
+
+        public ObservableCollection<TcpClientItem> Clients { get; } = new ObservableCollection<TcpClientItem>();
+        public ObservableCollection<string> MessageLogs { get; } = new ObservableCollection<string>();
+
+        private int _serverPort = 9000;
+        public int ServerPort
+        {
+            get => _serverPort;
+            set => SetProperty(ref _serverPort, value);
+        }
+
+        private bool _isRunning;
+        public bool IsRunning
+        {
+            get => _isRunning;
+            set => SetProperty(ref _isRunning, value);
+        }
+
+        private TcpClientItem _selectedClient;
+        public TcpClientItem SelectedClient
+        {
+            get => _selectedClient;
+            set => SetProperty(ref _selectedClient, value);
+        }
+
+        private string _outgoingMessage;
+        public string OutgoingMessage
+        {
+            get => _outgoingMessage;
+            set => SetProperty(ref _outgoingMessage, value);
+        }
+
+        private DelegateCommand _startServerCommand;
+        public DelegateCommand StartServerCommand =>
+            _startServerCommand ?? (_startServerCommand = new DelegateCommand(async () => await StartServerAsync(), () => !IsRunning)
+                .ObservesProperty(() => IsRunning));
+
+        private DelegateCommand _stopServerCommand;
+        public DelegateCommand StopServerCommand =>
+            _stopServerCommand ?? (_stopServerCommand = new DelegateCommand(StopServer, () => IsRunning)
+                .ObservesProperty(() => IsRunning));
+
+        private DelegateCommand _sendMessageCommand;
+        public DelegateCommand SendMessageCommand =>
+            _sendMessageCommand ?? (_sendMessageCommand = new DelegateCommand(async () => await SendMessageAsync()));
+
+        private async Task StartServerAsync()
+        {
+            if (ServerPort < 1 || ServerPort > 65535)
+            {
+                _workspace.ShowStatus("TCP端口范围应为1-65535", true);
+                return;
+            }
+
+            try
+            {
+                StopServer();
+
+                _cts = new CancellationTokenSource();
+                _listener = new TcpListener(IPAddress.Any, ServerPort);
+                _listener.Start();
+                IsRunning = true;
+                AddLog($"TCP服务器已启动,监听端口 {ServerPort}");
+                _workspace.ShowStatus($"TCP服务器已启动,端口: {ServerPort}", false);
+
+                await Task.Run(() => AcceptClientsLoop(_cts.Token));
+            }
+            catch (Exception ex)
+            {
+                AddLog($"启动失败: {ex.Message}");
+                _workspace.ShowStatus($"TCP服务启动失败: {ex.Message}", true);
+                IsRunning = false;
+            }
+        }
+
+        private async Task AcceptClientsLoop(CancellationToken token)
+        {
+            while (!token.IsCancellationRequested && _listener != null)
+            {
+                TcpClient client = null;
+                try
+                {
+                    client = await _listener.AcceptTcpClientAsync();
+                }
+                catch (ObjectDisposedException)
+                {
+                    return;
+                }
+                catch (InvalidOperationException)
+                {
+                    return;
+                }
+                catch (Exception ex)
+                {
+                    AddLog($"接收客户端异常: {ex.Message}");
+                    continue;
+                }
+
+                if (client == null)
+                {
+                    continue;
+                }
+
+                var endpoint = client.Client.RemoteEndPoint?.ToString() ?? Guid.NewGuid().ToString("N");
+                var clientId = endpoint;
+                if (_clientMap.ContainsKey(clientId))
+                {
+                    clientId = $"{endpoint}#{Guid.NewGuid().ToString("N").Substring(0, 4)}";
+                }
+
+                _clientMap[clientId] = client;
+                AddClient(new TcpClientItem { ClientId = clientId, RemoteEndPoint = endpoint });
+                AddLog($"客户端已连接: {endpoint}");
+
+                _ = Task.Run(() => ReceiveLoop(clientId, client, token));
+            }
+        }
+
+        private async Task ReceiveLoop(string clientId, TcpClient client, CancellationToken token)
+        {
+            var buffer = new byte[4096];
+            try
+            {
+                var stream = client.GetStream();
+                while (!token.IsCancellationRequested && client.Connected)
+                {
+                    var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
+                    if (bytesRead <= 0)
+                    {
+                        break;
+                    }
+
+                    var text = Encoding.UTF8.GetString(buffer, 0, bytesRead);
+                    AddLog($"[收到][{clientId}] {text}");
+                }
+            }
+            catch (ObjectDisposedException)
+            {
+            }
+            catch (Exception ex)
+            {
+                AddLog($"[{clientId}] 接收异常: {ex.Message}");
+            }
+            finally
+            {
+                RemoveClient(clientId);
+                try { client.Close(); } catch { }
+                AddLog($"客户端已断开: {clientId}");
+            }
+        }
+
+        private async Task SendMessageAsync()
+        {
+            if (SelectedClient == null)
+            {
+                _workspace.ShowStatus("请先选择客户端", true);
+                return;
+            }
+
+            var message = (OutgoingMessage ?? string.Empty).Trim();
+            if (string.IsNullOrEmpty(message))
+            {
+                _workspace.ShowStatus("请输入要发送的消息", true);
+                return;
+            }
+
+            if (!_clientMap.TryGetValue(SelectedClient.ClientId, out var client) || client == null || !client.Connected)
+            {
+                _workspace.ShowStatus("客户端已离线,请重新选择", true);
+                RemoveClient(SelectedClient.ClientId);
+                return;
+            }
+
+            try
+            {
+                var bytes = Encoding.UTF8.GetBytes(message);
+                await client.GetStream().WriteAsync(bytes, 0, bytes.Length);
+                AddLog($"[发送][{SelectedClient.ClientId}] {message}");
+                OutgoingMessage = string.Empty;
+            }
+            catch (Exception ex)
+            {
+                AddLog($"发送失败: {ex.Message}");
+                _workspace.ShowStatus($"发送失败: {ex.Message}", true);
+            }
+        }
+
+        private void OnDataChanged(object sender, MesDataChangedEventArgs e)
+        {
+            if (!e.Has(MesDataScope.WorkOrder))
+            {
+                return;
+            }
+
+            if (!IsRunning || _clientMap.IsEmpty)
+            {
+                RefreshKnownWorkOrders();
+                return;
+            }
+
+            var newWorkOrders = new List<string>();
+            lock (_workOrderSync)
+            {
+                var latest = DatabaseHelper.SelectWorkOrderInfo();
+                var latestNos = new HashSet<string>(
+                    latest.Where(w => !string.IsNullOrWhiteSpace(w.WorkOrderNo)).Select(w => w.WorkOrderNo),
+                    StringComparer.OrdinalIgnoreCase);
+
+                newWorkOrders = latestNos.Except(_knownWorkOrderNos).ToList();
+                _knownWorkOrderNos = latestNos;
+            }
+
+            if (newWorkOrders.Count > 0)
+            {
+                _ = Task.Run(async () => await BroadcastOrderRefAsync(newWorkOrders));
+            }
+        }
+
+        private async Task BroadcastOrderRefAsync(List<string> workOrders)
+        {
+            foreach (var workOrderNo in workOrders)
+            {
+                var payload = $"OrderRef|{workOrderNo}";
+                var bytes = Encoding.UTF8.GetBytes(payload);
+                var connected = _clientMap.ToList();
+
+                foreach (var pair in connected)
+                {
+                    var clientId = pair.Key;
+                    var client = pair.Value;
+                    if (client == null || !client.Connected)
+                    {
+                        RemoveClient(clientId);
+                        continue;
+                    }
+
+                    try
+                    {
+                        await client.GetStream().WriteAsync(bytes, 0, bytes.Length);
+                        AddLog($"[自动推送][{clientId}] {payload}");
+                    }
+                    catch (Exception ex)
+                    {
+                        AddLog($"[自动推送失败][{clientId}] {ex.Message}");
+                    }
+                }
+            }
+        }
+
+        private void RefreshKnownWorkOrders()
+        {
+            lock (_workOrderSync)
+            {
+                var latest = DatabaseHelper.SelectWorkOrderInfo();
+                _knownWorkOrderNos = new HashSet<string>(
+                    latest.Where(w => !string.IsNullOrWhiteSpace(w.WorkOrderNo)).Select(w => w.WorkOrderNo),
+                    StringComparer.OrdinalIgnoreCase);
+            }
+        }
+
+        private void StopServer()
+        {
+            try
+            {
+                _cts?.Cancel();
+                _listener?.Stop();
+            }
+            catch
+            {
+            }
+            finally
+            {
+                _listener = null;
+                _cts = null;
+            }
+
+            foreach (var kv in _clientMap.ToList())
+            {
+                try { kv.Value.Close(); } catch { }
+            }
+            _clientMap.Clear();
+            Application.Current?.Dispatcher.Invoke(() =>
+            {
+                Clients.Clear();
+                SelectedClient = null;
+            });
+
+            if (IsRunning)
+            {
+                AddLog("TCP服务器已停止");
+            }
+            IsRunning = false;
+            RefreshKnownWorkOrders();
+        }
+
+        private void AddClient(TcpClientItem item)
+        {
+            Application.Current?.Dispatcher.Invoke(() =>
+            {
+                Clients.Add(item);
+                RaisePropertyChanged(nameof(Clients));
+            });
+        }
+
+        private void RemoveClient(string clientId)
+        {
+            _clientMap.TryRemove(clientId, out _);
+            Application.Current?.Dispatcher.Invoke(() =>
+            {
+                var target = Clients.FirstOrDefault(c => c.ClientId == clientId);
+                if (target != null)
+                {
+                    Clients.Remove(target);
+                }
+
+                if (SelectedClient != null && SelectedClient.ClientId == clientId)
+                {
+                    SelectedClient = null;
+                }
+            });
+        }
+
+        private void AddLog(string message)
+        {
+            var text = $"[{DateTime.Now:HH:mm:ss}] {message}";
+            Application.Current?.Dispatcher.Invoke(() => MessageLogs.Add(text));
+        }
+    }
+
+    public class TcpClientItem : BindableBase
+    {
+        private string _clientId;
+        private string _remoteEndPoint;
+
+        public string ClientId
+        {
+            get => _clientId;
+            set => SetProperty(ref _clientId, value);
+        }
+
+        public string RemoteEndPoint
+        {
+            get => _remoteEndPoint;
+            set => SetProperty(ref _remoteEndPoint, value);
+        }
+    }
+}

+ 154 - 0
LocalhostMES/ViewModels/Tabs/WorkOrderManagementViewModel.cs

@@ -0,0 +1,154 @@
+using LocalhostMES.DataBase;
+using LocalhostMES.Core;
+using LocalhostMES.Models;
+using LocalhostMES.ViewModels.Services;
+using LocalhostMES.Views;
+using Prism.Commands;
+using Prism.Mvvm;
+using System;
+using System.Collections.ObjectModel;
+using System.Windows;
+
+namespace LocalhostMES.ViewModels.Tabs
+{
+    public class WorkOrderManagementViewModel : BindableBase
+    {
+        private readonly IMesWorkspace _workspace;
+
+        public WorkOrderManagementViewModel(IMesWorkspace workspace)
+        {
+            _workspace = workspace;
+            _workspace.Initialize();
+            MesDataChangedNotifier.Changed += OnDataChanged;
+        }
+
+        public ObservableCollection<WorkOrderInfo> DgWorkOrders => _workspace.WorkOrders;
+
+        private WorkOrderInfo _selectWorkOrderInfo;
+        public WorkOrderInfo SelectWorkOrderInfo
+        {
+            get => _selectWorkOrderInfo;
+            set => SetProperty(ref _selectWorkOrderInfo, value);
+        }
+
+        private DelegateCommand _refreshWorkOrdersCommand;
+        public DelegateCommand RefreshWorkOrdersCommand =>
+            _refreshWorkOrdersCommand ?? (_refreshWorkOrdersCommand = new DelegateCommand(RefreshWorkOrders));
+
+        private DelegateCommand _addWorkOrderCommand;
+        public DelegateCommand AddWorkOrderCommand =>
+            _addWorkOrderCommand ?? (_addWorkOrderCommand = new DelegateCommand(AddWorkOrder));
+
+        private DelegateCommand _deleteWorkOrderCommand;
+        public DelegateCommand DeleteWorkOrderCommand =>
+            _deleteWorkOrderCommand ?? (_deleteWorkOrderCommand = new DelegateCommand(DeleteWorkOrder));
+
+        private DelegateCommand _editWorkOrderCommand;
+        public DelegateCommand EditWorkOrderCommand =>
+            _editWorkOrderCommand ?? (_editWorkOrderCommand = new DelegateCommand(EditWorkOrder));
+
+        private void RefreshWorkOrders()
+        {
+            try
+            {
+                _workspace.ReloadWorkOrders();
+                _workspace.ShowStatus($"已加载 {_workspace.WorkOrders.Count} 个工单", false);
+            }
+            catch (Exception ex)
+            {
+                _workspace.ShowStatus($"刷新失败: {ex.Message}", true);
+            }
+        }
+
+        private void OnDataChanged(object sender, MesDataChangedEventArgs e)
+        {
+            if (!e.Has(MesDataScope.WorkOrder) && !e.Has(MesDataScope.Sn))
+            {
+                return;
+            }
+
+            Application.Current?.Dispatcher.Invoke(() => _workspace.ReloadWorkOrders());
+        }
+
+        private void AddWorkOrder()
+        {
+            try
+            {
+                var dialog = new WorkOrderDialog();
+                if (dialog.ShowDialog() == true)
+                {
+                    var workOrder = dialog.WorkOrder;
+                    if (DatabaseHelper.InsertWorkOrderInfo(workOrder))
+                    {
+                        _workspace.ShowStatus("工单创建成功", false);
+                        _workspace.ReloadWorkOrders();
+                    }
+                    else
+                    {
+                        _workspace.ShowStatus("创建失败", true);
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                _workspace.ShowStatus($"创建失败: {ex.Message}", true);
+            }
+        }
+
+        private void EditWorkOrder()
+        {
+            if (SelectWorkOrderInfo == null)
+            {
+                _workspace.ShowStatus("请先选择要修改的工单", true);
+                return;
+            }
+            try
+            {
+                var dialog = new WorkOrderDialog(SelectWorkOrderInfo) { Owner = Application.Current?.MainWindow };
+                if (dialog.ShowDialog() == true)
+                {
+                    var workOrder = dialog.WorkOrder;
+                    if (DatabaseHelper.UpdateWorkOrderInfo(workOrder))
+                    {
+                        _workspace.ShowStatus("工单修改成功", false);
+                        _workspace.ReloadWorkOrders();
+                    }
+                    else
+                    {
+                        _workspace.ShowStatus("修改失败", true);
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                _workspace.ShowStatus($"修改失败: {ex.Message}", true);
+            }
+        }
+
+        private void DeleteWorkOrder()
+        {
+            if (SelectWorkOrderInfo == null)
+            {
+                _workspace.ShowStatus("请先选择要删除的工单", true);
+                return;
+            }
+
+            var result = MessageBox.Show($"确定要删除工单 {SelectWorkOrderInfo.WorkOrderNo} 吗?",
+                "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Warning);
+
+            if (result == MessageBoxResult.Yes)
+            {
+                try
+                {
+                    DatabaseHelper.DeleteWorkOrderInfo(SelectWorkOrderInfo);
+                    _workspace.ShowStatus("工单已删除", false);
+                    _workspace.ReloadWorkOrders();
+                }
+                catch (Exception ex)
+                {
+                    _workspace.ShowStatus($"删除失败: {ex.Message}", true);
+                }
+            }
+        }
+    }
+}

+ 35 - 870
LocalhostMES/Views/MainView.xaml

@@ -1,91 +1,27 @@
-<Window x:Class="LocalhostMES.Views.MainView"
+<Window x:Class="LocalhostMES.Views.MainView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
-        xmlns:local="clr-namespace:LocalhostMES.Views"
-        xmlns:enums="clr-namespace:LocalhostMES.Enums"
+        xmlns:tabs="clr-namespace:LocalhostMES.Views.Tabs"
         xmlns:prism="http://prismlibrary.com/"
         prism:ViewModelLocator.AutoWireViewModel="True"
         mc:Ignorable="d"
-        Title="MainView"
-        Height="450"
-        Width="800">
-
-
+        Background="{DynamicResource Win11WindowBrush}"
+        Title="本地 MES 网关"
+        Height="520"
+        Width="920"
+        MinHeight="420"
+        MinWidth="720"
+        UseLayoutRounding="True"
+        SnapsToDevicePixels="True">
     <Window.Resources>
-        <!-- 样式定义 -->
-        <Style TargetType="TabItem">
-            <Setter Property="FontSize"
-                    Value="14" />
-            <Setter Property="FontWeight"
-                    Value="Bold" />
-            <Setter Property="Padding"
-                    Value="10,5" />
-        </Style>
-
-        <Style TargetType="GroupBox">
-            <Setter Property="Margin"
-                    Value="5" />
-            <Setter Property="Padding"
-                    Value="10" />
-        </Style>
-
-        <Style TargetType="Button">
-            <Setter Property="Padding"
-                    Value="8,4" />
-            <Setter Property="Margin"
-                    Value="2" />
-            <Setter Property="MinWidth"
-                    Value="80" />
-        </Style>
-
-        <Style TargetType="DataGrid">
-            <Setter Property="Margin"
-                    Value="5" />
-            <Setter Property="AutoGenerateColumns"
-                    Value="False" />
-            <Setter Property="IsReadOnly"
-                    Value="True" />
-            <Setter Property="CanUserAddRows"
-                    Value="False" />
-            <Setter Property="CanUserDeleteRows"
-                    Value="False" />
-            <Setter Property="CanUserReorderColumns"
-                    Value="False" />
-            <Setter Property="CanUserResizeRows"
-                    Value="False" />
-            <Setter Property="AlternatingRowBackground"
-                    Value="#F5F5F5" />
-        </Style>
-
-
-
-        <Style TargetType="TextBox">
-            <Setter Property="Margin"
-                        Value="5" />
-            <Setter Property="VerticalContentAlignment"
-                        Value="Center" />
-        </Style>
-
-        <Style TargetType="ComboBox">
-            <Setter Property="Margin"
-                        Value="5" />
-            <Setter Property="VerticalContentAlignment"
-                        Value="Center" />
-        </Style>
-
-        <Style TargetType="Label">
-            <Setter Property="Margin"
-                        Value="5,5,2,5" />
-            <Setter Property="VerticalAlignment"
-                        Value="Center" />
-        </Style>
-
-        <DataTemplate x:Key="StationTypeTemplate">
-            <TextBlock Text="{Binding Path=FormulaType, Mode=OneWay}" />
-        </DataTemplate>
+        <ResourceDictionary>
+            <ResourceDictionary.MergedDictionaries>
+                <ResourceDictionary Source="pack://application:,,,/Views/Resources/MesTabStyles.xaml" />
+            </ResourceDictionary.MergedDictionaries>
+        </ResourceDictionary>
     </Window.Resources>
     <b:Interaction.Triggers>
         <b:EventTrigger EventName="Loaded">
@@ -95,812 +31,41 @@
             <b:InvokeCommandAction Command="{Binding ClosedCommand}" />
         </b:EventTrigger>
     </b:Interaction.Triggers>
-    <Grid>
-        <TabControl>
-            <!-- Tab 1: 接口测试 -->
+    <Grid Margin="8">
+        <Border Background="{DynamicResource Win11CardBrush}"
+                BorderBrush="{DynamicResource Win11BorderBrush}"
+                BorderThickness="1"
+                CornerRadius="12"
+                Padding="6">
+            <TabControl Margin="2" SelectedIndex="{Binding SelectedTabIndex, Mode=TwoWay}">
             <TabItem Header="接口测试">
-                <Grid>
-                    <Grid.ColumnDefinitions>
-                        <ColumnDefinition Width="400" />
-                        <ColumnDefinition Width="*" />
-                    </Grid.ColumnDefinitions>
-
-                    <!-- 左侧:接口列表 -->
-                    <GroupBox Grid.Column="0"
-                              Header="接口列表"
-                              Margin="10">
-                        <StackPanel>
-                            <!--<Button x:Name="btnTestWorkOrder"
-                                    Content="测试工单下发"
-                                    Height="40"
-                                    Margin="0,5"
-                                    Click="BtnTestWorkOrder_Click" />-->
-                            <Button x:Name="btnTestSnPrint"
-                                    Content="测试SN打印请求"
-                                    Height="40"
-                                    Margin="0,5"
-                                    Command="{Binding TestSnPrintCommand}" />
-                            <Button x:Name="btnTestSnComponent"
-                                    Content="测试SN关键件绑定"
-                                    Height="40"
-                                    Margin="0,5"
-                                    Command="{Binding TestSnComponentCommand}" />
-                            <Button x:Name="btnTestProcessParams"
-                                    Content="测试加工参数上报"
-                                    Height="40"
-                                    Margin="0,5"
-                                    Command="{Binding TestProcessParamsCommand}" />
-
-                            <Separator Margin="0,10" />
-
-                            <Button x:Name="btnClearLog"
-                                    Content="清空日志"
-                                    Height="30"
-                                    Margin="0,5"
-                                    Command="{Binding ClearLogCommand}" />
-                        </StackPanel>
-                    </GroupBox>
-
-                    <!-- 右侧:日志显示 -->
-                    <GroupBox Grid.Column="1"
-                              Header="请求/响应日志"
-                              Margin="10">
-                        <Grid>
-                            <Grid.RowDefinitions>
-                                <RowDefinition Height="*" />
-                                <RowDefinition Height="Auto" />
-                            </Grid.RowDefinitions>
-
-
-
-                            <ListBox Name="logbox"
-                                     Grid.Row="0"
-                                     ItemsSource="{Binding Logs}"
-                                     BorderBrush="Transparent">
-
-                            </ListBox>
-
-                            <StackPanel Grid.Row="1"
-                                        Orientation="Horizontal"
-                                        HorizontalAlignment="Right">
-                                <TextBlock x:Name="txtStatus"
-                                           Text="{Binding StatusTxt}"
-                                           Margin="5"
-                                           Foreground="{Binding StatusForeground}"
-                                           VerticalAlignment="Center" />
-                            </StackPanel>
-                        </Grid>
-                    </GroupBox>
-                </Grid>
+                <tabs:ApiTestView />
             </TabItem>
-
-            <!-- Tab 2: 工单管理 -->
             <TabItem Header="工单管理">
-                <Grid>
-                    <Grid.RowDefinitions>
-                        <RowDefinition Height="Auto" />
-                        <RowDefinition Height="*" />
-                    </Grid.RowDefinitions>
-
-                    <!-- 工具栏 -->
-                    <StackPanel Grid.Row="0"
-                                Orientation="Horizontal"
-                                Margin="10">
-                        <Button x:Name="btnRefreshWorkOrders"
-                                Content="刷新"
-                                Width="80"
-                                Command="{Binding RefreshWorkOrdersCommand}" />
-                        <Button x:Name="btnAddWorkOrder"
-                                Content="添加工单"
-                                Width="80"
-                                Margin="10,0,0,0"
-                                Command="{Binding AddWorkOrderCommand}" />
-                        <Button x:Name="btnDeleteWorkOrder"
-                                Content="删除工单"
-                                Width="80"
-                                Margin="10,0,0,0"
-                                Command="{Binding DeleteWorkOrderCommand}" />
-                    </StackPanel>
-
-                    <!-- 工单列表 -->
-                    <DataGrid x:Name="dgWorkOrders"
-                              Grid.Row="1"
-                              SelectedItem="{Binding SelectWorkOrderInfo}"
-                              ItemsSource="{Binding DgWorkOrders}"
-                              Margin="10,0,10,10">
-                        <DataGrid.Columns>
-                            <DataGridTextColumn Header="工单号"
-                                                Binding="{Binding WorkOrderNo}"
-                                                Width="120" />
-                            <DataGridTextColumn Header="物料编码"
-                                                Binding="{Binding MaterialCode}"
-                                                Width="100" />
-                            <DataGridTextColumn Header="物料名称"
-                                                Binding="{Binding MaterialName}"
-                                                Width="150" />
-                            <DataGridTextColumn Header="计划数量"
-                                                Binding="{Binding PlannedQuantity}"
-                                                Width="80" />
-                            <DataGridTextColumn Header="完成数量"
-                                                Binding="{Binding CompletedQuantity}"
-                                                Width="80" />
-                            <DataGridTextColumn Header="状态"
-                                                Binding="{Binding Status}"
-                                                Width="80">
-                                <DataGridTextColumn.ElementStyle>
-                                    <Style TargetType="TextBlock">
-                                        <Setter Property="HorizontalAlignment"
-                                                Value="Center" />
-                                    </Style>
-                                </DataGridTextColumn.ElementStyle>
-                            </DataGridTextColumn>
-                            <DataGridTextColumn Header="线体编码"
-                                                Binding="{Binding LineCode}"
-                                                Width="80" />
-                            <DataGridTextColumn Header="创建时间"
-                                                Binding="{Binding CreateTime, StringFormat=yyyy-MM-dd HH:mm}"
-                                                Width="140" />
-                        </DataGrid.Columns>
-                    </DataGrid>
-                </Grid>
+                <tabs:WorkOrderManagementView />
             </TabItem>
-
-            <!-- Tab 3: SN管理 -->
             <TabItem Header="SN管理">
-                <Grid>
-                    <Grid.ColumnDefinitions>
-                        <ColumnDefinition Width="117*" />
-                        <ColumnDefinition Width="165*" />
-                        <ColumnDefinition Width="512*" />
-                    </Grid.ColumnDefinitions>
-                    <Grid.RowDefinitions>
-                        <RowDefinition Height="Auto" />
-                        <RowDefinition Height="*" />
-                    </Grid.RowDefinitions>
-
-                    <!-- 查询条件 -->
-                    <GroupBox Grid.Row="0"
-                              Header="查询条件"
-                              Margin="10,10,10,10"
-                              Grid.ColumnSpan="3">
-                        <StackPanel Orientation="Horizontal">
-                            <TextBlock Text="工单号:"
-                                       VerticalAlignment="Center"
-                                       Margin="5,0" />
-                            <ComboBox  ItemsSource="{Binding DgWorkOrders}" 
-                                       DisplayMemberPath="WorkOrderNo"
-                                       SelectedValuePath="WorkOrderNo"
-                                       SelectedValue="{Binding SearchWorkOrder}">
-                                
-                            </ComboBox>
-                            <TextBox x:Name="txtSearchWorkOrder"
-                                     Width="150"
-                                     Margin="5,0"
-                                     Text="{Binding SearchWorkOrder}" />
-                            <Button x:Name="btnSearchSns"
-                                    Content="查询"
-                                    Width="80"
-                                    Margin="10,0,0,0"
-                                    Command="{Binding SearchSnsCommand}" />
-                        </StackPanel>
-                    </GroupBox>
-
-                    <!-- SN列表 -->
-                    <DataGrid x:Name="dgSns"
-                              Grid.Row="1"
-                              ItemsSource="{Binding DgSns}"
-                              SelectedItem="{Binding SelectSnInfo}"
-                              Margin="10,0,10,10"
-                              Grid.ColumnSpan="3">
-                        <DataGrid.Columns>
-                            <DataGridTextColumn Header="SN条码"
-                                                Binding="{Binding Sn}"
-                                                Width="200" />
-                            <DataGridTextColumn Header="工单号"
-                                                Binding="{Binding WorkOrderNo}"
-                                                Width="120" />
-                            <DataGridTextColumn Header="类型"
-                                                Binding="{Binding PrintType}"
-                                                Width="80" />
-                            <DataGridTextColumn Header="生成时间"
-                                                Binding="{Binding GenerateTime, StringFormat=yyyy-MM-dd HH:mm:ss}"
-                                                Width="140" />
-                            <DataGridCheckBoxColumn Header="已使用"
-                                                    Binding="{Binding IsUsed}"
-                                                    Width="70" />
-                        </DataGrid.Columns>
-                    </DataGrid>
-                </Grid>
+                <tabs:SnManagementView />
             </TabItem>
-
             <TabItem Header="关键件管理">
-                <Grid Margin="10">
-                    <Grid.RowDefinitions>
-                        <RowDefinition Height="Auto" />
-                        <RowDefinition Height="Auto" />
-                        <RowDefinition Height="*" />
-                        <RowDefinition Height="Auto" />
-                    </Grid.RowDefinitions>
-
-                    <!-- 标题 -->
-                    <TextBlock Grid.Row="0"
-                               Text="关键件信息"
-                               FontSize="20"
-                               FontWeight="Bold"
-                               HorizontalAlignment="Center"
-                               Margin="0,0,0,15" />
-
-                    <!-- 添加区域 -->
-                    <Border Grid.Row="1"
-                            BorderBrush="#CCCCCC"
-                            BorderThickness="1"
-                            CornerRadius="5"
-                            Padding="10"
-                            Margin="0,0,0,40"
-                            Background="#F5F5F5">
-                        <Grid>
-                            <Grid.ColumnDefinitions>
-                                <ColumnDefinition Width="Auto" />
-                                <ColumnDefinition Width="*" />
-                                <ColumnDefinition Width="Auto" />
-                                <ColumnDefinition Width="*" />
-                                <ColumnDefinition Width="Auto" />
-                                <ColumnDefinition Width="80" />
-                            </Grid.ColumnDefinitions>
-                            <Grid.RowDefinitions>
-                                <RowDefinition Height="Auto" />
-                                <RowDefinition Height="Auto" />
-                            </Grid.RowDefinitions>
-
-                            <!-- 第一行 -->
-                            <Label Grid.Row="0"
-                                   Grid.Column="0">工位类型:</Label>
-                            <ComboBox Grid.Row="0"
-                                      Grid.Column="1"
-                                      ItemsSource="{Binding Source={ enums:EnumBindingSource {x:Type enums:StationType}}}"
-                                      SelectedItem="{Binding NewPart.FormulaType}" />
-
-                            <Label Grid.Row="0"
-                                   Grid.Column="2">关键件条码:</Label>
-                            <TextBox Grid.Row="0"
-                                     Grid.Column="3"
-                                     Text="{Binding NewPart.PartNum, UpdateSourceTrigger=PropertyChanged}" />
-
-                            <Label Grid.Row="0"
-                                   Grid.Column="4">数量:</Label>
-                            <TextBox Grid.Row="0"
-                                     Grid.Column="5"
-                                     Text="{Binding NewPart.PartQty, UpdateSourceTrigger=PropertyChanged}" />
-
-                            <!-- 第二行 -->
-                            <Label Grid.Row="1"
-                                   Grid.Column="0">物料名称:</Label>
-                            <TextBox Grid.Row="1"
-                                     Grid.Column="1"
-                                     Text="{Binding NewPart.MaterialCode, UpdateSourceTrigger=PropertyChanged}" />
-
-                            <Label Grid.Row="1"
-                                   Grid.Column="2">原条码:</Label>
-                            <TextBox Grid.Row="1"
-                                     Grid.Column="3"
-                                     Text="{Binding NewPart.OldPartNum, UpdateSourceTrigger=PropertyChanged}" />
-
-                            <Label Grid.Row="1"
-                                   Grid.Column="4">位置序号:</Label>
-                            <TextBox Grid.Row="1"
-                                     Grid.Column="5"
-                                     Text="{Binding NewPart.PositionNo, UpdateSourceTrigger=PropertyChanged}" />
-                        </Grid>
-                    </Border>
-
-                    <!-- 按钮区域 -->
-                    <StackPanel Grid.Row="1"
-                                Orientation="Horizontal"
-                                HorizontalAlignment="Right"
-                                Margin="0,0,0,0"
-                                VerticalAlignment="Bottom">
-                        <Button Content="添加"
-                                Command="{Binding AddPartInfoCommand}"
-                                Background="#4CAF50"
-                                Foreground="White" />
-                        <Button Content="刷新"
-                                Command="{Binding RefPartInfoCommand}"
-                                Background="#FF9800"
-                                Foreground="White" />
-                        <Button Content="删除"
-                                Command="{Binding DeletePartInfoCommand}"
-                                Background="#F44336"
-                                Foreground="White" />
-                    </StackPanel>
-
-                    <!-- 数据列表 -->
-                    <DataGrid Grid.Row="2"
-                              ItemsSource="{Binding PartInfos}"
-                              SelectedItem="{Binding SelectPart}"
-                              SelectionMode="Single"
-                              AutoGenerateColumns="False"
-                              CanUserAddRows="False"
-                              IsReadOnly="True"
-                              GridLinesVisibility="None"
-                              RowDetailsVisibilityMode="Collapsed"
-                              HeadersVisibility="Column"
-                              Margin="0,10,0,10">
-
-                        <DataGrid.Resources>
-                            <Style TargetType="DataGridRow">
-                                <Style.Triggers>
-                                    <Trigger Property="IsSelected"
-                                             Value="True">
-                                        <Setter Property="Background"
-                                                Value="#E3F2FD" />
-                                        <Setter Property="BorderBrush"
-                                                Value="#2196F3" />
-                                    </Trigger>
-                                </Style.Triggers>
-                            </Style>
-
-                            <Style TargetType="DataGridColumnHeader">
-                                <Setter Property="Background"
-                                        Value="#2196F3" />
-                                <Setter Property="Foreground"
-                                        Value="White" />
-                                <Setter Property="FontWeight"
-                                        Value="Bold" />
-                                <Setter Property="Padding"
-                                        Value="10,5" />
-                                <Setter Property="HorizontalContentAlignment"
-                                        Value="Center" />
-                            </Style>
-                        </DataGrid.Resources>
-
-                        <DataGrid.Columns>
-                            <DataGridCheckBoxColumn Binding="{Binding IsSelected}"
-                                                    Header="选择"
-                                                    Width="50" />
-                            <DataGridTextColumn Header="工位类型"
-                                                Binding="{Binding FormulaType}"
-                                                Width="80" />
-                            <DataGridTextColumn Header="关键件条码"
-                                                Binding="{Binding PartNum}"
-                                                Width="120" />
-                            <DataGridTextColumn Header="数量"
-                                                Binding="{Binding PartQty}"
-                                                Width="60">
-                                <DataGridTextColumn.ElementStyle>
-                                    <Style TargetType="TextBlock">
-                                        <Setter Property="HorizontalAlignment"
-                                                Value="Right" />
-                                        <Setter Property="Margin"
-                                                Value="0,0,10,0" />
-                                    </Style>
-                                </DataGridTextColumn.ElementStyle>
-                            </DataGridTextColumn>
-                            <DataGridTextColumn Header="物料代码"
-                                                Binding="{Binding MaterialCode}"
-                                                Width="100" />
-                            <DataGridTextColumn Header="关键件类型"
-                                                Binding="{Binding MaterialType}"
-                                                Width="80" />
-                            <DataGridTextColumn Header="原关键件条码"
-                                                Binding="{Binding OldPartNum}"
-                                                Width="120" />
-                            <DataGridTextColumn Header="位置序号"
-                                                Binding="{Binding PositionNo}"
-                                                Width="80" />
-                            <DataGridTemplateColumn Header="操作"
-                                                    Width="100">
-                                <DataGridTemplateColumn.CellTemplate>
-                                    <DataTemplate>
-                                        <Button Content="删除"
-                                                Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
-                                                CommandParameter="{Binding}"
-                                                Background="#F44336"
-                                                Foreground="White"
-                                                Padding="5,2"
-                                                Margin="2,0" />
-                                    </DataTemplate>
-                                </DataGridTemplateColumn.CellTemplate>
-                            </DataGridTemplateColumn>
-                        </DataGrid.Columns>
-                    </DataGrid>
-
-                    <!-- 状态栏 -->
-                    <StatusBar Grid.Row="3"
-                               Background="#F5F5F5">
-                        <StatusBarItem>
-                            <TextBlock>
-                    <Run Text="记录总数:" />
-                    <Run Text="{Binding PartInfos.Count, Mode=OneWay}" />
-                            </TextBlock>
-                        </StatusBarItem>
-                        <StatusBarItem HorizontalAlignment="Right">
-                            <TextBlock Text="{Binding StatusMessage}" />
-                        </StatusBarItem>
-                    </StatusBar>
-                </Grid>
+                <tabs:KeyPartManagementView />
             </TabItem>
             <TabItem Header="零件管理">
-                <Grid Margin="10">
-                    <Grid.RowDefinitions>
-                        <RowDefinition Height="Auto"/>
-                        <RowDefinition Height="Auto"/>
-                        <RowDefinition Height="*"/>
-                    </Grid.RowDefinitions>
-
-                    <!-- 标题 -->
-                    <TextBlock Grid.Row="0" Text="零件管理" FontSize="20" FontWeight="Bold" 
-                   HorizontalAlignment="Center" Margin="0,0,0,20"/>
-
-                    <!-- 数据输入表单 -->
-                    <GroupBox Grid.Row="1" Header="添加/编辑零件信息" Margin="0,0,0,10">
-                        <Grid Margin="10">
-                            <Grid.ColumnDefinitions>
-                                <ColumnDefinition Width="Auto"/>
-                                <ColumnDefinition Width="*"/>
-                                <ColumnDefinition Width="Auto"/>
-                                <ColumnDefinition Width="*"/>
-                            </Grid.ColumnDefinitions>
-                            <Grid.RowDefinitions>
-                                <RowDefinition Height="Auto"/>
-                                <RowDefinition Height="Auto"/>
-                                <RowDefinition Height="Auto"/>
-                                <RowDefinition Height="Auto"/>
-                                <RowDefinition Height="Auto"/>
-                                <RowDefinition Height="Auto"/>
-                                <RowDefinition Height="Auto"/>
-                                <RowDefinition Height="Auto"/>
-                            </Grid.RowDefinitions>
-
-                            <!-- 第一列 -->
-
-
-                            <TextBlock Grid.Row="0" Grid.Column="0" Text="站点名称:" VerticalAlignment="Center" Margin="5"/>
-                            <ComboBox Grid.Row="0"
-                                      Grid.Column="1"
-                                      ItemsSource="{Binding Source={ enums:EnumBindingSource {x:Type enums:StationType}}}"
-                                      SelectedItem="{Binding CurrentParkingLot.FormulaType}"  Margin="5" Width="200"/>
-
-
-                            <TextBlock Grid.Row="1" Grid.Column="0" Text="序号:" VerticalAlignment="Center" Margin="5"/>
-                            <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding CurrentParkingLot.SerialNumber, UpdateSourceTrigger=PropertyChanged}" 
-                         Margin="5" Width="200"/>
-
-                            <TextBlock Grid.Row="2" Grid.Column="0" Text="零件号:" VerticalAlignment="Center" Margin="5"/>
-                            <TextBox Grid.Row="2" Grid.Column="1" Text="{Binding CurrentParkingLot.PartNumber, UpdateSourceTrigger=PropertyChanged}" 
-                         Margin="5" Width="200"/>
-
-                            <TextBlock Grid.Row="3" Grid.Column="0" Text="零件名称:" VerticalAlignment="Center" Margin="5"/>
-                            <TextBox Grid.Row="3" Grid.Column="1" Text="{Binding CurrentParkingLot.PartName, UpdateSourceTrigger=PropertyChanged}" 
-                         Margin="5" Width="200"/>
-
-                            <!-- 第二列 -->
-                            <TextBlock Grid.Row="0" Grid.Column="2" Text="计划数量:" VerticalAlignment="Center" Margin="5,5,5,5"/>
-                            <TextBox Grid.Row="0" Grid.Column="3" Text="{Binding CurrentParkingLot.PlanNum, UpdateSourceTrigger=PropertyChanged}" 
-                         Margin="5" Width="200"/>
-
-                            <TextBlock Grid.Row="1" Grid.Column="2" Text="使用数量:" VerticalAlignment="Center" Margin="5"/>
-                            <TextBox Grid.Row="1" Grid.Column="3" Text="{Binding CurrentParkingLot.UseNum, UpdateSourceTrigger=PropertyChanged}" 
-                         Margin="5" Width="200"/>
-
-                            <TextBlock Grid.Row="2" Grid.Column="2" Text="已完成数量:" VerticalAlignment="Center" Margin="5"/>
-                            <TextBox Grid.Row="2" Grid.Column="3" Text="{Binding CurrentParkingLot.CompletedNum, UpdateSourceTrigger=PropertyChanged}" 
-                         Margin="5" Width="200"/>
-
-                            <!-- 按钮 -->
-                            <StackPanel Grid.Row="7" Grid.Column="0" Grid.ColumnSpan="4" 
-                            Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,20,0,0">
-                                <Button x:Name="btnAdd" Content="添加" Width="80" Height="30" Margin="10" 
-                            Command="{Binding AddCommand}"/>
-                                <Button x:Name="btnUpdate" Content="更新" Width="80" Height="30" Margin="10" 
-                            Command="{Binding UpdateCommand}" 
-                            IsEnabled="{Binding IsEditMode}"/>
-                                <Button x:Name="btnCancel" Content="取消编辑" Width="80" Height="30" Margin="10" 
-                            Command="{Binding CancelEditCommand}"
-                            IsEnabled="{Binding IsEditMode}"/>
-                                <Button x:Name="btnClear" Content="清空表单" Width="80" Height="30" Margin="10" 
-                            Command="{Binding ClearFormCommand}"/>
-                            </StackPanel>
-                        </Grid>
-                    </GroupBox>
-
-                    <!-- 数据列表 -->
-                    <GroupBox Grid.Row="2" Header="零件列表">
-                        <Grid>
-                            <Grid.RowDefinitions>
-                                <RowDefinition Height="*"/>
-                                <RowDefinition Height="Auto"/>
-                            </Grid.RowDefinitions>
-
-                            <!-- DataGrid -->
-                            <DataGrid x:Name="dataGrid" Grid.Row="0" AutoGenerateColumns="False" 
-                          ItemsSource="{Binding ParkingLots}" 
-                          SelectedItem="{Binding SelectedParkingLot, Mode=TwoWay}"
-                          CanUserAddRows="False" CanUserDeleteRows="False"
-                          SelectionMode="Single" SelectionUnit="FullRow"
-                          Margin="5" IsReadOnly="True">
-                                <DataGrid.Columns>
-                                    <DataGridTextColumn Header="站点名称" Binding="{Binding FormulaType}" Width="120"/>
-                                    <DataGridTextColumn Header="序号" Binding="{Binding SerialNumber}" Width="80"/>
-                                    <DataGridTextColumn Header="零件号" Binding="{Binding PartNumber}" Width="120"/>
-                                    <DataGridTextColumn Header="零件名称" Binding="{Binding PartName}" Width="150"/>
-                                    <DataGridTextColumn Header="计划数量" Binding="{Binding PlanNum}" Width="80"/>
-                                    <DataGridTextColumn Header="使用数量" Binding="{Binding UseNum}" Width="80"/>
-                                    <DataGridTextColumn Header="已完成数量" Binding="{Binding CompletedNum}" Width="100"/>
-                                    <DataGridTemplateColumn Header="操作" Width="200">
-                                        <DataGridTemplateColumn.CellTemplate>
-                                            <DataTemplate>
-                                                <StackPanel Orientation="Horizontal">
-                                                    <Button Content="编辑" Width="50" Margin="2" 
-                                                Command="{Binding DataContext.EditCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
-                                                CommandParameter="{Binding}"/>
-                                                    <Button Content="删除" Width="50" Margin="2" 
-                                                Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
-                                                CommandParameter="{Binding}"/>
-                                                </StackPanel>
-                                            </DataTemplate>
-                                        </DataGridTemplateColumn.CellTemplate>
-                                    </DataGridTemplateColumn>
-                                </DataGrid.Columns>
-                            </DataGrid>
-
-                            <!-- 统计信息 -->
-                            <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Margin="5">
-                                <TextBlock Text="总计:" FontWeight="Bold" Margin="5"/>
-                                <TextBlock Text="{Binding ParkingLots.Count}" Foreground="Blue" Margin="5"/>
-                                <TextBlock Text="条记录" Margin="5"/>
-                            </StackPanel>
-                        </Grid>
-                    </GroupBox>
-                </Grid>
+                <tabs:PartCatalogView />
             </TabItem>
-            <!-- Tab 4: 绑定记录 -->
             <TabItem Header="绑定记录">
-                <Grid>
-                    <Grid.RowDefinitions>
-                        <RowDefinition Height="Auto" />
-                        <RowDefinition Height="*" />
-                    </Grid.RowDefinitions>
-
-                    <!-- 工具栏 -->
-                    <StackPanel Grid.Row="0"
-                                Orientation="Horizontal"
-                                Margin="10">
-                        <Button x:Name="btnRefreshBindRecords"
-                                Content="刷新"
-                                Width="80"
-                                Command="{Binding RefreshBindRecordsCommand}" />
-                        <Button x:Name="btnClearBindRecords"
-                                Content="清空"
-                                Width="80"
-                                Margin="10,0,0,0"
-                                Command="{Binding ClearBindRecordsCommand}" />
-                    </StackPanel>
-
-                    <!-- 绑定记录列表 -->
-                    <DataGrid x:Name="dgBindRecords"
-                              Grid.Row="1"
-                              ItemsSource="{Binding DgBindRecords}"
-                              SelectedItem="{Binding SelectBindRecord}"
-                              Margin="10,0,10,10">
-                        <DataGrid.Columns>
-                            <DataGridTextColumn Header="SN"
-                                                Binding="{Binding Sn}"
-                                                Width="150" />
-                            <DataGridTextColumn Header="关键件条码"
-                                                Binding="{Binding PartNum}"
-                                                Width="150" />
-                            <DataGridTextColumn Header="工位"
-                                                Binding="{Binding StationCode}"
-                                                Width="100" />
-                            <DataGridTextColumn Header="绑定类型"
-                                                Binding="{Binding ScanType}"
-                                                Width="80">
-                                <DataGridTextColumn.ElementStyle>
-                                    <Style TargetType="TextBlock">
-                                        <Setter Property="HorizontalAlignment"
-                                                Value="Center" />
-                                    </Style>
-                                </DataGridTextColumn.ElementStyle>
-                            </DataGridTextColumn>
-                            <DataGridTextColumn Header="操作员"
-                                                Binding="{Binding Employee}"
-                                                Width="100" />
-                            <DataGridTextColumn Header="绑定时间"
-                                                Binding="{Binding BindTime, StringFormat=yyyy-MM-dd HH:mm:ss}"
-                                                Width="140" />
-                        </DataGrid.Columns>
-                    </DataGrid>
-                </Grid>
+                <tabs:BindRecordsView />
             </TabItem>
-
-            <!-- Tab 5: 加工记录 -->
             <TabItem Header="加工记录">
-                <Grid>
-                    <Grid.RowDefinitions>
-                        <RowDefinition Height="Auto" />
-                        <RowDefinition Height="*" />
-                    </Grid.RowDefinitions>
-
-                    <!-- 工具栏 -->
-                    <StackPanel Grid.Row="0"
-                                Orientation="Horizontal"
-                                Margin="10">
-                        <Button x:Name="btnRefreshProcessRecords"
-                                Content="刷新"
-                                Width="80"
-                                Command="{Binding RefreshProcessRecordsCommand}" />
-                        <Button x:Name="btnClearProcessRecords"
-                                Content="清空"
-                                Width="80"
-                                Margin="10,0,0,0"
-                                Command="{Binding ClearProcessRecordsCommand}" />
-                    </StackPanel>
-
-                    <!-- 加工记录列表 -->
-                    <DataGrid x:Name="dgProcessRecords"
-                              Grid.Row="1"
-                              ItemsSource="{Binding DgProcessRecords}"
-                              SelectedItem="{Binding SelectProcessRecord}"
-                              Margin="10,0,10,10">
-                        <DataGrid.Columns>
-                            <DataGridTextColumn Header="SN"
-                                                Binding="{Binding Sn}"
-                                                Width="150" />
-                            <DataGridTextColumn Header="工位"
-                                                Binding="{Binding Station}"
-                                                Width="100" />
-                            <DataGridTextColumn Header="结果"
-                                                Binding="{Binding OverallResult}"
-                                                Width="60">
-                                <DataGridTextColumn.ElementStyle>
-                                    <Style TargetType="TextBlock">
-                                        <Setter Property="HorizontalAlignment"
-                                                Value="Center" />
-                                        <Setter Property="Foreground"
-                                                Value="{Binding OverallResult, Converter={StaticResource ResultColorConverter}}" />
-                                    </Style>
-                                </DataGridTextColumn.ElementStyle>
-                            </DataGridTextColumn>
-                            <DataGridTextColumn Header="设备"
-                                                Binding="{Binding Equipment}"
-                                                Width="120" />
-                            <DataGridTextColumn Header="加工时间"
-                                                Binding="{Binding ProcessTime, StringFormat=yyyy-MM-dd HH:mm:ss}"
-                                                Width="140" />
-                        </DataGrid.Columns>
-                    </DataGrid>
-                </Grid>
+                <tabs:ProcessRecordsView />
+            </TabItem>
+            <TabItem Header="TCP服务器">
+                <tabs:TcpServerView />
             </TabItem>
-
-            <!-- Tab 6: 系统设置 -->
             <TabItem Header="系统设置">
-                <Grid Margin="10">
-                    <Grid.RowDefinitions>
-                        <RowDefinition Height="Auto" />
-                        <RowDefinition Height="Auto" />
-                        <RowDefinition Height="Auto" />
-                        <RowDefinition Height="Auto" />
-                        <RowDefinition Height="*" />
-                    </Grid.RowDefinitions>
-
-                    <!-- Web API设置 -->
-                    <GroupBox Grid.Row="0"
-                              Header="Web API服务设置">
-                        <StackPanel>
-                            <StackPanel Orientation="Horizontal"
-                                        Margin="0,5">
-                                <TextBlock Text="服务端口:"
-                                           Width="80"
-                                           VerticalAlignment="Center" />
-                                <TextBox x:Name="txtPort"
-                                         Width="100"
-                                         Text="{Binding ServerPort}" />
-                                <Button x:Name="btnStartService"
-                                        Content="启动服务"
-                                        Width="80"
-                                        IsEnabled="{Binding StartServiceEnable}"
-                                        Margin="10,0,0,0"
-                                        Command="{Binding StartServiceCommand}" />
-                                <Button x:Name="btnStopService"
-                                        Content="停止服务"
-                                        Width="80"
-                                        IsEnabled="{Binding StopServiceEnable}"
-                                        Margin="5,0,0,0"
-                                        Command="{Binding StopServiceCommand}" />
-                                <StackPanel Margin="200,0,0,0" Orientation="Horizontal">
-
-                                    <CheckBox Content="屏蔽远程MES" 
-                                            Width="110" 
-                                            IsEnabled="{Binding StopServiceEnable}" 
-                                            Margin="5,0,0,0" 
-                                            IsChecked="{Binding Management.IsLocalhostMode}"/>
-
-                                    <!--<Button Content="停止服务" 
-                                               Width="80" 
-                                                  IsEnabled="{Binding StopServiceEnable}" 
-                                                  Margin="5,0,0,0" 
-                                                  Command="{Binding StopServiceCommand}"/>-->
-
-                                </StackPanel>
-                            </StackPanel>
-                            <TextBlock x:Name="txtServiceStatus"
-                                       Foreground="{Binding  Servicebrushes}"
-                                       Text="{Binding ServiceStatus}"
-                                       Margin="0,5" />
-                        </StackPanel>
-                    </GroupBox>
-
-                    <!-- API客户端设置 -->
-                    <GroupBox Grid.Row="1"
-                              Header="API客户端设置"
-                              Margin="0,10,0,0">
-                        <StackPanel>
-                            <StackPanel Orientation="Horizontal"
-                                        Margin="0,5">
-                                <TextBlock Text="API地址:"
-                                           Width="80"
-                                           VerticalAlignment="Center" />
-                                <TextBox x:Name="txtApiUrl"
-                                         Width="300"
-                                         Text="{Binding ApiUrl}" />
-                            </StackPanel>
-                            <StackPanel Orientation="Horizontal"
-                                        Margin="0,5">
-                                <TextBlock Text="App Key:"
-                                           Width="80"
-                                           VerticalAlignment="Center" />
-                                <TextBox x:Name="txtAppKey"
-                                         Width="200"
-                                         Text="{Binding AppKey}" />
-                            </StackPanel>
-                            <StackPanel Orientation="Horizontal"
-                                        Margin="0,5">
-                                <TextBlock Text="Token:"
-                                           Width="80"
-                                           VerticalAlignment="Center" />
-                                <TextBox x:Name="txtToken"
-                                         Width="200"
-                                         Text="{Binding Token}" />
-                            </StackPanel>
-                            <Button x:Name="btnSaveSettings"
-                                    Content="保存设置"
-                                    Width="80"
-                                    Margin="0,10,0,0"
-                                    Command="{Binding SaveSettingsCommand}" />
-                        </StackPanel>
-                    </GroupBox>
-
-                    <!-- 接口地址 -->
-                    <GroupBox Grid.Row="2"
-                              Header="接口地址"
-                              Margin="0,10,0,0">
-                        <StackPanel>
-                            <TextBlock Text="1. 工单下发接口: /api/mes/receiveWorkOrder"
-                                       Margin="0,2" />
-                            <TextBlock Text="2. SN打印请求接口: /api/mes/requestSnPrint"
-                                       Margin="0,2" />
-                            <TextBlock Text="3. SN关键件绑定接口: /api/mes/receiveSnComponent"
-                                       Margin="0,2" />
-                            <TextBlock Text="4. 加工参数上报接口: /api/mes/receiveProcessParameters"
-                                       Margin="0,2" />
-                        </StackPanel>
-                    </GroupBox>
-
-                    <!-- 工单状态说明 -->
-                    <GroupBox Grid.Row="3"
-                              Header="工单状态说明"
-                              Margin="0,10,0,0">
-                        <StackPanel>
-                            <TextBlock Text="0:已创建、1:已排产、2:已发布、3:关闭、4:已锁定、5:已开工、6:已完成、7:异常完工"
-                                       Margin="0,2" />
-                            <TextBlock Text="冻结状态: 0:否、1:是"
-                                       Margin="0,2" />
-                            <TextBlock Text="下发状态: 0:未下发、1:已下发"
-                                       Margin="0,2" />
-                        </StackPanel>
-                    </GroupBox>
-                </Grid>
+                <tabs:SystemSettingsView />
             </TabItem>
-        </TabControl>
+            </TabControl>
+        </Border>
     </Grid>
 </Window>

+ 130 - 23
LocalhostMES/Views/MainView.xaml.cs

@@ -1,4 +1,5 @@
-using LocalhostMES.Controller;
+using LocalhostMES.Api.Hosting;
+using LocalhostMES.Api.Services;
 using LocalhostMES.Core;
 using LocalhostMES.DataBase;
 using LocalhostMES.Models;
@@ -13,7 +14,6 @@ using System.Windows.Controls;
 using System.Windows.Data;
 using System.Windows.Documents;
 using System.Windows.Input;
-using System.Windows.Media;
 using System.Windows.Media.Imaging;
 using System.Windows.Shapes;
 using Unity;
@@ -115,33 +115,58 @@ namespace LocalhostMES.Views
     public partial class WorkOrderDialog : Window
     {
         public WorkOrderInfo WorkOrder { get; private set; }
+        private readonly bool _isEditMode;
 
         public WorkOrderDialog()
+            : this(null)
         {
+        }
+
+        public WorkOrderDialog(WorkOrderInfo source)
+        {
+            _isEditMode = source != null;
+            WorkOrder = source == null
+                ? new WorkOrderInfo
+                {
+                    WorkOrderNo = "WO-" + DateTime.Now.ToString("yyyyMMddHHmmss"),
+                    Status = "2",
+                    IsLocalhost = true,
+                    LineCode = "RSC01",
+                    CreateTime = DateTime.Now,
+                    PlannedQuantity = 100,
+                    StartTime = DateTime.Now,
+                    EndTime = DateTime.Now
+                }
+                : new WorkOrderInfo
+                {
+                    WorkOrderNo = source.WorkOrderNo,
+                    OrderNo = source.OrderNo,
+                    MaterialCode = source.MaterialCode,
+                    MaterialName = source.MaterialName,
+                    PlannedQuantity = source.PlannedQuantity,
+                    CompletedQuantity = source.CompletedQuantity,
+                    Status = source.Status,
+                    LineCode = source.LineCode,
+                    CreateTime = source.CreateTime,
+                    StartTime = source.StartTime,
+                    EndTime = source.EndTime,
+                    IsLocalhost = source.IsLocalhost
+                };
+
             InitializeComponent();
-            WorkOrder = new WorkOrderInfo
-            {
-                WorkOrderNo = "WO-" + DateTime.Now.ToString("yyyyMMddHHmmss"),
-                Status = "2",
-                LineCode = "RSC01",
-                CreateTime = DateTime.Now,
-                PlannedQuantity = 100,
-                 StartTime=DateTime.Now,
-                 EndTime=DateTime.Now
-            };
             DataContext = WorkOrder;
         }
 
         private void InitializeComponent()
         {
-            if (WorkOrder == null) 
+            if (WorkOrder == null)
             {
                 WorkOrder = new WorkOrderInfo();
             }
             Width = 400;
             Height = 450;
             WindowStartupLocation = WindowStartupLocation.CenterOwner;
-            Title = "创建新工单";
+            Title = _isEditMode ? "修改工单" : "创建新工单";
 
             var grid = new Grid();
             grid.ColumnDefinitions.Add(new ColumnDefinition()); grid.ColumnDefinitions.Add(new ColumnDefinition());
@@ -213,7 +238,7 @@ namespace LocalhostMES.Views
                 Width = 80,
                 Margin = new Thickness(5)
             };
-            okButton.Click += (s, e) => { DatabaseHelper.InsertWorkOrderInfo(WorkOrder);  DialogResult = true; Close(); };
+            okButton.Click += (s, e) => { DialogResult = true; Close(); };
 
             var cancelButton = new Button
             {
@@ -251,21 +276,103 @@ namespace LocalhostMES.Views
         }
     }
 
-    // 结果颜色转换器
-    public class ResultColorConverter : System.Windows.Data.IValueConverter
+    public partial class SnDialog : Window
     {
-        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
+        public SnInfo SnInfo { get; private set; }
+
+        public SnDialog(SnInfo source)
         {
-            if ( value is string result )
+            SnInfo = new SnInfo
             {
-                return result == "OK" ? Brushes.Green : Brushes.Red;
+                Sn = source?.Sn,
+                WorkOrderNo = source?.WorkOrderNo,
+                PrintType = source?.PrintType,
+                GenerateTime = source?.GenerateTime ?? DateTime.Now,
+                IsUsed = source?.IsUsed ?? false
+            };
+
+            InitializeComponent();
+            DataContext = SnInfo;
+        }
+
+        private void InitializeComponent()
+        {
+            Width = 420;
+            Height = 320;
+            WindowStartupLocation = WindowStartupLocation.CenterOwner;
+            Title = "修改SN";
+
+            var grid = new Grid();
+            grid.ColumnDefinitions.Add(new ColumnDefinition());
+            grid.ColumnDefinitions.Add(new ColumnDefinition());
+            for (var i = 0; i < 6; i++)
+            {
+                grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
             }
-            return Brushes.Black;
+            grid.RowDefinitions.Add(new RowDefinition());
+
+            var row = 0;
+            AddLabeledTextBox(grid, "SN条码:", nameof(SnInfo.Sn), row++, false);
+            AddLabeledTextBox(grid, "工单号:", nameof(SnInfo.WorkOrderNo), row++);
+            AddLabeledTextBox(grid, "类型:", nameof(SnInfo.PrintType), row++);
+            AddLabeledTextBox(grid, "生成时间:", nameof(SnInfo.GenerateTime), row++);
+
+            var usedLabel = new Label { Content = "已使用:" };
+            Grid.SetRow(usedLabel, row);
+            Grid.SetColumn(usedLabel, 0);
+            var usedCheck = new CheckBox { VerticalAlignment = VerticalAlignment.Center };
+            usedCheck.SetBinding(CheckBox.IsCheckedProperty, nameof(SnInfo.IsUsed));
+            Grid.SetRow(usedCheck, row);
+            Grid.SetColumn(usedCheck, 1);
+            grid.Children.Add(usedLabel);
+            grid.Children.Add(usedCheck);
+            row++;
+
+            var buttonPanel = new StackPanel
+            {
+                Orientation = Orientation.Horizontal,
+                HorizontalAlignment = HorizontalAlignment.Right,
+                Margin = new Thickness(0, 16, 0, 0)
+            };
+
+            var okButton = new Button
+            {
+                Content = "确定",
+                Width = 80,
+                Margin = new Thickness(5)
+            };
+            okButton.Click += (s, e) => { DialogResult = true; Close(); };
+
+            var cancelButton = new Button
+            {
+                Content = "取消",
+                Width = 80,
+                Margin = new Thickness(5)
+            };
+            cancelButton.Click += (s, e) => { DialogResult = false; Close(); };
+
+            buttonPanel.Children.Add(okButton);
+            buttonPanel.Children.Add(cancelButton);
+            Grid.SetRow(buttonPanel, row);
+            Grid.SetColumnSpan(buttonPanel, 2);
+            grid.Children.Add(buttonPanel);
+
+            Content = grid;
         }
 
-        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
+        private static void AddLabeledTextBox(Grid grid, string label, string bindingPath, int row, bool enabled = true)
         {
-            throw new NotImplementedException();
+            var labelControl = new Label { Content = label };
+            Grid.SetRow(labelControl, row);
+            Grid.SetColumn(labelControl, 0);
+
+            var textBox = new TextBox { IsEnabled = enabled };
+            textBox.SetBinding(TextBox.TextProperty, bindingPath);
+            Grid.SetRow(textBox, row);
+            Grid.SetColumn(textBox, 1);
+
+            grid.Children.Add(labelControl);
+            grid.Children.Add(textBox);
         }
     }
 }

+ 165 - 0
LocalhostMES/Views/Resources/MesTabStyles.xaml

@@ -0,0 +1,165 @@
+<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
+    <SolidColorBrush x:Key="Win11WindowBrush" Color="#F5F6F8" />
+    <SolidColorBrush x:Key="Win11CardBrush" Color="#FFFFFF" />
+    <SolidColorBrush x:Key="Win11BorderBrush" Color="#DEE2E8" />
+    <SolidColorBrush x:Key="Win11PrimaryBrush" Color="#2563EB" />
+    <SolidColorBrush x:Key="Win11PrimaryHoverBrush" Color="#1D4ED8" />
+    <SolidColorBrush x:Key="Win11TextBrush" Color="#111827" />
+    <SolidColorBrush x:Key="Win11SubTextBrush" Color="#6B7280" />
+    <SolidColorBrush x:Key="Win11DangerBrush" Color="#DC2626" />
+    <SolidColorBrush x:Key="Win11SuccessBrush" Color="#16A34A" />
+
+    <Style TargetType="Window">
+        <Setter Property="Background" Value="{DynamicResource Win11WindowBrush}" />
+        <Setter Property="FontFamily" Value="Microsoft YaHei UI" />
+        <Setter Property="TextOptions.TextFormattingMode" Value="Display" />
+        <Setter Property="TextOptions.TextRenderingMode" Value="ClearType" />
+    </Style>
+
+    <Style TargetType="TabControl">
+        <Setter Property="Background" Value="Transparent" />
+        <Setter Property="BorderThickness" Value="0" />
+        <Setter Property="Padding" Value="8" />
+    </Style>
+
+    <Style TargetType="TabItem">
+        <Setter Property="FontSize" Value="13" />
+        <Setter Property="FontWeight" Value="SemiBold" />
+        <Setter Property="Padding" Value="14,8" />
+        <Setter Property="Margin" Value="0,0,6,0" />
+        <Setter Property="Background" Value="#EDF1F7" />
+        <Setter Property="Foreground" Value="{DynamicResource Win11SubTextBrush}" />
+    </Style>
+
+    <Style TargetType="GroupBox">
+        <Setter Property="Margin" Value="0,0,0,10" />
+        <Setter Property="Padding" Value="12" />
+        <Setter Property="BorderBrush" Value="{DynamicResource Win11BorderBrush}" />
+        <Setter Property="BorderThickness" Value="1" />
+        <Setter Property="Background" Value="{DynamicResource Win11CardBrush}" />
+    </Style>
+
+    <Style x:Key="BaseActionButtonStyle" TargetType="Button">
+        <Setter Property="MinWidth" Value="88" />
+        <Setter Property="Height" Value="32" />
+        <Setter Property="Padding" Value="14,0" />
+        <Setter Property="Margin" Value="4,0,0,0" />
+        <Setter Property="Foreground" Value="White" />
+        <Setter Property="Background" Value="{DynamicResource Win11PrimaryBrush}" />
+        <Setter Property="BorderBrush" Value="Transparent" />
+        <Setter Property="BorderThickness" Value="1" />
+        <Setter Property="Cursor" Value="Hand" />
+        <Setter Property="Template">
+            <Setter.Value>
+                <ControlTemplate TargetType="Button">
+                    <Border x:Name="ButtonBorder"
+                            CornerRadius="8"
+                            Background="{TemplateBinding Background}"
+                            BorderBrush="{TemplateBinding BorderBrush}"
+                            BorderThickness="{TemplateBinding BorderThickness}">
+                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
+                    </Border>
+                    <ControlTemplate.Triggers>
+                        <Trigger Property="IsMouseOver" Value="True">
+                            <Setter TargetName="ButtonBorder" Property="Opacity" Value="0.92" />
+                        </Trigger>
+                        <Trigger Property="IsPressed" Value="True">
+                            <Setter TargetName="ButtonBorder" Property="Opacity" Value="0.8" />
+                        </Trigger>
+                        <Trigger Property="IsEnabled" Value="False">
+                            <Setter TargetName="ButtonBorder" Property="Opacity" Value="0.45" />
+                        </Trigger>
+                    </ControlTemplate.Triggers>
+                </ControlTemplate>
+            </Setter.Value>
+        </Setter>
+    </Style>
+
+    <Style TargetType="Button" BasedOn="{StaticResource BaseActionButtonStyle}" />
+    <Style x:Key="SecondaryButtonStyle" TargetType="Button" BasedOn="{StaticResource BaseActionButtonStyle}">
+        <Setter Property="Foreground" Value="{DynamicResource Win11TextBrush}" />
+        <Setter Property="Background" Value="#EEF2F7" />
+    </Style>
+    <Style x:Key="DangerButtonStyle" TargetType="Button" BasedOn="{StaticResource BaseActionButtonStyle}">
+        <Setter Property="Background" Value="{DynamicResource Win11DangerBrush}" />
+    </Style>
+    <Style x:Key="SuccessButtonStyle" TargetType="Button" BasedOn="{StaticResource BaseActionButtonStyle}">
+        <Setter Property="Background" Value="{DynamicResource Win11SuccessBrush}" />
+    </Style>
+
+    <Style TargetType="TextBox">
+        <Setter Property="Margin" Value="4" />
+        <Setter Property="MinHeight" Value="32" />
+        <Setter Property="Padding" Value="10,4" />
+        <Setter Property="VerticalContentAlignment" Value="Center" />
+        <Setter Property="Background" Value="{DynamicResource Win11CardBrush}" />
+        <Setter Property="BorderBrush" Value="{DynamicResource Win11BorderBrush}" />
+        <Setter Property="BorderThickness" Value="1" />
+    </Style>
+
+    <Style TargetType="ComboBox">
+        <Setter Property="Margin" Value="4" />
+        <Setter Property="MinHeight" Value="32" />
+        <Setter Property="Padding" Value="8,2" />
+        <Setter Property="Background" Value="{DynamicResource Win11CardBrush}" />
+        <Setter Property="BorderBrush" Value="{DynamicResource Win11BorderBrush}" />
+        <Setter Property="BorderThickness" Value="1" />
+    </Style>
+
+    <Style TargetType="Label">
+        <Setter Property="Margin" Value="4,5,2,5" />
+        <Setter Property="VerticalAlignment" Value="Center" />
+        <Setter Property="Foreground" Value="{DynamicResource Win11SubTextBrush}" />
+    </Style>
+
+    <Style TargetType="DataGrid">
+        <Setter Property="Margin" Value="0" />
+        <Setter Property="AutoGenerateColumns" Value="False" />
+        <Setter Property="CanUserAddRows" Value="False" />
+        <Setter Property="CanUserDeleteRows" Value="False" />
+        <Setter Property="CanUserResizeRows" Value="False" />
+        <Setter Property="CanUserReorderColumns" Value="False" />
+        <Setter Property="IsReadOnly" Value="True" />
+        <Setter Property="HeadersVisibility" Value="Column" />
+        <Setter Property="GridLinesVisibility" Value="Horizontal" />
+        <Setter Property="BorderBrush" Value="{DynamicResource Win11BorderBrush}" />
+        <Setter Property="BorderThickness" Value="1" />
+        <Setter Property="RowBackground" Value="{DynamicResource Win11CardBrush}" />
+        <Setter Property="AlternatingRowBackground" Value="#F8FAFC" />
+        <Setter Property="HorizontalGridLinesBrush" Value="#EEF2F7" />
+        <Setter Property="ColumnHeaderStyle">
+            <Setter.Value>
+                <Style TargetType="DataGridColumnHeader">
+                    <Setter Property="Background" Value="#EEF2F7" />
+                    <Setter Property="Foreground" Value="{DynamicResource Win11SubTextBrush}" />
+                    <Setter Property="FontWeight" Value="SemiBold" />
+                    <Setter Property="HorizontalContentAlignment" Value="Center" />
+                    <Setter Property="Padding" Value="8,6" />
+                </Style>
+            </Setter.Value>
+        </Setter>
+        <Setter Property="RowStyle">
+            <Setter.Value>
+                <Style TargetType="DataGridRow">
+                    <Style.Triggers>
+                        <Trigger Property="IsMouseOver" Value="True">
+                            <Setter Property="Background" Value="#EEF4FF" />
+                        </Trigger>
+                        <Trigger Property="IsSelected" Value="True">
+                            <Setter Property="Background" Value="#E8F0FE" />
+                            <Setter Property="Foreground" Value="{DynamicResource Win11TextBrush}" />
+                        </Trigger>
+                    </Style.Triggers>
+                </Style>
+            </Setter.Value>
+        </Setter>
+    </Style>
+
+    <Style TargetType="StatusBar">
+        <Setter Property="Background" Value="#EEF2F7" />
+        <Setter Property="BorderBrush" Value="{DynamicResource Win11BorderBrush}" />
+        <Setter Property="BorderThickness" Value="1" />
+        <Setter Property="Padding" Value="8,2" />
+    </Style>
+</ResourceDictionary>

+ 38 - 0
LocalhostMES/Views/Tabs/ApiTestView.xaml

@@ -0,0 +1,38 @@
+<UserControl x:Class="LocalhostMES.Views.Tabs.ApiTestView"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+             xmlns:prism="http://prismlibrary.com/"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             mc:Ignorable="d"
+             d:DesignHeight="400" d:DesignWidth="780"
+             Unloaded="ApiTestView_OnUnloaded">
+    <Grid>
+        <Grid.ColumnDefinitions>
+            <ColumnDefinition Width="400" />
+            <ColumnDefinition Width="*" />
+        </Grid.ColumnDefinitions>
+        <GroupBox Grid.Column="0" Header="接口列表" Margin="10">
+            <StackPanel>
+                <Button Content="测试SN打印请求" Height="40" Margin="0,5" Command="{Binding TestSnPrintCommand}" />
+                <Button Content="测试SN关键件绑定" Height="40" Margin="0,5" Command="{Binding TestSnComponentCommand}" />
+                <Button Content="测试加工参数上报" Height="40" Margin="0,5" Command="{Binding TestProcessParamsCommand}" />
+                <Separator Margin="0,10" />
+                <Button Content="清空日志" Height="30" Margin="0,5" Style="{StaticResource DangerButtonStyle}" Command="{Binding ClearLogCommand}" />
+            </StackPanel>
+        </GroupBox>
+        <GroupBox Grid.Column="1" Header="请求/响应日志" Margin="10">
+            <Grid>
+                <Grid.RowDefinitions>
+                    <RowDefinition Height="*" />
+                    <RowDefinition Height="Auto" />
+                </Grid.RowDefinitions>
+                <ListBox Grid.Row="0" ItemsSource="{Binding Logs}" BorderBrush="Transparent" />
+                <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
+                    <TextBlock Text="{Binding StatusTxt}" Margin="5" Foreground="{Binding StatusForeground}" VerticalAlignment="Center" />
+                </StackPanel>
+            </Grid>
+        </GroupBox>
+    </Grid>
+</UserControl>

+ 21 - 0
LocalhostMES/Views/Tabs/ApiTestView.xaml.cs

@@ -0,0 +1,21 @@
+using System;
+using System.Windows.Controls;
+
+namespace LocalhostMES.Views.Tabs
+{
+    public partial class ApiTestView : UserControl
+    {
+        public ApiTestView()
+        {
+            InitializeComponent();
+        }
+
+        private void ApiTestView_OnUnloaded(object sender, System.Windows.RoutedEventArgs e)
+        {
+            if (DataContext is IDisposable d)
+            {
+                d.Dispose();
+            }
+        }
+    }
+}

+ 39 - 0
LocalhostMES/Views/Tabs/BindRecordsView.xaml

@@ -0,0 +1,39 @@
+<UserControl x:Class="LocalhostMES.Views.Tabs.BindRecordsView"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+             xmlns:prism="http://prismlibrary.com/"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             mc:Ignorable="d"
+             d:DesignHeight="400" d:DesignWidth="780">
+    <Grid>
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="*" />
+        </Grid.RowDefinitions>
+        <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="10">
+            <TextBlock Text="SN:" VerticalAlignment="Center" Margin="4,0" />
+            <TextBox Width="180" Text="{Binding SearchSn, UpdateSourceTrigger=PropertyChanged}" />
+            <Button Content="按SN搜索" Width="96" Style="{StaticResource SecondaryButtonStyle}" Command="{Binding SearchBySnCommand}" />
+            <Button Content="刷新" Width="80" Style="{StaticResource SecondaryButtonStyle}" Command="{Binding RefreshBindRecordsCommand}" />
+            <Button Content="清空" Width="80" Style="{StaticResource DangerButtonStyle}" Command="{Binding ClearBindRecordsCommand}" />
+        </StackPanel>
+        <DataGrid Grid.Row="1" ItemsSource="{Binding DgBindRecords}" SelectedItem="{Binding SelectBindRecord}" Margin="10,0,10,10">
+            <DataGrid.Columns>
+                <DataGridTextColumn Header="SN" Binding="{Binding Sn}" Width="150" />
+                <DataGridTextColumn Header="关键件条码" Binding="{Binding PartNum}" Width="150" />
+                <DataGridTextColumn Header="工位" Binding="{Binding StationCode}" Width="100" />
+                <DataGridTextColumn Header="绑定类型" Binding="{Binding ScanType}" Width="80">
+                    <DataGridTextColumn.ElementStyle>
+                        <Style TargetType="TextBlock">
+                            <Setter Property="HorizontalAlignment" Value="Center" />
+                        </Style>
+                    </DataGridTextColumn.ElementStyle>
+                </DataGridTextColumn>
+                <DataGridTextColumn Header="操作员" Binding="{Binding Employee}" Width="100" />
+                <DataGridTextColumn Header="绑定时间" Binding="{Binding BindTime, StringFormat=yyyy-MM-dd HH:mm:ss}" Width="140" />
+            </DataGrid.Columns>
+        </DataGrid>
+    </Grid>
+</UserControl>

+ 12 - 0
LocalhostMES/Views/Tabs/BindRecordsView.xaml.cs

@@ -0,0 +1,12 @@
+using System.Windows.Controls;
+
+namespace LocalhostMES.Views.Tabs
+{
+    public partial class BindRecordsView : UserControl
+    {
+        public BindRecordsView()
+        {
+            InitializeComponent();
+        }
+    }
+}

+ 110 - 0
LocalhostMES/Views/Tabs/KeyPartManagementView.xaml

@@ -0,0 +1,110 @@
+<UserControl x:Class="LocalhostMES.Views.Tabs.KeyPartManagementView"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+             xmlns:prism="http://prismlibrary.com/"
+             xmlns:enums="clr-namespace:LocalhostMES.Enums"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             mc:Ignorable="d"
+             d:DesignHeight="480" d:DesignWidth="780">
+    <Grid Margin="12">
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="*" />
+            <RowDefinition Height="Auto" />
+        </Grid.RowDefinitions>
+        <TextBlock Grid.Row="0" Text="关键件信息" FontSize="20" FontWeight="Bold" HorizontalAlignment="Center" Margin="0,0,0,12" />
+        <Border Grid.Row="1"
+                BorderBrush="{DynamicResource Win11BorderBrush}"
+                BorderThickness="1"
+                CornerRadius="10"
+                Padding="10"
+                Margin="0,0,0,8"
+                Background="{DynamicResource Win11CardBrush}">
+            <Grid>
+                <Grid.ColumnDefinitions>
+                    <ColumnDefinition Width="Auto" />
+                    <ColumnDefinition Width="*" />
+                    <ColumnDefinition Width="Auto" />
+                    <ColumnDefinition Width="*" />
+                    <ColumnDefinition Width="Auto" />
+                    <ColumnDefinition Width="100" />
+                </Grid.ColumnDefinitions>
+                <Grid.RowDefinitions>
+                    <RowDefinition Height="Auto" />
+                </Grid.RowDefinitions>
+                <Label Grid.Row="0" Grid.Column="0">工站类型:</Label>
+                <ComboBox Grid.Row="0" Grid.Column="1" Margin="4,0" MinWidth="120"
+                          ItemsSource="{enums:EnumBindingSource EnumType={x:Type enums:KeyPartStationType}}"
+                          SelectedItem="{Binding NewPart.StationType}" />
+                <Label Grid.Row="0" Grid.Column="2">关键件号:</Label>
+                <TextBox Grid.Row="0" Grid.Column="3" Margin="4,0" MinWidth="160"
+                         Text="{Binding NewPart.PartNum, UpdateSourceTrigger=PropertyChanged}" />
+                <Label Grid.Row="0" Grid.Column="4">数量:</Label>
+                <TextBox Grid.Row="0" Grid.Column="5" Margin="4,0"
+                         Text="{Binding NewPart.PartQty, UpdateSourceTrigger=PropertyChanged}" />
+            </Grid>
+        </Border>
+        <StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,0,0,8">
+            <Button Content="添加" Style="{StaticResource SuccessButtonStyle}" Command="{Binding AddPartInfoCommand}" />
+            <Button Content="刷新" Style="{StaticResource SecondaryButtonStyle}" Command="{Binding RefPartInfoCommand}" />
+            <Button Content="删除所选" Style="{StaticResource DangerButtonStyle}" Command="{Binding DeletePartInfoCommand}" />
+        </StackPanel>
+        <DataGrid Grid.Row="3" ItemsSource="{Binding PartInfos}" SelectedItem="{Binding SelectPart}" SelectionMode="Single"
+                  AutoGenerateColumns="False" CanUserAddRows="False" IsReadOnly="True" GridLinesVisibility="None"
+                  HeadersVisibility="Column" Margin="0,0,0,8">
+            <DataGrid.Resources>
+                <Style TargetType="DataGridRow">
+                    <Style.Triggers>
+                        <Trigger Property="IsSelected" Value="True">
+                            <Setter Property="Background" Value="#E3F2FD" />
+                            <Setter Property="BorderBrush" Value="#2196F3" />
+                        </Trigger>
+                    </Style.Triggers>
+                </Style>
+                <Style TargetType="DataGridColumnHeader">
+                    <Setter Property="Background" Value="#2196F3" />
+                    <Setter Property="Foreground" Value="White" />
+                    <Setter Property="FontWeight" Value="Bold" />
+                    <Setter Property="Padding" Value="10,5" />
+                    <Setter Property="HorizontalContentAlignment" Value="Center" />
+                </Style>
+            </DataGrid.Resources>
+            <DataGrid.Columns>
+                <DataGridTextColumn Header="工站类型" Binding="{Binding StationType}" Width="100" />
+                <DataGridTextColumn Header="关键件号" Binding="{Binding PartNum}" Width="*" MinWidth="160" />
+                <DataGridTextColumn Header="数量" Binding="{Binding PartQty}" Width="80">
+                    <DataGridTextColumn.ElementStyle>
+                        <Style TargetType="TextBlock">
+                            <Setter Property="HorizontalAlignment" Value="Right" />
+                            <Setter Property="Margin" Value="0,0,10,0" />
+                        </Style>
+                    </DataGridTextColumn.ElementStyle>
+                </DataGridTextColumn>
+                <DataGridTemplateColumn Header="操作" Width="90">
+                    <DataGridTemplateColumn.CellTemplate>
+                        <DataTemplate>
+                            <Button Content="删除" Padding="5,2" Margin="2,0" Background="#F44336" Foreground="White"
+                                    Command="{Binding DataContext.DeletePartRowCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
+                                    CommandParameter="{Binding}" />
+                        </DataTemplate>
+                    </DataGridTemplateColumn.CellTemplate>
+                </DataGridTemplateColumn>
+            </DataGrid.Columns>
+        </DataGrid>
+        <StatusBar Grid.Row="4">
+            <StatusBarItem>
+                <TextBlock>
+                    <Run Text="记录总数:" />
+                    <Run Text="{Binding PartInfos.Count, Mode=OneWay}" />
+                </TextBlock>
+            </StatusBarItem>
+            <StatusBarItem HorizontalAlignment="Right">
+                <TextBlock Text="{Binding StatusMessage}" />
+            </StatusBarItem>
+        </StatusBar>
+    </Grid>
+</UserControl>

+ 12 - 0
LocalhostMES/Views/Tabs/KeyPartManagementView.xaml.cs

@@ -0,0 +1,12 @@
+using System.Windows.Controls;
+
+namespace LocalhostMES.Views.Tabs
+{
+    public partial class KeyPartManagementView : UserControl
+    {
+        public KeyPartManagementView()
+        {
+            InitializeComponent();
+        }
+    }
+}

+ 155 - 0
LocalhostMES/Views/Tabs/PartCatalogView.xaml

@@ -0,0 +1,155 @@
+<UserControl x:Class="LocalhostMES.Views.Tabs.PartCatalogView"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+             xmlns:prism="http://prismlibrary.com/"
+             xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             mc:Ignorable="d"
+             d:DesignHeight="480"
+             d:DesignWidth="780">
+    <b:Interaction.Triggers>
+        <b:EventTrigger EventName="Loaded">
+            <b:InvokeCommandAction Command="{Binding LoadedCommand}" />
+        </b:EventTrigger>
+    </b:Interaction.Triggers>
+    <Grid Margin="10">
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="*" />
+        </Grid.RowDefinitions>
+        <TextBlock Grid.Row="0"
+                   Text="零件管理"
+                   FontSize="20"
+                   FontWeight="Bold"
+                   HorizontalAlignment="Center"
+                   Margin="0,0,0,16" />
+        <GroupBox Grid.Row="1"
+                  Header="添加/编辑零件"
+                  Margin="0,0,0,10">
+            <Grid Margin="10">
+                <Grid.ColumnDefinitions>
+                    <ColumnDefinition Width="Auto" />
+                    <ColumnDefinition Width="*" />
+                </Grid.ColumnDefinitions>
+                <Grid.RowDefinitions>
+                    <RowDefinition Height="Auto" />
+                    <RowDefinition Height="Auto" />
+                    <RowDefinition Height="Auto" />
+                </Grid.RowDefinitions>
+                <TextBlock Grid.Row="0"
+                           Grid.Column="0"
+                           Text="名称:"
+                           VerticalAlignment="Center"
+                           Margin="5" />
+                <TextBox Grid.Row="0"
+                         Grid.Column="1"
+                         Margin="5"
+                         MinWidth="240"
+                         Text="{Binding CurrentParkingLot.PartName, UpdateSourceTrigger=PropertyChanged}" />
+                <TextBlock Grid.Row="1"
+                           Grid.Column="0"
+                           Text="数量:"
+                           VerticalAlignment="Center"
+                           Margin="5" />
+                <TextBox Grid.Row="1"
+                         Grid.Column="1"
+                         Margin="5"
+                         Width="160"
+                         Text="{Binding CurrentParkingLot.Quantity, UpdateSourceTrigger=PropertyChanged}" />
+                <StackPanel Grid.Row="2"
+                            Grid.Column="0"
+                            Grid.ColumnSpan="2"
+                            Orientation="Horizontal"
+                            HorizontalAlignment="Center"
+                            Margin="0,16,0,0">
+                    <Button Content="添加"
+                            Width="80"
+                            Height="30"
+                            Margin="10"
+                            Command="{Binding AddCommand}" />
+                    <Button Content="更新"
+                            Width="80"
+                            Height="30"
+                            Margin="10"
+                            Command="{Binding UpdateCommand}"
+                            IsEnabled="{Binding IsEditMode}" />
+                    <Button Content="取消编辑"
+                            Width="90"
+                            Height="30"
+                            Margin="10"
+                            Command="{Binding CancelEditCommand}"
+                            IsEnabled="{Binding IsEditMode}" />
+                    <Button Content="清空"
+                            Width="80"
+                            Height="30"
+                            Margin="10"
+                            Command="{Binding ClearFormCommand}" />
+                </StackPanel>
+            </Grid>
+        </GroupBox>
+        <GroupBox Grid.Row="2"
+                  Header="零件列表">
+            <Grid>
+                <Grid.RowDefinitions>
+                    <RowDefinition Height="*" />
+                    <RowDefinition Height="Auto" />
+                </Grid.RowDefinitions>
+                <DataGrid Grid.Row="0"
+                          AutoGenerateColumns="False"
+                          ItemsSource="{Binding ParkingLots}"
+                          SelectedItem="{Binding SelectedParkingLot, Mode=TwoWay}"
+                          CanUserAddRows="False"
+                          CanUserDeleteRows="False"
+                          SelectionMode="Single"
+                          SelectionUnit="FullRow"
+                          Margin="5"
+                          IsReadOnly="True">
+                    <DataGrid.Columns>
+                        <DataGridTextColumn Header="名称"
+                                            Binding="{Binding PartName}"
+                                            Width="*"
+                                            MinWidth="160" />
+                        <DataGridTextColumn Header="数量"
+                                            Binding="{Binding Quantity}"
+                                            Width="100" />
+                        <DataGridTemplateColumn Header="操作"
+                                                Width="160">
+                            <DataGridTemplateColumn.CellTemplate>
+                                <DataTemplate>
+                                    <StackPanel Orientation="Horizontal">
+                                        <Button Content="编辑"
+                                                Width="56"
+                                                Margin="2"
+                                                Command="{Binding DataContext.EditCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
+                                                CommandParameter="{Binding}" />
+                                        <Button Content="删除"
+                                                Width="56"
+                                                Margin="2"
+                                                Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
+                                                CommandParameter="{Binding}" />
+                                    </StackPanel>
+                                </DataTemplate>
+                            </DataGridTemplateColumn.CellTemplate>
+                        </DataGridTemplateColumn>
+                    </DataGrid.Columns>
+                </DataGrid>
+                <StackPanel Grid.Row="1"
+                            Orientation="Horizontal"
+                            HorizontalAlignment="Right"
+                            Margin="5">
+                    <TextBlock Text="总计:"
+                               FontWeight="Bold"
+                               Margin="5" />
+                    <TextBlock Text="{Binding ParkingLots.Count}"
+                               Foreground="Blue"
+                               Margin="5" />
+                    <TextBlock Text="条"
+                               Margin="5" />
+                </StackPanel>
+            </Grid>
+        </GroupBox>
+    </Grid>
+</UserControl>

+ 12 - 0
LocalhostMES/Views/Tabs/PartCatalogView.xaml.cs

@@ -0,0 +1,12 @@
+using System.Windows.Controls;
+
+namespace LocalhostMES.Views.Tabs
+{
+    public partial class PartCatalogView : UserControl
+    {
+        public PartCatalogView()
+        {
+            InitializeComponent();
+        }
+    }
+}

+ 39 - 0
LocalhostMES/Views/Tabs/ProcessRecordsView.xaml

@@ -0,0 +1,39 @@
+<UserControl x:Class="LocalhostMES.Views.Tabs.ProcessRecordsView"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+             xmlns:prism="http://prismlibrary.com/"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             mc:Ignorable="d"
+             d:DesignHeight="400" d:DesignWidth="780">
+    <Grid>
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="*" />
+        </Grid.RowDefinitions>
+        <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="10">
+            <TextBlock Text="SN:" VerticalAlignment="Center" Margin="4,0" />
+            <TextBox Width="180" Text="{Binding SearchSn, UpdateSourceTrigger=PropertyChanged}" />
+            <Button Content="按SN搜索" Width="96" Style="{StaticResource SecondaryButtonStyle}" Command="{Binding SearchBySnCommand}" />
+            <Button Content="刷新" Width="80" Style="{StaticResource SecondaryButtonStyle}" Command="{Binding RefreshProcessRecordsCommand}" />
+            <Button Content="清空" Width="80" Style="{StaticResource DangerButtonStyle}" Command="{Binding ClearProcessRecordsCommand}" />
+        </StackPanel>
+        <DataGrid Grid.Row="1" ItemsSource="{Binding DgProcessRecords}" SelectedItem="{Binding SelectProcessRecord}" Margin="10,0,10,10">
+            <DataGrid.Columns>
+                <DataGridTextColumn Header="SN" Binding="{Binding Sn}" Width="150" />
+                <DataGridTextColumn Header="工位" Binding="{Binding Station}" Width="100" />
+                <DataGridTextColumn Header="结果" Binding="{Binding OverallResult}" Width="60">
+                    <DataGridTextColumn.ElementStyle>
+                        <Style TargetType="TextBlock">
+                            <Setter Property="HorizontalAlignment" Value="Center" />
+                            <Setter Property="Foreground" Value="{Binding OverallResult, Converter={StaticResource ResultColorConverter}}" />
+                        </Style>
+                    </DataGridTextColumn.ElementStyle>
+                </DataGridTextColumn>
+                <DataGridTextColumn Header="设备" Binding="{Binding Equipment}" Width="120" />
+                <DataGridTextColumn Header="加工时间" Binding="{Binding ProcessTime, StringFormat=yyyy-MM-dd HH:mm:ss}" Width="140" />
+            </DataGrid.Columns>
+        </DataGrid>
+    </Grid>
+</UserControl>

+ 12 - 0
LocalhostMES/Views/Tabs/ProcessRecordsView.xaml.cs

@@ -0,0 +1,12 @@
+using System.Windows.Controls;
+
+namespace LocalhostMES.Views.Tabs
+{
+    public partial class ProcessRecordsView : UserControl
+    {
+        public ProcessRecordsView()
+        {
+            InitializeComponent();
+        }
+    }
+}

+ 39 - 0
LocalhostMES/Views/Tabs/SnManagementView.xaml

@@ -0,0 +1,39 @@
+<UserControl x:Class="LocalhostMES.Views.Tabs.SnManagementView"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+             xmlns:prism="http://prismlibrary.com/"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             mc:Ignorable="d"
+             d:DesignHeight="400" d:DesignWidth="780">
+    <Grid>
+        <Grid.ColumnDefinitions>
+            <ColumnDefinition Width="*" />
+        </Grid.ColumnDefinitions>
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="*" />
+        </Grid.RowDefinitions>
+        <GroupBox Grid.Row="0" Header="查询条件" Margin="10,10,10,10" Grid.ColumnSpan="1">
+            <StackPanel Orientation="Horizontal">
+                <TextBlock Text="工单号:" VerticalAlignment="Center" Margin="5,0" />
+                <ComboBox ItemsSource="{Binding DgWorkOrders}" DisplayMemberPath="WorkOrderNo" SelectedValuePath="WorkOrderNo" SelectedValue="{Binding SearchWorkOrder}" Width="160" />
+                <TextBox Width="150" Margin="5,0" Text="{Binding SearchWorkOrder}" />
+                <Button Content="查询" Width="80" Style="{StaticResource SecondaryButtonStyle}" Command="{Binding SearchSnsCommand}" />
+                <Button Content="修改" Width="80" Style="{StaticResource SuccessButtonStyle}" Command="{Binding EditSnCommand}" />
+                <Button Content="转绑定记录" Width="96" Style="{StaticResource SecondaryButtonStyle}" Command="{Binding GotoBindRecordsCommand}" />
+                <Button Content="转加工记录" Width="96" Style="{StaticResource SecondaryButtonStyle}" Command="{Binding GotoProcessRecordsCommand}" />
+            </StackPanel>
+        </GroupBox>
+        <DataGrid Grid.Row="1" ItemsSource="{Binding DgSns}" SelectedItem="{Binding SelectSnInfo}" Margin="10,0,10,10">
+            <DataGrid.Columns>
+                <DataGridTextColumn Header="SN条码" Binding="{Binding Sn}" Width="200" />
+                <DataGridTextColumn Header="工单号" Binding="{Binding WorkOrderNo}" Width="120" />
+                <DataGridTextColumn Header="类型" Binding="{Binding PrintType}" Width="80" />
+                <DataGridTextColumn Header="生成时间" Binding="{Binding GenerateTime, StringFormat=yyyy-MM-dd HH:mm:ss}" Width="140" />
+                <DataGridCheckBoxColumn Header="已使用" Binding="{Binding IsUsed}" Width="70" />
+            </DataGrid.Columns>
+        </DataGrid>
+    </Grid>
+</UserControl>

+ 12 - 0
LocalhostMES/Views/Tabs/SnManagementView.xaml.cs

@@ -0,0 +1,12 @@
+using System.Windows.Controls;
+
+namespace LocalhostMES.Views.Tabs
+{
+    public partial class SnManagementView : UserControl
+    {
+        public SnManagementView()
+        {
+            InitializeComponent();
+        }
+    }
+}

+ 77 - 0
LocalhostMES/Views/Tabs/SystemSettingsView.xaml

@@ -0,0 +1,77 @@
+<UserControl x:Class="LocalhostMES.Views.Tabs.SystemSettingsView"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+             xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+             xmlns:prism="http://prismlibrary.com/"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             mc:Ignorable="d"
+             d:DesignHeight="480" d:DesignWidth="780">
+    <Grid Margin="10">
+        <b:Interaction.Triggers>
+            <b:EventTrigger EventName="Loaded">
+                <b:InvokeCommandAction Command="{Binding ViewLoadedCommand}" />
+            </b:EventTrigger>
+        </b:Interaction.Triggers>
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="*" />
+        </Grid.RowDefinitions>
+        <GroupBox Grid.Row="0" Header="Web API服务设置">
+            <StackPanel>
+                <StackPanel Orientation="Horizontal" Margin="0,5">
+                    <TextBlock Text="服务端口:" Width="80" VerticalAlignment="Center" />
+                    <TextBox Width="100" Text="{Binding ServerPort}" />
+                    <Button Content="启动服务" Style="{StaticResource SuccessButtonStyle}" Width="90" IsEnabled="{Binding StartServiceEnable}" Command="{Binding StartServiceCommand}" />
+                    <Button Content="停止服务" Style="{StaticResource DangerButtonStyle}" Width="90" IsEnabled="{Binding StopServiceEnable}" Command="{Binding StopServiceCommand}" />
+                    <CheckBox Content="屏蔽远程MES" Width="120" IsEnabled="{Binding StopServiceEnable}" Margin="24,0,0,0" IsChecked="{Binding Management.IsLocalhostMode}" />
+                </StackPanel>
+                <TextBlock Foreground="{Binding Servicebrushes}" Text="{Binding ServiceStatus}" Margin="0,5" />
+            </StackPanel>
+        </GroupBox>
+        <GroupBox Grid.Row="1" Header="API客户端设置" Margin="0,12,0,0">
+            <StackPanel>
+                <StackPanel Orientation="Horizontal" Margin="0,5">
+                    <TextBlock Text="API地址:" Width="80" VerticalAlignment="Center" />
+                    <TextBox Width="320" Text="{Binding ApiUrl}" />
+                </StackPanel>
+                <StackPanel Orientation="Horizontal" Margin="0,5">
+                    <TextBlock Text="App Key:" Width="80" VerticalAlignment="Center" />
+                    <TextBox Width="220" Text="{Binding AppKey}" />
+                </StackPanel>
+                <StackPanel Orientation="Horizontal" Margin="0,5">
+                    <TextBlock Text="Token:" Width="80" VerticalAlignment="Center" />
+                    <TextBox Width="220" Text="{Binding Token}" />
+                </StackPanel>
+                <Button Content="保存设置" Style="{StaticResource SecondaryButtonStyle}" Width="90" Margin="0,10,0,0" Command="{Binding SaveSettingsCommand}" />
+            </StackPanel>
+        </GroupBox>
+        <GroupBox Grid.Row="2" Header="外观主题" Margin="0,12,0,0">
+            <StackPanel Orientation="Horizontal">
+                <TextBlock Text="深色模式:" Width="80" VerticalAlignment="Center" />
+                <CheckBox IsChecked="{Binding IsDarkTheme}" VerticalAlignment="Center" />
+                <TextBlock Text="(切换后立即生效)" Margin="8,0,0,0" VerticalAlignment="Center" Opacity="0.8" />
+            </StackPanel>
+        </GroupBox>
+        <GroupBox Grid.Row="3" Header="接口地址" Margin="0,12,0,0">
+            <StackPanel>
+                <TextBlock Text="1. 工单下发接口: /api/mes/receiveWorkOrder" Margin="0,2" />
+                <TextBlock Text="2. SN打印请求接口: /api/mes/requestSnPrint" Margin="0,2" />
+                <TextBlock Text="3. SN关键件绑定接口: /api/mes/receiveSnComponent" Margin="0,2" />
+                <TextBlock Text="4. 加工参数上报接口: /api/mes/receiveProcessParameters" Margin="0,2" />
+            </StackPanel>
+        </GroupBox>
+        <GroupBox Grid.Row="4" Header="工单状态说明" Margin="0,12,0,0">
+            <StackPanel>
+                <TextBlock Text="0:已创建、1:已排产、2:已发布、3:关闭、4:已锁定、5:已开工、6:已完成、7:异常完工" Margin="0,2" TextWrapping="Wrap" />
+                <TextBlock Text="冻结状态: 0:否、1:是" Margin="0,2" />
+                <TextBlock Text="下发状态: 0:未下发、1:已下发" Margin="0,2" />
+            </StackPanel>
+        </GroupBox>
+    </Grid>
+</UserControl>

+ 12 - 0
LocalhostMES/Views/Tabs/SystemSettingsView.xaml.cs

@@ -0,0 +1,12 @@
+using System.Windows.Controls;
+
+namespace LocalhostMES.Views.Tabs
+{
+    public partial class SystemSettingsView : UserControl
+    {
+        public SystemSettingsView()
+        {
+            InitializeComponent();
+        }
+    }
+}

+ 69 - 0
LocalhostMES/Views/Tabs/TcpServerView.xaml

@@ -0,0 +1,69 @@
+<UserControl x:Class="LocalhostMES.Views.Tabs.TcpServerView"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+             xmlns:prism="http://prismlibrary.com/"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             mc:Ignorable="d"
+             d:DesignHeight="480" d:DesignWidth="780">
+    <Grid Margin="10">
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="*" />
+        </Grid.RowDefinitions>
+
+        <GroupBox Header="TCP服务器">
+            <StackPanel Orientation="Horizontal">
+                <TextBlock Text="监听端口:" VerticalAlignment="Center" Margin="4,0" />
+                <TextBox Width="120" Text="{Binding ServerPort, UpdateSourceTrigger=PropertyChanged}" />
+                <Button Content="启动" Width="80" Style="{StaticResource SuccessButtonStyle}" Command="{Binding StartServerCommand}" />
+                <Button Content="停止" Width="80" Style="{StaticResource DangerButtonStyle}" Command="{Binding StopServerCommand}" />
+                <TextBlock Text="{Binding IsRunning, StringFormat=运行状态: {0}}" VerticalAlignment="Center" Margin="10,0,0,0" />
+            </StackPanel>
+        </GroupBox>
+
+        <GroupBox Grid.Row="1" Header="手动发送" Margin="0,10,0,10">
+            <Grid>
+                <Grid.ColumnDefinitions>
+                    <ColumnDefinition Width="260" />
+                    <ColumnDefinition Width="*" />
+                    <ColumnDefinition Width="Auto" />
+                </Grid.ColumnDefinitions>
+                <ComboBox Grid.Column="0"
+                          ItemsSource="{Binding Clients}"
+                          SelectedItem="{Binding SelectedClient}"
+                          DisplayMemberPath="RemoteEndPoint"
+                          MinWidth="220" />
+                <TextBox Grid.Column="1" Margin="6,0,6,0"
+                         Text="{Binding OutgoingMessage, UpdateSourceTrigger=PropertyChanged}" />
+                <Button Grid.Column="2" Content="发送" Width="80" Command="{Binding SendMessageCommand}" />
+            </Grid>
+        </GroupBox>
+
+        <Grid Grid.Row="2">
+            <Grid.ColumnDefinitions>
+                <ColumnDefinition Width="280" />
+                <ColumnDefinition Width="10" />
+                <ColumnDefinition Width="*" />
+            </Grid.ColumnDefinitions>
+
+            <GroupBox Grid.Column="0" Header="已连接客户端">
+                <DataGrid ItemsSource="{Binding Clients}"
+                          SelectedItem="{Binding SelectedClient}"
+                          Margin="0"
+                          AutoGenerateColumns="False">
+                    <DataGrid.Columns>
+                        <DataGridTextColumn Header="客户端" Binding="{Binding RemoteEndPoint}" Width="*" />
+                        <DataGridTextColumn Header="ID" Binding="{Binding ClientId}" Width="120" />
+                    </DataGrid.Columns>
+                </DataGrid>
+            </GroupBox>
+
+            <GroupBox Grid.Column="2" Header="收发日志">
+                <ListBox ItemsSource="{Binding MessageLogs}" />
+            </GroupBox>
+        </Grid>
+    </Grid>
+</UserControl>

+ 15 - 0
LocalhostMES/Views/Tabs/TcpServerView.xaml.cs

@@ -0,0 +1,15 @@
+using System.Windows.Controls;
+
+namespace LocalhostMES.Views.Tabs
+{
+    /// <summary>
+    /// TcpServerView.xaml 的交互逻辑
+    /// </summary>
+    public partial class TcpServerView : UserControl
+    {
+        public TcpServerView()
+        {
+            InitializeComponent();
+        }
+    }
+}

+ 40 - 0
LocalhostMES/Views/Tabs/WorkOrderManagementView.xaml

@@ -0,0 +1,40 @@
+<UserControl x:Class="LocalhostMES.Views.Tabs.WorkOrderManagementView"
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+             xmlns:prism="http://prismlibrary.com/"
+             prism:ViewModelLocator.AutoWireViewModel="True"
+             mc:Ignorable="d"
+             d:DesignHeight="400" d:DesignWidth="780">
+    <Grid>
+        <Grid.RowDefinitions>
+            <RowDefinition Height="Auto" />
+            <RowDefinition Height="*" />
+        </Grid.RowDefinitions>
+        <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="10">
+            <Button Content="刷新" Style="{StaticResource SecondaryButtonStyle}" Width="80" Command="{Binding RefreshWorkOrdersCommand}" />
+            <Button Content="添加工单" Style="{StaticResource SuccessButtonStyle}" Width="88" Command="{Binding AddWorkOrderCommand}" />
+            <Button Content="修改工单" Style="{StaticResource SecondaryButtonStyle}" Width="88" Command="{Binding EditWorkOrderCommand}" />
+            <Button Content="删除工单" Style="{StaticResource DangerButtonStyle}" Width="88" Command="{Binding DeleteWorkOrderCommand}" />
+        </StackPanel>
+        <DataGrid Grid.Row="1" SelectedItem="{Binding SelectWorkOrderInfo}" ItemsSource="{Binding DgWorkOrders}" Margin="10,0,10,10">
+            <DataGrid.Columns>
+                <DataGridTextColumn Header="工单号" Binding="{Binding WorkOrderNo}" Width="120" />
+                <DataGridTextColumn Header="物料编码" Binding="{Binding MaterialCode}" Width="100" />
+                <DataGridTextColumn Header="物料名称" Binding="{Binding MaterialName}" Width="150" />
+                <DataGridTextColumn Header="计划数量" Binding="{Binding PlannedQuantity}" Width="80" />
+                <DataGridTextColumn Header="完成数量" Binding="{Binding CompletedQuantity}" Width="80" />
+                <DataGridTextColumn Header="状态" Binding="{Binding StatusDisplay}" Width="88">
+                    <DataGridTextColumn.ElementStyle>
+                        <Style TargetType="TextBlock">
+                            <Setter Property="HorizontalAlignment" Value="Center" />
+                        </Style>
+                    </DataGridTextColumn.ElementStyle>
+                </DataGridTextColumn>
+                <DataGridTextColumn Header="线体编码" Binding="{Binding LineCode}" Width="80" />
+                <DataGridTextColumn Header="创建时间" Binding="{Binding CreateTime, StringFormat=yyyy-MM-dd HH:mm}" Width="140" />
+            </DataGrid.Columns>
+        </DataGrid>
+    </Grid>
+</UserControl>

+ 12 - 0
LocalhostMES/Views/Tabs/WorkOrderManagementView.xaml.cs

@@ -0,0 +1,12 @@
+using System.Windows.Controls;
+
+namespace LocalhostMES.Views.Tabs
+{
+    public partial class WorkOrderManagementView : UserControl
+    {
+        public WorkOrderManagementView()
+        {
+            InitializeComponent();
+        }
+    }
+}

+ 2 - 0
LocalhostMES/packages.config

@@ -105,6 +105,8 @@
   <package id="System.Text.Encodings.Web" version="10.0.1" targetFramework="net472" />
   <package id="System.Text.Json" version="10.0.1" targetFramework="net472" />
   <package id="System.Threading.Tasks.Extensions" version="4.6.3" targetFramework="net472" />
+  <package id="TouchSocket" version="3.1.17" targetFramework="net472" />
+  <package id="TouchSocket.Core" version="3.1.17" targetFramework="net472" />
   <package id="System.ValueTuple" version="4.6.1" targetFramework="net472" />
   <package id="Unity" version="5.11.1" targetFramework="net472" />
   <package id="Unity.Abstractions" version="5.11.7" targetFramework="net472" />