Env.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. using ControlzEx.Theming;
  2. using DIL;
  3. using SCADA.CommonCtrl.WpfHelper;
  4. using SCADA.CommonLib;
  5. using SCADA.CommonLib.Data.DIL;
  6. using SCADA.CommonLib.Helper;
  7. using SCADA_DAQ.Plugin.Core.License;
  8. using SysManage.User;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Collections.ObjectModel;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Reflection;
  15. using System.Windows;
  16. using System.Windows.Media;
  17. using SCADA_DAQ.Plugin.CoreUI;
  18. using SCADA.CommonLib.License;
  19. namespace SCADA_DAQ
  20. {
  21. class Env
  22. {
  23. public static DILDBV1 DAL = null;
  24. public static bool EnvInitFinish = false;
  25. public static User NewUser;
  26. public static Schedual Schedual { get; internal set; } = Schedual.Instance;
  27. public static DateTime StartTime { get; set; }
  28. public static int StartTick { get; internal set; }
  29. public static DataBaseConfig CurrentDbConfig { get; set; }
  30. public static AutoSaveParameterItem<DatabaseSelector> CurrentDataBase { get; set; }
  31. public static DataBaseConfig SysDBConfig { get; set; }
  32. public static AutoSaveParameterItem<DatabaseSelector> SysDataBase { get; set; }
  33. public static DataBaseConfig AlarmDBConfig { get; set; }
  34. public static AutoSaveParameterItem<DatabaseSelector> AlarmDataBase { get; set; }
  35. public static AutoSaveParameterItem<ObservableCollection<DataBaseConfig>> DataBaseResource { get; set; }
  36. public static AutoSaveParameterItem<bool> DataBaseNeedRest { get; set; } = AutoSaveParameterItem.Create("App.DatabaseNeedRest", false);
  37. /// <summary>
  38. /// 产量个数
  39. /// </summary>
  40. public static AutoSaveParameterItem<int> TotalOutputPcs { get; set; } = AutoSaveParameterItem.Create("App.TotalOutputPcs", 0);
  41. /// <summary>
  42. /// 产量
  43. /// </summary>
  44. public static AutoSaveParameterItem<decimal> TotalOutputQty { get; set; } = AutoSaveParameterItem.Create("App.TotalOutputQty", 0m);
  45. public static void ParameterInit(IApp app)
  46. {
  47. CurrentDataBase = AutoSaveParameterItem.Create("App.DataBaseConfig", new DatabaseSelector()
  48. { CurrentDataBaseConfig = "Default" });
  49. SysDataBase = AutoSaveParameterItem.Create("App.DataBaseConfig.System", new DatabaseSelector()
  50. { CurrentDataBaseConfig = "SysDB" });
  51. AlarmDataBase = AutoSaveParameterItem.Create("App.DataBaseConfig.Alarm", new DatabaseSelector()
  52. { CurrentDataBaseConfig = "AlarmDB" });
  53. DataBaseResource = AutoSaveParameterItem.Create("App.DataBaseResource",
  54. new ObservableCollection<DataBaseConfig>()
  55. {
  56. new DataBaseConfig()
  57. {
  58. ResourceName="Default",
  59. DBType = DatabaseType.Sqlite,
  60. FilePath = @"Data\Platform.db"
  61. },
  62. new DataBaseConfig()
  63. {
  64. ResourceName="AlarmDB",
  65. DBType = DatabaseType.Sqlite,
  66. FilePath = @"Data\Alarmdb.db"
  67. },
  68. new DataBaseConfig()
  69. {
  70. ResourceName="SysDB",
  71. DBType = DatabaseType.Sqlite,
  72. FilePath = @"Data\LocalApp.db"
  73. },
  74. }, true);
  75. dataBaseConfigInit(DataBaseResource, CurrentDataBase.Value, out var currentconfig);
  76. dataBaseConfigInit(DataBaseResource, SysDataBase.Value, out var sysConfig);
  77. dataBaseConfigInit(DataBaseResource, AlarmDataBase.Value, out var alarmConfig);
  78. CurrentDbConfig = currentconfig;
  79. AlarmDBConfig = alarmConfig;
  80. SysDBConfig = sysConfig;
  81. void dataBaseConfigInit(ObservableCollection<DataBaseConfig> srouce, DatabaseSelector selector, out DataBaseConfig config)
  82. {
  83. config = DataBaseResource.Value.FirstOrDefault(t => t.ResourceName == selector?.CurrentDataBaseConfig);
  84. selector.DataBaseConfigResource = DataBaseResource.Value;
  85. if (config == null)
  86. {
  87. config = DataBaseResource.Value.FirstOrDefault();
  88. selector.CurrentDataBaseConfig = config.ResourceName;
  89. }
  90. selector.DataBaseConfig = config;
  91. }
  92. app.ThemeConfig.ThemeNameSrc = new List<string> { "Light", "Dark" };
  93. app.ThemeConfig.ThemeColorSrc = new List<string>() { "Red", "Green", "Blue", "Purple", "Orange", "Lime", "Emerald", "Teal", "Cyan", "Cobalt", "Indigo", "Violet", "Pink", "Magenta", "Crimson", "Amber", "Yellow", "Brown", "Olive", "Steel", "Mauve", "Taupe", "Sienna" };
  94. app.ThemeConfig.LanguageSrc = new Dictionary<string, string>()
  95. {
  96. {"中文(简体)","zh-cn" },
  97. {"中文(繁体)","zh-tw" },
  98. {"English(US)","en-us" },
  99. {"Deutsch","de-de" },
  100. {"Руская","ru-ru" },
  101. {"日本語","ja-jp" },
  102. {"한국어","ko-kr" },
  103. {"ภาษาไทย","th-th"}
  104. };
  105. app.ThemeConfig.PropertyChanged += SystemConfig_PropertyChanged;
  106. bool neeRestDatabase = DataBaseNeedRest.Value;
  107. DAL = new DILDBV1(CurrentDbConfig.GetDB());
  108. CheckDataBase(DAL, CurrentDbConfig.NeedReset || DataBaseNeedRest.Value);
  109. //GlobalEnv.Instance.GlobalDB = DAL;
  110. //GlobalEnv.Instance.AlarmDB = new DILDBV1(AlarmDBConfig.GetDB());
  111. //CheckDataBase(GlobalEnv.Instance.AlarmDB as BaseDB, CurrentDbConfig.NeedReset || DataBaseNeedRest.Value);
  112. //GlobalEnv.Instance.LocalAppDB = new LocalDB.DIL.DILDBV1(SysDBConfig.GetDB());
  113. //CheckDataBase(GlobalEnv.Instance.LocalAppDB as BaseDB, CurrentDbConfig.NeedReset || DataBaseNeedRest.Value);
  114. app.RuntimeInfo.GlobalDB = DAL;
  115. app.RuntimeInfo.AlarmDB = new DILDBV1(AlarmDBConfig.GetDB());
  116. CheckDataBase(app.RuntimeInfo.AlarmDB as BaseDB, CurrentDbConfig.NeedReset || DataBaseNeedRest.Value);
  117. app.RuntimeInfo.LocalAppDB = new LocalDB.DIL.DILDBV1(SysDBConfig.GetDB());
  118. CheckDataBase(app.RuntimeInfo.LocalAppDB as BaseDB, CurrentDbConfig.NeedReset || DataBaseNeedRest.Value);
  119. NewUser = new User(DAL)
  120. {
  121. UserName = "Admin",
  122. PassWordReviseHandler = () =>
  123. {
  124. var passWordRevise = new FrmUserLogin(new PasswordReviseViewModel(NewUser));
  125. ((BaseMainWindow)Application.Current.MainWindow).ShowChildWindow(passWordRevise);
  126. },
  127. TryLoginHandler = () =>
  128. {
  129. if (NewUser.IsLogged == false)
  130. {
  131. FrmUserLogin frmUserLog = new FrmUserLogin(new UserLoginViewModel(NewUser));
  132. ((BaseMainWindow)Application.Current.MainWindow).ShowChildWindow(frmUserLog);
  133. }
  134. else
  135. {
  136. (Application.Current as IApp).ShowToast($"{LanguageHelper.GetStringByKey("SysCfg_CurrentUser")}{NewUser.UserName}", ControlStyle.Info);
  137. }
  138. },
  139. MidCheckHandler = () =>
  140. {
  141. var frmUserLog = new FrmUserLogin(new UserLoginViewModel(NewUser));
  142. if (NewUser.IsLogged == false)
  143. {
  144. ((BaseMainWindow)Application.Current.MainWindow).ShowChildWindow(frmUserLog);
  145. return NewUser.IsLogged;
  146. }
  147. else
  148. {
  149. return NewUser.IsLogged;
  150. }
  151. }
  152. };
  153. app.RuntimeInfo.User = NewUser;
  154. EnvInitFinish = true;
  155. }
  156. private static void SystemConfig_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
  157. {
  158. if (e.PropertyName == nameof(ThemeConfig.Language))
  159. {
  160. SetLanguage();
  161. }
  162. else if (e.PropertyName == nameof(ThemeConfig.ThemeColors) || e.PropertyName == nameof(ThemeConfig.ThemeName))
  163. {
  164. SetTheme();
  165. }
  166. else if (e.PropertyName == nameof(ThemeConfig.FontName) || e.PropertyName == nameof(ThemeConfig.FontSize) || e.PropertyName == nameof(ThemeConfig.FontWeight))
  167. {
  168. SetFont();
  169. }
  170. }
  171. static Env()
  172. {
  173. }
  174. public static void SetLanguage()
  175. {
  176. try
  177. {
  178. List<ResourceDictionary> dictionaryList = new List<ResourceDictionary>();
  179. foreach (ResourceDictionary dictionary in Application.Current.Resources.MergedDictionaries)
  180. {
  181. dictionaryList.Add(dictionary);
  182. }
  183. string requestedCulture = $@"{(Application.Current as IApp).ThemeConfig.Language}.xaml";
  184. ResourceDictionary resourceDictionary = null;
  185. ResourceDictionary defaultLanguage = null;
  186. foreach (var item in dictionaryList)
  187. {
  188. try
  189. {
  190. if (item.Source == null) continue;
  191. if (item.Source.Segments.LastOrDefault() == requestedCulture)
  192. {
  193. resourceDictionary = item;
  194. }
  195. if (item.Source.Segments.LastOrDefault() == "zh-cn.xaml")
  196. {
  197. defaultLanguage = item;
  198. }
  199. }
  200. catch (Exception)
  201. {
  202. }
  203. }
  204. if (requestedCulture == null) return;
  205. Application.Current.Resources.MergedDictionaries.Remove(resourceDictionary);
  206. Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);
  207. LanguageHelper.CurrentLanguageDictionary = resourceDictionary;
  208. LanguageHelper.DefaultLanguageDictionary = defaultLanguage;
  209. }
  210. catch (Exception ex)
  211. {
  212. System.Diagnostics.Trace.TraceError($"{ex}");
  213. }
  214. }
  215. private static void Theme_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
  216. {
  217. SetTheme();
  218. }
  219. public static void SetTheme()
  220. {
  221. try
  222. {
  223. var themeConfig = (Application.Current as IApp).ThemeConfig;
  224. ThemeManager.Current.ChangeTheme(Application.Current, $"{themeConfig.ThemeName}.{themeConfig.ThemeColors}");
  225. }
  226. catch (Exception ex)
  227. {
  228. System.Diagnostics.Trace.TraceError($"{ex}");
  229. }
  230. }
  231. public static void SetFont()
  232. {
  233. var app = (Application.Current as IApp);
  234. Application.Current.Resources["DefaultFontWeight"] = FontWeight.FromOpenTypeWeight(app.ThemeConfig.FontWeight);
  235. Application.Current.Resources["DefaultFontSize"] = app.ThemeConfig.FontSize;
  236. Application.Current.Resources["DefaultFont"] = new FontFamily(app.ThemeConfig.FontName);
  237. }
  238. private static void CheckDataBase(BaseDB db, bool dataBaseNeedRest)
  239. {
  240. string databasepath = "";
  241. if (db.DatabaseType == DatabaseType.Sqlite)
  242. {
  243. databasepath = Path.Combine(db.ServerName, db.DatabaseInfo);
  244. }
  245. else
  246. {
  247. return;
  248. }
  249. if (dataBaseNeedRest) //用户设置了重置数据库
  250. {
  251. System.Diagnostics.Trace.TraceInformation($"用户请求重置数据库,数据库开始重置");
  252. if (ReleseDatabase())
  253. {
  254. DataBaseNeedRest.Value = false; //数据库重置成功
  255. }
  256. }
  257. else
  258. {
  259. if (File.Exists(databasepath))
  260. {
  261. //object dt = db.ExecuteScalar("PRAGMA integrity_check");
  262. //if ($"{dt}".ToUpper() == "OK")
  263. //{
  264. // System.Diagnostics.Debug.WriteLine($"{databasepath} 数据库检测正常");
  265. //}
  266. //else
  267. //{
  268. // Application.Current.Dispatcher.Invoke(new Action(() =>
  269. // {
  270. // if (MessageBox.Show(Application.Current?.MainWindow, LanguageHelper.GetStringByKey("SysCfg_DatabaseIsDamageTip"), LanguageHelper.SysCfg_Wran, MessageBoxButton.OK) == MessageBoxResult.OK)
  271. // {
  272. // System.Diagnostics.Trace.TraceWarning($"检测到本地数据库已损坏,开始重置数据库");
  273. // _ = ReleseDatabase();
  274. // }
  275. // }));
  276. //}
  277. }
  278. else
  279. {
  280. ReleseDatabase();
  281. }
  282. }
  283. bool ReleseDatabase()
  284. {
  285. try
  286. {
  287. if (File.Exists(databasepath))
  288. {
  289. File.Move(databasepath, $"{databasepath}.{DateTime.Now:yyyyMMddHHmmss}");
  290. }
  291. var assembly = Assembly.GetEntryAssembly();
  292. Stream res = null;
  293. var dbRes = LocalResource.ResourceManager.GetObject(Path.GetFileNameWithoutExtension(databasepath));
  294. if (dbRes is byte[] resBytes)
  295. {
  296. res = new MemoryStream(resBytes);
  297. }
  298. if (res == null) return true;
  299. using (res)
  300. {
  301. FileHelper.EnsureDirectoryExist(databasepath);
  302. byte[] save = ZipHelper.UnZip(res)[0];
  303. using (FileStream fsObj = new FileStream(databasepath, FileMode.Create))
  304. {
  305. fsObj.Write(save, 0, save.Length);
  306. fsObj.Close();
  307. }
  308. }
  309. System.Diagnostics.Debug.WriteLine($"{databasepath} 数据库修复成功");
  310. return true;
  311. }
  312. catch (Exception ex)
  313. {
  314. System.Diagnostics.Trace.Fail($"{databasepath} 数据库修复失败,{ex}");
  315. //_ = MessageBox.Show(Application.Current?.MainWindow, ex.ToString(), LanguageHelper.GetStringByKey("SysCfg_DatabaseRepairFail"));
  316. }
  317. return false;
  318. }
  319. }
  320. }
  321. }