You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

315 lines
9.9 KiB

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;
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; }
public List<AgileJsonConfigEntity> AgileJsonConfigEntities { get; set; }
public List<string> JsonKeysBak = new List<string>();
public List<Param> ModeList { get; set; }
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));
ModeList = GetRunModelList();
AgileJsonConfigEntities = new List<AgileJsonConfigEntity>();
AgileJsonConfigEntities.Add(new AgileJsonConfigEntity(this, JsonKeysBak) {
Mode = 0,
Spec = "p8-p8",
});
}
/// <summary>
/// 初始化算法数据
/// </summary>
/// <param name="param"></param>
[Log]
public void InitAlgorithmData(object param)
{
try
{
if (param == null)
{
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();
}
}
else
{
string[] types = param.ToString().Split(" ");
string filename = string.Empty;
if (types.Last().Equals("S4"))
{
filename = "p8p8s4.config";
}else if (types.Last().Equals("S3"))
{
filename = "p8p8s3.config";
}else if (types.Last().Equals("S2"))
{
filename = "p8p8s2.config";
}else if (types.Last().Equals("S1"))
{
filename = "p8p8s1.config";
}else
{
filename = "p8p8.config";
}
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SparkCore", "config",filename);
if (!File.Exists(filePath))
{
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();
}
}
else
{
string content = File.ReadAllText(filePath);
AlgorithmConfigJson = JToken.Parse(content).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(this, JsonKeysBak)
{
Mode = 0,
Spec = "p8-p8",
});
});
private static readonly Dictionary<int, List<string>> SpecOptions = new()
{
[0] = new List<string> { "p8-p8" },
[1] = new List<string> {
"p8-p8", "p8-p8-s1", "p8-p8-s2",
"p8-p8-s3", "p8-p8-s4"
}
};
public List<string> GetSpecOptions(int mode)
{
return SpecOptions.TryGetValue(mode, out var options)
? options
: new List<string>();
}
private List<string> GetNestedKeys(JToken token, string prefix = "")
{
var keys = new List<string>();
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;
}
/// <summary>
/// 保存数据
/// </summary>
/// <param name="param"></param>
[Log]
public void SaveAlgorithmData(object param)
{
try
{
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;
}
}
/// <summary>
/// 美化JSON
/// </summary>
/// <param name="param"></param>
[Log]
public void BeautifyJson(object param)
{
try
{
AlgorithmConfigJson = JToken.Parse(AlgorithmConfigJson).ToString();
}
catch (Exception ex)
{
Growl.ErrorGlobal(ex.Message);
}
}
/// <summary>
/// 压缩JSON
/// </summary>
/// <param name="param"></param>
[Log]
public void UglifyJson(object param)
{
AlgorithmConfigJson = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(AlgorithmConfigJson));
}
// 公共方法来获取 AlgorithmConfigJson
[Log]
public string GetAlgorithmConfigJson()
{
return AlgorithmConfigJson;
}
public List<Param> GetRunModelList()
{
return new List<Param>
{
new Param()
{
Value = "0",
Name = "实验室模式"
},
new Param()
{
Value = "1",
Name = "工厂模式"
}
};
}
}
public class Param
{
public string Value { get; set; }
public string Name { get; set; }
}