diff --git a/MainWindow.xaml.cs b/MainWindow.xaml.cs index ea6a3d4..f4c5b89 100644 --- a/MainWindow.xaml.cs +++ b/MainWindow.xaml.cs @@ -41,6 +41,7 @@ public partial class MainWindow { //初始化 // ConfigHelper.Instance.SetLang("en"); + DataBaseHelper.CreateConnection(); } #region 重写窗体操作按钮 @@ -83,6 +84,7 @@ public partial class MainWindow if (result == MessageBoxResult.Yes) { + DataBaseHelper.CloseConnection(); this.Close(); } } diff --git a/Model/Entity/CutterConfigEntity.cs b/Model/Entity/CutterConfigEntity.cs new file mode 100644 index 0000000..a8edfb7 --- /dev/null +++ b/Model/Entity/CutterConfigEntity.cs @@ -0,0 +1,87 @@ +using SparkClient.Model.Entity.Base; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace SparkClient.Model.Entity; + +/// +/// 系统设置实体 +/// + +public class CutterConfigEntity : BaseEntity +{ + public static readonly new string TableName = "CUTTER_CONFIG"; + [DbField("GUID")] + public Guid GUID { get; set; } + /// + /// 项目名称 + /// + [DbField("ITEM_NAME")] + public string ItemName { get; set; } + /// + /// key + /// + [DbField("KEY")] + public string Key { get; set; } + /// + /// value + /// + [DbField("VALUE")] + public string Value { get; set; } + private static Dictionary GetFieldMappings() + { + var properties = typeof(CutterConfigEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance); + return properties + .Where(p => Attribute.IsDefined(p, typeof(DbFieldAttribute))) + .ToDictionary( + p => p.Name, + p => ((DbFieldAttribute)p.GetCustomAttribute(typeof(DbFieldAttribute))).FieldName + ); + } + + // 生成 Insert 语句 + public string GenerateInsertSQL() + { + var mappings = GetFieldMappings(); + var columns = string.Join(", ", mappings.Values); + var values = string.Join(", ", mappings.Keys.Select(k => $"@{k}")); + return $"INSERT INTO {TableName} ({columns}) VALUES ({values});"; + } + + // 生成 Update 语句 + public string GenerateUpdateSQL(Dictionary fieldsToUpdate = null) + { + if (fieldsToUpdate == null || fieldsToUpdate.Count == 0) + { + // 默认根据 ID 更新所有字段 + var mappings = GetFieldMappings(); + var setClause = string.Join(", ", mappings.Values.Select(f => $"{f} = @{f}")); + return $"UPDATE {TableName} SET {setClause} WHERE GUID = @GUID;"; + } + else + { + // 根据传入的字段更新 + var setClause = string.Join(", ", fieldsToUpdate.Keys.Select(f => $"{f} = @{f}")); + return $"UPDATE {TableName} SET {setClause} WHERE GUID = @GUID;"; + } + } + + // 生成 Delete 语句 + public string GenerateDeleteSQL(Dictionary conditions = null) + { + if (conditions == null || conditions.Count == 0) + { + // 默认根据 ID 删除 + return $"DELETE FROM {TableName} WHERE GUID ='" + GUID.ToString() + "';"; + } + else + { + // 根据传入条件删除 + var whereClause = string.Join(" AND ", conditions.Keys.Select(f => $"{f} = @{f}")); + return $"DELETE FROM {TableName} WHERE {whereClause};"; + } + } + +} + + diff --git a/Model/Entity/MethodConfigEntity.cs b/Model/Entity/MethodConfigEntity.cs new file mode 100644 index 0000000..eb6e33e --- /dev/null +++ b/Model/Entity/MethodConfigEntity.cs @@ -0,0 +1,83 @@ +using SparkClient.Model.Entity.Base; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace SparkClient.Model.Entity; + +/// +/// 系统设置实体 +/// + +public class MethodConfigEntity : BaseEntity +{ + public static readonly new string TableName = "METHOD_CONFIG"; + [DbField("GUID")] + public Guid GUID { get; set; } + /// + /// json内容 + /// + [DbField("JSON")] + public string Json { get; set; } + /// + /// Json排序 + /// + [DbField("JSON_ORDER")] + public int JsonOrder { get; set; } + + private static Dictionary GetFieldMappings() + { + var properties = typeof(MethodConfigEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance); + return properties + .Where(p => Attribute.IsDefined(p, typeof(DbFieldAttribute))) + .ToDictionary( + p => p.Name, + p => ((DbFieldAttribute)p.GetCustomAttribute(typeof(DbFieldAttribute))).FieldName + ); + } + + // 生成 Insert 语句 + public string GenerateInsertSQL() + { + var mappings = GetFieldMappings(); + var columns = string.Join(", ", mappings.Values); + var values = string.Join(", ", mappings.Keys.Select(k => $"@{k}")); + return $"INSERT INTO {TableName} ({columns}) VALUES ({values});"; + } + + // 生成 Update 语句 + public string GenerateUpdateSQL(Dictionary fieldsToUpdate = null) + { + if (fieldsToUpdate == null || fieldsToUpdate.Count == 0) + { + // 默认根据 ID 更新所有字段 + var mappings = GetFieldMappings(); + var setClause = string.Join(", ", mappings.Values.Select(f => $"{f} = @{f}")); + return $"UPDATE {TableName} SET {setClause} WHERE GUID = " + GUID.ToString() + ";"; + } + else + { + // 根据传入的字段更新 + var setClause = string.Join(", ", fieldsToUpdate.Keys.Select(f => $"{f} = @{f}")); + return $"UPDATE {TableName} SET {setClause} WHERE GUID = " + GUID.ToString() + ";"; + } + } + + // 生成 Delete 语句 + public string GenerateDeleteSQL(Dictionary conditions = null) + { + if (conditions == null || conditions.Count == 0) + { + // 默认根据 ID 删除 + return $"DELETE FROM {TableName} WHERE GUID =" + GUID.ToString() + ";"; + } + else + { + // 根据传入条件删除 + var whereClause = string.Join(" AND ", conditions.Keys.Select(f => $"{f} = @{f}")); + return $"DELETE FROM {TableName} WHERE {whereClause};"; + } + } + +} + + diff --git a/Model/Helper/DataBaseHelper.cs b/Model/Helper/DataBaseHelper.cs index 202cbe7..8324d62 100644 --- a/Model/Helper/DataBaseHelper.cs +++ b/Model/Helper/DataBaseHelper.cs @@ -1,4 +1,5 @@ -using System.IO; +using System.Data; +using System.IO; using Microsoft.Data.Sqlite; namespace SparkClient.Model.Helper; @@ -32,4 +33,107 @@ public class DataBaseHelper connection.Close(); } + + static readonly string password = Common.DatabasePwd; + static readonly string dbPath = Common.DataBaseFileName; + static SqliteConnection connection; + static SqliteTransaction sqliteTransaction; + + public static void CreateConnection() + { + connection = new SqliteConnection(new SqliteConnectionStringBuilder("data source=" + DataBaseHelper.dbPath) + { + Mode = SqliteOpenMode.ReadWriteCreate, + Password = password + }.ToString()); + if (connection.State != ConnectionState.Open) { + connection.Open(); + using (var command = connection.CreateCommand()) + { + command.CommandText = "PRAGMA key = '" + password + "';"; + command.CommandText += "PRAGMA case_sensitive_like = 1;"; + command.ExecuteNonQuery(); + } + } + } + + public static void CloseConnection() + { + connection.Close(); + } + public static void BeginTransaction() + { + if (connection != null) + { + sqliteTransaction = connection.BeginTransaction(); + } + } + public static void commit() + { + if (sqliteTransaction != null) + { + sqliteTransaction.Commit(); + sqliteTransaction.Dispose(); + sqliteTransaction = null; + } + } + public static void rollback() + { + if (sqliteTransaction != null) + { + sqliteTransaction.Rollback(); + sqliteTransaction.Dispose(); + sqliteTransaction = null; + } + } + + public static int ExecuteNonQuery(string sql, SqliteParameter[] sqlParameters = null) + { + int resultCount = -1; + try + { + SqliteCommand cmd = new SqliteCommand(); + cmd.Connection = connection; + cmd.CommandText = sql; + cmd.Transaction = sqliteTransaction; + if (sqlParameters != null) + { + cmd.Parameters.AddRange(sqlParameters); + } + resultCount = cmd.ExecuteNonQuery(); + cmd.Parameters.Clear(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + + return resultCount; + } + + //查询全部 + public static DataTable ExecuteQuery(String sql, SqliteParameter[] sqlParameters = null) + { + DataTable table = new DataTable(); + try + { + SqliteCommand cmd = new SqliteCommand(); + cmd.Connection = connection; + cmd.CommandText = sql; + if (sqlParameters != null) + { + cmd.Parameters.AddRange(sqlParameters); + } + SqliteDataReader reader = cmd.ExecuteReader(); + cmd.Parameters.Clear(); + table.Load(reader); + return table; + } + catch (Exception ex) + { + System.Windows.MessageBox.Show("检索失败"); + Console.WriteLine(ex.ToString()); + } + return null; + } } \ No newline at end of file diff --git a/Resource/Images/ze-add-o 1@3x.png b/Resource/Images/ze-add-o 1@3x.png new file mode 100644 index 0000000..362f13e Binary files /dev/null and b/Resource/Images/ze-add-o 1@3x.png differ diff --git a/ViewModel/Configuration/AlgorithmConfigVM.cs b/ViewModel/Configuration/AlgorithmConfigVM.cs index 92d1837..18ef232 100644 --- a/ViewModel/Configuration/AlgorithmConfigVM.cs +++ b/ViewModel/Configuration/AlgorithmConfigVM.cs @@ -1,7 +1,12 @@ -using System.Windows.Input; +using System.Data; +using System.Text; +using System.Windows.Input; using HandyControl.Controls; +using Microsoft.Data.Sqlite; using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using SparkClient.Model.Entity; +using SparkClient.Model.Helper; namespace SparkClient.ViewModel.Configuration; @@ -28,8 +33,22 @@ public class AlgorithmConfigVM : BaseViewModel /// public void InitAlgorithmData(object param) { - AlgorithmConfigJson = "{}"; - } + AlgorithmConfigJson = "{}"; + string sql = @"SELECT JSON as json FROM METHOD_CONFIG ORDER BY JSON_ORDER"; + DataTable dataTable = DataBaseHelper.ExecuteQuery(sql); + StringBuilder sb = new StringBuilder(); + if (dataTable != null) + { + foreach (DataRow row in dataTable.Rows) + { + sb.Append(row["json"].ToString()); + } + } + if(sb.Length>0) + { + AlgorithmConfigJson = JToken.Parse(sb.ToString()).ToString(); + } + } /// @@ -38,11 +57,55 @@ public class AlgorithmConfigVM : BaseViewModel /// public void SaveAlgorithmData(object param) { - Growl.Info("Saving Algorithm Data"); + DataBaseHelper.BeginTransaction(); + string temp = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(AlgorithmConfigJson)); + string deleteSql = @"DELETE FROM METHOD_CONFIG"; + DataBaseHelper.ExecuteNonQuery(deleteSql); + int order = 0; + int insertCount = 0; + while (temp.Length>2000) + { + MethodConfigEntity entity = new MethodConfigEntity(); + entity.GUID = Guid.NewGuid(); + entity.JsonOrder = order++; + entity.Json = temp.Substring(0,2000); + temp = temp.Substring(2000); + string sql = entity.GenerateInsertSQL(); + SqliteParameter[] sqliteParameters = { + new SqliteParameter("@Json", entity.Json), + new SqliteParameter("@JsonOrder", entity.JsonOrder), + new SqliteParameter("@GUID", entity.GUID), + }; + insertCount += DataBaseHelper.ExecuteNonQuery(sql, sqliteParameters); + } + if (temp.Length>0) + { + MethodConfigEntity entity = new MethodConfigEntity(); + entity.GUID = Guid.NewGuid(); + entity.JsonOrder = order++; + entity.Json = temp; + string sql = entity.GenerateInsertSQL(); + SqliteParameter[] sqliteParameters = { + new SqliteParameter("@Json", entity.Json), + new SqliteParameter("@JsonOrder", entity.JsonOrder), + new SqliteParameter("@GUID", entity.GUID.ToString()), + }; + insertCount += DataBaseHelper.ExecuteNonQuery(sql, sqliteParameters); + } + if (insertCount >= 0) + { + Growl.Info("保存成功"); + DataBaseHelper.commit(); + } + else + { + Growl.Error("保存失败"); + DataBaseHelper.rollback(); + } } /// - /// 梅花JSON + /// 美化JSON /// /// public void BeautifyJson(object param) diff --git a/ViewModel/Configuration/ConfigMenuPageVM.cs b/ViewModel/Configuration/ConfigMenuPageVM.cs index 0ee8fb0..f0ea75f 100644 --- a/ViewModel/Configuration/ConfigMenuPageVM.cs +++ b/ViewModel/Configuration/ConfigMenuPageVM.cs @@ -43,6 +43,7 @@ public class ConfigMenuPageVM : BaseViewModel public void AlgorithmConfig(object parameter) { BaseControlVM vm = new BaseControlVM(new AlgorithmConfigVM(), MultilingualHelper.getString("AlgorithmConfig")); + vm.ShowFunctionButton = System.Windows.Visibility.Hidden; WindowManager.mainViewModel.Content = vm; WindowManager.openContent.Add(vm); } @@ -53,6 +54,7 @@ public class ConfigMenuPageVM : BaseViewModel public void CutConfig(object parameter) { BaseControlVM vm = new BaseControlVM(new CutConfigVM(), MultilingualHelper.getString("CutConfig")); + vm.ShowFunctionButton = System.Windows.Visibility.Hidden; WindowManager.mainViewModel.Content = vm; WindowManager.openContent.Add(vm); } diff --git a/ViewModel/Configuration/CutConfigVM.cs b/ViewModel/Configuration/CutConfigVM.cs index 4bcc97a..a1657a2 100644 --- a/ViewModel/Configuration/CutConfigVM.cs +++ b/ViewModel/Configuration/CutConfigVM.cs @@ -1,14 +1,37 @@ -namespace SparkClient.ViewModel.Configuration; +using HandyControl.Controls; +using System.Data; +using System.Windows.Controls; +using System.Windows.Input; +using SparkClient.Model.Entity; +using SparkClient.Model.Helper; +using static System.Windows.Forms.VisualStyles.VisualStyleElement.ToolTip; +using System.Text.RegularExpressions; +using Microsoft.Data.Sqlite; + +namespace SparkClient.ViewModel.Configuration; public class CutConfigVM: BaseViewModel { - + public ICommand AddRowsCommand { get; } + public ICommand SaveCutConfigDataCommand { get; } + public ICommand DelCutRowCommand { get; } + + public DataTable _cutterInfos; + public DataTable CutterInfos { get { return _cutterInfos; } set { _cutterInfos = value; OnPropertyChanged("CutterInfos"); } } + + private int RowNo = 0; public CutConfigVM() { + AddRowsCommand = new RelayCommand(AddRows); + + SaveCutConfigDataCommand = new RelayCommand(SaveCutConfigData); + + DelCutRowCommand = new RelayCommand(DelCutRow); // 初始化VIEW层参数 // 初始化VIEW层Command this.InitCutConfigData(null); } + /// /// 初始化切工仪数据 @@ -16,6 +39,16 @@ public class CutConfigVM: BaseViewModel /// public void InitCutConfigData(object param) { + string sql = @"SELECT ITEM_NAME as ItemName , KEY AS Key, VALUE AS Value, GUID FROM CUTTER_CONFIG"; + DataTable dataTable = DataBaseHelper.ExecuteQuery(sql); + if (dataTable!=null) { + dataTable.Columns.Add(new DataColumn("RowNo", typeof(int))); + foreach (DataRow row in dataTable.Rows) + { + row["RowNo"] = RowNo++; + } + CutterInfos = dataTable; + } } /// @@ -24,7 +57,10 @@ public class CutConfigVM: BaseViewModel /// 行数 public void AddRows(object row) { - + for (int i = 0;i<5;i++) + { + CutterInfos.Rows.Add("", "", "",Guid.NewGuid(), RowNo++); + } } /// @@ -33,7 +69,74 @@ public class CutConfigVM: BaseViewModel /// public void SaveCutConfigData(object param) { - + int count = CutterInfos.AsEnumerable().Where(r => r["Key"].ToString() != "").GroupBy(r => new { key = r.Field("Key") }).Count(); + if (count < CutterInfos.AsEnumerable().Where(r => r["Key"].ToString() != "").Count()) + { + Growl.Error("Key有重复数据"); + return; + } + string sql = @"SELECT ITEM_NAME as ItemName , KEY AS Key, VALUE AS Value, GUID FROM CUTTER_CONFIG"; + DataTable dataTable = DataBaseHelper.ExecuteQuery(sql); + int insertCount = 0; + foreach (DataRow row in CutterInfos.Rows) + { + if (row["Key"] == "") + { + continue; + } + DataRow removerow = dataTable.AsEnumerable().Where(r => r["GUID"].ToString() == row["GUID"].ToString()).FirstOrDefault(); + if (removerow != null) + { + CutterConfigEntity entity = new CutterConfigEntity(); + entity.ItemName = row["ItemName"].ToString(); + entity.Key = row["Key"].ToString(); + entity.Value = row["Value"].ToString(); + entity.GUID = Guid.Parse(row["GUID"].ToString()); + sql = entity.GenerateUpdateSQL(); + SqliteParameter[] sqliteParameters = { + new SqliteParameter("@ITEM_NAME", row["ItemName"].ToString()), + new SqliteParameter("@KEY", row["Key"].ToString()), + new SqliteParameter("@VALUE", row["Value"].ToString()), + new SqliteParameter("@GUID", row["GUID"].ToString()), + }; + insertCount += DataBaseHelper.ExecuteNonQuery(sql, sqliteParameters); + dataTable.Rows.Remove(removerow); + } + else + { + CutterConfigEntity entity = new CutterConfigEntity(); + entity.ItemName = row["ItemName"].ToString(); + entity.Key = row["Key"].ToString(); + entity.Value = row["Value"].ToString(); + sql = entity.GenerateInsertSQL(); + SqliteParameter[] sqliteParameters = { + new SqliteParameter("@ItemName", row["ItemName"].ToString()), + new SqliteParameter("@Key", row["Key"].ToString()), + new SqliteParameter("@Value", row["Value"].ToString()), + new SqliteParameter("@GUID", row["GUID"].ToString()), + }; + insertCount += DataBaseHelper.ExecuteNonQuery(sql, sqliteParameters); + } + } + foreach (DataRow row in dataTable.Rows) + { + CutterConfigEntity entity = new CutterConfigEntity(); + entity.ItemName = row["ItemName"].ToString(); + entity.Key = row["Key"].ToString(); + entity.Value = row["Value"].ToString(); + Guid.TryParse(row["GUID"].ToString(), out Guid result); + entity.GUID = result; + sql = entity.GenerateDeleteSQL(); + insertCount += DataBaseHelper.ExecuteNonQuery(sql); + } + if (insertCount>=0) + { + Growl.Info("保存成功"); + } + else + { + Growl.Error("保存失败"); + } } /// @@ -42,6 +145,7 @@ public class CutConfigVM: BaseViewModel /// 行 public void DelCutRow(object row) { - + DataRowView a = row as DataRowView; + CutterInfos.Rows.Remove(a.Row); } } \ No newline at end of file diff --git a/Views/Configuration/CutConfigPage.xaml b/Views/Configuration/CutConfigPage.xaml index f655217..54ff6c5 100644 --- a/Views/Configuration/CutConfigPage.xaml +++ b/Views/Configuration/CutConfigPage.xaml @@ -1,12 +1,81 @@  - - 切工仪配置 + xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" + xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" + xmlns:d="http://schemas.microsoft.com/expression/blend/2008" + xmlns:local="clr-namespace:SparkClient.Views" + mc:Ignorable="d"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +