using System.Collections.ObjectModel; using System.Data; using System.IO; using System.Text; using System.Windows.Input; using HandyControl.Controls; using log4net; using Microsoft.Data.Sqlite; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using SparkClient.Model.Entity; using SparkClient.Model.Helper; using SparkClient.ViewModel.Configuration.SettingsPages; using MessageBox = SparkClient.Views.Dialog.MessageBox; using SparkClient.Model.Attributes; using SparkClient.Model.Extension; namespace SparkClient.ViewModel.Configuration; public class AlgorithmConfigVM : BaseViewModel { private static readonly ILog Logger = LogManager.GetLogger(typeof(AlgorithmConfigVM)); public ICommand SaveAlgorithmDataCommand { get; } public ICommand BeautifyJsonCommand { get; } public ICommand UglifyJsonCommand { get; } private ObservableCollection _agileJsonConfigEntities; public ObservableCollection AgileJsonConfigEntities { get => _agileJsonConfigEntities; set { _agileJsonConfigEntities = value; OnPropertyChanged(nameof(AgileJsonConfigEntities)); } } public List _jsonKeysBak; private bool _isEnabled; public bool IsEnabled { get { return _isEnabled; } set { _isEnabled = value; OnPropertyChanged(nameof(IsEnabled)); } } private string _AlgorithmConfigJson; public string AlgorithmConfigJson { get { return _AlgorithmConfigJson; } set { _AlgorithmConfigJson = value; OnPropertyChanged("AlgorithmConfigJson"); } } public AlgorithmConfigVM() { SaveAlgorithmDataCommand = new RelayCommand(SaveAlgorithmData); BeautifyJsonCommand = new RelayCommand(BeautifyJson); UglifyJsonCommand = new RelayCommand(UglifyJson); InitAlgorithmData(null); IsEnabledByRole(); _jsonKeysBak = GetNestedKeys(JObject.Parse(AlgorithmConfigJson)); InitAgileJsonConfig(); } private void InitAgileJsonConfig() { AgileJsonConfigEntities = new ObservableCollection(); string sql = @"SELECT Mode, Shape, Spec, JsonKey, Value FROM AGILE_ALGORITHM_CONFIG"; DataTable dataTable = DataBaseHelper.ExecuteQuery(sql); var baseData = new AgileJsonConfigEntity(_jsonKeysBak); if (dataTable != null && dataTable.Rows.Count >= 0) { foreach (DataRow row in dataTable.Rows) { try { AgileJsonConfigEntities.Add(new AgileJsonConfigEntity(_jsonKeysBak) { Mode = baseData.ModeList.Find(e => e.Value.Equals(row["Mode"].ToSafeString())), Spec = baseData.SpceList.Find(e => e.Value.Equals(row["Spec"].ToSafeString())), Shape = row["Shape"].ToSafeString(), JsonKey = row["JsonKey"].ToSafeString(), Value = row["Value"].ToSafeString() }); } catch { } } } } private bool CheckAndSaveAgileJson() { var finalSaveData = new ObservableCollection(); var insertSql = new List(); foreach (var row in AgileJsonConfigEntities) { if (string.IsNullOrWhiteSpace(row.JsonKey) || string.IsNullOrWhiteSpace(row.Value) || string.IsNullOrWhiteSpace(row.Shape)) continue; if (row.Mode == null || row.Spec == null) continue; insertSql.Add($"INSERT INTO AGILE_ALGORITHM_CONFIG (GUID, Mode, Spec, Shape, JsonKey, Value)" + $@"VALUES ('{row.toMD5Code()}',{row.Mode.Value},'{row.Spec.Value}','{row.Shape}','{row.JsonKey}','{row.Value}');"); finalSaveData.Add(row); } AgileJsonConfigEntities = finalSaveData; var deleteSql = $"DELETE FROM AGILE_ALGORITHM_CONFIG;"; try { DataBaseHelper.BeginTransaction(); DataBaseHelper.ExecuteNonQuery(deleteSql); insertSql.ForEach(e => DataBaseHelper.ExecuteNonQuery(e)); DataBaseHelper.commit(); } catch (Exception e) { Logger.Error($"灵活配置存储异常:{e.Message}\r\n {e.StackTrace}"); new MessageBox().Show($"灵活配置存储异常:{e.Message}"); DataBaseHelper.rollback(); return false; } return true; } public string GetAlgorithmConfig(string param) { string sql = @"SELECT Mode, Shape, Spec, JsonKey, Value FROM AGILE_ALGORITHM_CONFIG"; DataTable dataTable = DataBaseHelper.ExecuteQuery(sql); if (dataTable != null && dataTable.Rows.Count >= 0) { var jsonAlgorithm = JToken.Parse(_AlgorithmConfigJson); foreach (DataRow row in dataTable.Rows) { //只对当前运行环境有效 if (Common.RunMode == int.Parse(row["Mode"].ToSafeString())) { } } return jsonAlgorithm.ToString(); } return _AlgorithmConfigJson; } /// /// 初始化算法数据 /// /// [Log] public void InitAlgorithmData(object param) { try { AlgorithmConfigJson = "{}"; string sql = @"SELECT JSON as json FROM ALGORITHM_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(); } } catch (Exception ex) { new MessageBox().Show($"{MultilingualHelper.getString("ApplicationError")}{ex.Message}"); Logger.Error($"全局异常捕获:{ex.Message}", ex); } } // 命令实现 public ICommand AddCommand => new RelayCommand((param) => { AgileJsonConfigEntities.Add(new AgileJsonConfigEntity(_jsonKeysBak)); }); private List GetNestedKeys(JToken token, string prefix = "") { var keys = new List(); if (token is JObject obj) { foreach (var property in obj.Properties()) { var currentKey = string.IsNullOrEmpty(prefix) ? property.Name : $"{prefix}.{property.Name}"; keys.Add(currentKey); keys.AddRange(GetNestedKeys(property.Value, currentKey)); } } return keys; } /// /// 保存数据 /// /// [Log] public void SaveAlgorithmData(object param) { try { if (!CheckAndSaveAgileJson()) { return; } DataBaseHelper.BeginTransaction(); string temp = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(AlgorithmConfigJson)); string deleteSql = @"DELETE FROM ALGORITHM_CONFIG"; DataBaseHelper.ExecuteNonQuery(deleteSql); int order = 0; int insertCount = 0; while (temp.Length > 2000) { AlgorithmConfigEntity entity = new AlgorithmConfigEntity() { GUID = Guid.NewGuid(), JsonOrder = order++, 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) { AlgorithmConfigEntity entity = new AlgorithmConfigEntity() { GUID = Guid.NewGuid(), JsonOrder = order++, 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(MultilingualHelper.getString("SaveSuccess")); DataBaseHelper.commit(); } else { Growl.Error(MultilingualHelper.getString("SaveFail")); DataBaseHelper.rollback(); } } catch (Exception ex) { Growl.Error(MultilingualHelper.getString("SaveFail")); Logger.Error($"全局异常捕获:{ex.Message}",ex); } } private void IsEnabledByRole (){ string PERMISSIONS = Settings.SelectValueById("PERMISSIONS"); if ("admin".Equals(PERMISSIONS)) { IsEnabled = true; } else { IsEnabled = false; } } /// /// 美化JSON /// /// [Log] public void BeautifyJson(object param) { try { AlgorithmConfigJson = JToken.Parse(AlgorithmConfigJson).ToString(); } catch (Exception ex) { Growl.ErrorGlobal(ex.Message); } } /// /// 压缩JSON /// /// [Log] public void UglifyJson(object param) { AlgorithmConfigJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(AlgorithmConfigJson)); } // 公共方法来获取 AlgorithmConfigJson [Log] public string GetAlgorithmConfigJson() { return AlgorithmConfigJson; } }