using ControlzEx.Theming; using DIL; using SCADA.CommonCtrl.WpfHelper; using SCADA.CommonLib; using SCADA.CommonLib.Data.DIL; using SCADA.CommonLib.Helper; using SCADA_DAQ.Plugin.Core.License; using SysManage.User; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Reflection; using System.Windows; using System.Windows.Media; using SCADA_DAQ.Plugin.CoreUI; using SCADA.CommonLib.License; namespace SCADA_DAQ { class Env { public static DILDBV1 DAL = null; public static bool EnvInitFinish = false; public static User NewUser; public static Schedual Schedual { get; internal set; } = Schedual.Instance; public static DateTime StartTime { get; set; } public static int StartTick { get; internal set; } public static DataBaseConfig CurrentDbConfig { get; set; } public static AutoSaveParameterItem CurrentDataBase { get; set; } public static DataBaseConfig SysDBConfig { get; set; } public static AutoSaveParameterItem SysDataBase { get; set; } public static DataBaseConfig AlarmDBConfig { get; set; } public static AutoSaveParameterItem AlarmDataBase { get; set; } public static AutoSaveParameterItem> DataBaseResource { get; set; } public static AutoSaveParameterItem DataBaseNeedRest { get; set; } = AutoSaveParameterItem.Create("App.DatabaseNeedRest", false); /// /// 产量个数 /// public static AutoSaveParameterItem TotalOutputPcs { get; set; } = AutoSaveParameterItem.Create("App.TotalOutputPcs", 0); /// /// 产量 /// public static AutoSaveParameterItem TotalOutputQty { get; set; } = AutoSaveParameterItem.Create("App.TotalOutputQty", 0m); public static void ParameterInit(IApp app) { CurrentDataBase = AutoSaveParameterItem.Create("App.DataBaseConfig", new DatabaseSelector() { CurrentDataBaseConfig = "Default" }); SysDataBase = AutoSaveParameterItem.Create("App.DataBaseConfig.System", new DatabaseSelector() { CurrentDataBaseConfig = "SysDB" }); AlarmDataBase = AutoSaveParameterItem.Create("App.DataBaseConfig.Alarm", new DatabaseSelector() { CurrentDataBaseConfig = "AlarmDB" }); DataBaseResource = AutoSaveParameterItem.Create("App.DataBaseResource", new ObservableCollection() { new DataBaseConfig() { ResourceName="Default", DBType = DatabaseType.Sqlite, FilePath = @"Data\Platform.db" }, new DataBaseConfig() { ResourceName="AlarmDB", DBType = DatabaseType.Sqlite, FilePath = @"Data\Alarmdb.db" }, new DataBaseConfig() { ResourceName="SysDB", DBType = DatabaseType.Sqlite, FilePath = @"Data\LocalApp.db" }, }, true); dataBaseConfigInit(DataBaseResource, CurrentDataBase.Value, out var currentconfig); dataBaseConfigInit(DataBaseResource, SysDataBase.Value, out var sysConfig); dataBaseConfigInit(DataBaseResource, AlarmDataBase.Value, out var alarmConfig); CurrentDbConfig = currentconfig; AlarmDBConfig = alarmConfig; SysDBConfig = sysConfig; void dataBaseConfigInit(ObservableCollection srouce, DatabaseSelector selector, out DataBaseConfig config) { config = DataBaseResource.Value.FirstOrDefault(t => t.ResourceName == selector?.CurrentDataBaseConfig); selector.DataBaseConfigResource = DataBaseResource.Value; if (config == null) { config = DataBaseResource.Value.FirstOrDefault(); selector.CurrentDataBaseConfig = config.ResourceName; } selector.DataBaseConfig = config; } app.ThemeConfig.ThemeNameSrc = new List { "Light", "Dark" }; app.ThemeConfig.ThemeColorSrc = new List() { "Red", "Green", "Blue", "Purple", "Orange", "Lime", "Emerald", "Teal", "Cyan", "Cobalt", "Indigo", "Violet", "Pink", "Magenta", "Crimson", "Amber", "Yellow", "Brown", "Olive", "Steel", "Mauve", "Taupe", "Sienna" }; app.ThemeConfig.LanguageSrc = new Dictionary() { {"中文(简体)","zh-cn" }, {"中文(繁体)","zh-tw" }, {"English(US)","en-us" }, {"Deutsch","de-de" }, {"Руская","ru-ru" }, {"日本語","ja-jp" }, {"한국어","ko-kr" }, {"ภาษาไทย","th-th"} }; app.ThemeConfig.PropertyChanged += SystemConfig_PropertyChanged; bool neeRestDatabase = DataBaseNeedRest.Value; DAL = new DILDBV1(CurrentDbConfig.GetDB()); CheckDataBase(DAL, CurrentDbConfig.NeedReset || DataBaseNeedRest.Value); //GlobalEnv.Instance.GlobalDB = DAL; //GlobalEnv.Instance.AlarmDB = new DILDBV1(AlarmDBConfig.GetDB()); //CheckDataBase(GlobalEnv.Instance.AlarmDB as BaseDB, CurrentDbConfig.NeedReset || DataBaseNeedRest.Value); //GlobalEnv.Instance.LocalAppDB = new LocalDB.DIL.DILDBV1(SysDBConfig.GetDB()); //CheckDataBase(GlobalEnv.Instance.LocalAppDB as BaseDB, CurrentDbConfig.NeedReset || DataBaseNeedRest.Value); app.RuntimeInfo.GlobalDB = DAL; app.RuntimeInfo.AlarmDB = new DILDBV1(AlarmDBConfig.GetDB()); CheckDataBase(app.RuntimeInfo.AlarmDB as BaseDB, CurrentDbConfig.NeedReset || DataBaseNeedRest.Value); app.RuntimeInfo.LocalAppDB = new LocalDB.DIL.DILDBV1(SysDBConfig.GetDB()); CheckDataBase(app.RuntimeInfo.LocalAppDB as BaseDB, CurrentDbConfig.NeedReset || DataBaseNeedRest.Value); NewUser = new User(DAL) { UserName = "Admin", PassWordReviseHandler = () => { var passWordRevise = new FrmUserLogin(new PasswordReviseViewModel(NewUser)); ((BaseMainWindow)Application.Current.MainWindow).ShowChildWindow(passWordRevise); }, TryLoginHandler = () => { if (NewUser.IsLogged == false) { FrmUserLogin frmUserLog = new FrmUserLogin(new UserLoginViewModel(NewUser)); ((BaseMainWindow)Application.Current.MainWindow).ShowChildWindow(frmUserLog); } else { (Application.Current as IApp).ShowToast($"{LanguageHelper.GetStringByKey("SysCfg_CurrentUser")}{NewUser.UserName}", ControlStyle.Info); } }, MidCheckHandler = () => { var frmUserLog = new FrmUserLogin(new UserLoginViewModel(NewUser)); if (NewUser.IsLogged == false) { ((BaseMainWindow)Application.Current.MainWindow).ShowChildWindow(frmUserLog); return NewUser.IsLogged; } else { return NewUser.IsLogged; } } }; app.RuntimeInfo.User = NewUser; EnvInitFinish = true; } private static void SystemConfig_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName == nameof(ThemeConfig.Language)) { SetLanguage(); } else if (e.PropertyName == nameof(ThemeConfig.ThemeColors) || e.PropertyName == nameof(ThemeConfig.ThemeName)) { SetTheme(); } else if (e.PropertyName == nameof(ThemeConfig.FontName) || e.PropertyName == nameof(ThemeConfig.FontSize) || e.PropertyName == nameof(ThemeConfig.FontWeight)) { SetFont(); } } static Env() { } public static void SetLanguage() { try { List dictionaryList = new List(); foreach (ResourceDictionary dictionary in Application.Current.Resources.MergedDictionaries) { dictionaryList.Add(dictionary); } string requestedCulture = $@"{(Application.Current as IApp).ThemeConfig.Language}.xaml"; ResourceDictionary resourceDictionary = null; ResourceDictionary defaultLanguage = null; foreach (var item in dictionaryList) { try { if (item.Source == null) continue; if (item.Source.Segments.LastOrDefault() == requestedCulture) { resourceDictionary = item; } if (item.Source.Segments.LastOrDefault() == "zh-cn.xaml") { defaultLanguage = item; } } catch (Exception) { } } if (requestedCulture == null) return; Application.Current.Resources.MergedDictionaries.Remove(resourceDictionary); Application.Current.Resources.MergedDictionaries.Add(resourceDictionary); LanguageHelper.CurrentLanguageDictionary = resourceDictionary; LanguageHelper.DefaultLanguageDictionary = defaultLanguage; } catch (Exception ex) { System.Diagnostics.Trace.TraceError($"{ex}"); } } private static void Theme_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { SetTheme(); } public static void SetTheme() { try { var themeConfig = (Application.Current as IApp).ThemeConfig; ThemeManager.Current.ChangeTheme(Application.Current, $"{themeConfig.ThemeName}.{themeConfig.ThemeColors}"); } catch (Exception ex) { System.Diagnostics.Trace.TraceError($"{ex}"); } } public static void SetFont() { var app = (Application.Current as IApp); Application.Current.Resources["DefaultFontWeight"] = FontWeight.FromOpenTypeWeight(app.ThemeConfig.FontWeight); Application.Current.Resources["DefaultFontSize"] = app.ThemeConfig.FontSize; Application.Current.Resources["DefaultFont"] = new FontFamily(app.ThemeConfig.FontName); } private static void CheckDataBase(BaseDB db, bool dataBaseNeedRest) { string databasepath = ""; if (db.DatabaseType == DatabaseType.Sqlite) { databasepath = Path.Combine(db.ServerName, db.DatabaseInfo); } else { return; } if (dataBaseNeedRest) //用户设置了重置数据库 { System.Diagnostics.Trace.TraceInformation($"用户请求重置数据库,数据库开始重置"); if (ReleseDatabase()) { DataBaseNeedRest.Value = false; //数据库重置成功 } } else { if (File.Exists(databasepath)) { //object dt = db.ExecuteScalar("PRAGMA integrity_check"); //if ($"{dt}".ToUpper() == "OK") //{ // System.Diagnostics.Debug.WriteLine($"{databasepath} 数据库检测正常"); //} //else //{ // Application.Current.Dispatcher.Invoke(new Action(() => // { // if (MessageBox.Show(Application.Current?.MainWindow, LanguageHelper.GetStringByKey("SysCfg_DatabaseIsDamageTip"), LanguageHelper.SysCfg_Wran, MessageBoxButton.OK) == MessageBoxResult.OK) // { // System.Diagnostics.Trace.TraceWarning($"检测到本地数据库已损坏,开始重置数据库"); // _ = ReleseDatabase(); // } // })); //} } else { ReleseDatabase(); } } bool ReleseDatabase() { try { if (File.Exists(databasepath)) { File.Move(databasepath, $"{databasepath}.{DateTime.Now:yyyyMMddHHmmss}"); } var assembly = Assembly.GetEntryAssembly(); Stream res = null; var dbRes = LocalResource.ResourceManager.GetObject(Path.GetFileNameWithoutExtension(databasepath)); if (dbRes is byte[] resBytes) { res = new MemoryStream(resBytes); } if (res == null) return true; using (res) { FileHelper.EnsureDirectoryExist(databasepath); byte[] save = ZipHelper.UnZip(res)[0]; using (FileStream fsObj = new FileStream(databasepath, FileMode.Create)) { fsObj.Write(save, 0, save.Length); fsObj.Close(); } } System.Diagnostics.Debug.WriteLine($"{databasepath} 数据库修复成功"); return true; } catch (Exception ex) { System.Diagnostics.Trace.Fail($"{databasepath} 数据库修复失败,{ex}"); //_ = MessageBox.Show(Application.Current?.MainWindow, ex.ToString(), LanguageHelper.GetStringByKey("SysCfg_DatabaseRepairFail")); } return false; } } } }