using ControlzEx.Theming; using DIL; using NPOI.SS.Formula.Functions; using SCADA.CommonCtrl.Wpf; using SCADA.CommonCtrl.WpfControl; using SCADA.CommonCtrl.WpfHelper; using SCADA.CommonLib; using SCADA.CommonLib.Data.DIL; using SCADA.CommonLib.Data.DIL.Sqlite; using SCADA.CommonLib.Helper; using SCADA_DAQ.Plugin.Core.License; using SCADA_DAQ.Plugin.CoreUI; 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; 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; internal static LicenseInfo LicenseInfo; public static DateTime StartTime { get; set; } public static int StartTick { get; internal set; } public static AutoSaveParameterItem ProductTitle { get; set; } public static AutoSaveParameterItem ProductName { get; set; } public static AutoSaveParameterItem CompanyName { get; set; } public static AutoSaveParameterItem AuthorInfo { get; set; } public static AutoSaveParameterItem MainDllName { get; 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 DefaultUserName { get; set; } public static AutoSaveParameterItem WebServerAddress = AutoSaveParameterItem.Create("App.WebServer", "www.skdscada.com"); 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); #region 系统设置 public static AutoSaveParameterItem ComputerId; public static AutoSaveParameterItem ComputerTag; public static AutoSaveParameterItem RESTfulPort; public static AutoSaveParameterItem RPCPort; public static AutoSaveParameterItem SingleModel; public static AutoSaveParameterItem LogLevel; public static AutoSaveParameterItem AutoCycle; public static AutoSaveParameterItem CycleTime; public static AutoSaveParameterItem DataExpireDay; #endregion #region 主题配置 public static AutoSaveParameterItem ThemeName; public static AutoSaveParameterItem ThemeColor; #endregion public static AutoSaveParameterItem Language; /// /// 设备配置文件 /// public static AutoSaveParameterItem DeviceConfigFilePath; public static void ParameterInit() { ProductTitle = AutoSaveParameterItem.Create("App.MainTitle", ApplicationHelper.GetProductTitle(), true); ProductTitle.DisplayName = "窗口标题"; ProductName = AutoSaveParameterItem.Create("App.ProductName", "EICP", true); ProductName.DisplayName = "产品名称"; CompanyName = AutoSaveParameterItem.Create("App.CompanyName", "", true); CompanyName.DisplayName = "公司名称"; AuthorInfo = AutoSaveParameterItem.Create("App.AuthorInfo", System.Windows.Forms.Application.CompanyName, true); AuthorInfo.DisplayName = "作者信息"; DefaultUserName = AutoSaveParameterItem.Create("App.DefualtUserName", "Operator", true); DefaultUserName.DisplayName = "默认用户"; ComputerId = AutoSaveParameterItem.Create("App.ComputerId", "", true); ComputerId.IsReadOnly = true; ComputerId.DisplayName = "本机ID"; ComputerTag = AutoSaveParameterItem.Create("App.ComputerTag", "", true); ComputerTag.IsReadOnly = true; RESTfulPort = AutoSaveParameterItem.Create("App.RESTfulPort", 7888); RESTfulPort.DisplayName = "网页端口"; RPCPort = AutoSaveParameterItem.Create("App.RPCPort", 7880); RPCPort.DisplayName = "本地端口"; SingleModel = AutoSaveParameterItem.Create("App.SingleModel", true); SingleModel.DisplayName = "单例模式"; LogLevel = AutoSaveParameterItem.Create("App.LogLevel", SCADA.CommonLib.LoggerHelper.LogLevel.All); AutoCycle = AutoSaveParameterItem.Create("App.AutoCycle", false); AutoCycle.DisplayName = "页面自动循环"; CycleTime = AutoSaveParameterItem.Create("App.CycleTime", 5); CycleTime.IsEnableBinding = new System.Windows.Data.Binding("Value") { Source = AutoCycle }; CycleTime.Unit = "秒"; 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\QwPlatform.db" }, new DataBaseConfig() { ResourceName="AlarmDB", DBType = DatabaseType.Sqlite, FilePath = @"Data\QwPlatform.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; } DataExpireDay = AutoSaveParameterItem.Create($"App.DataExpireDay", 30); DataExpireDay.DisplayName = "数据过期时间(天)"; ThemeName = AutoSaveParameterItem.Create("App.ThemeName", "Light"); ThemeName.StringType = StringType.IsLimited; ThemeName.ShowButton = false; ThemeName.ItemsSource = new Dictionary { { "Light", "Light" }, { "Dark", "Dark" } }; ThemeColor = AutoSaveParameterItem.Create("App.ThemeColor", "Blue"); ThemeColor.StringType = StringType.IsLimited; ThemeColor.ShowButton = false; DeviceConfigFilePath = AutoSaveParameterItem.Create("DeviceConfigFilePath", "DeviceCfg.xml"); DeviceConfigFilePath.StringType = StringType.IsFilePath; DeviceConfigFilePath.DisplayName = "设备配置文件"; Language = AutoSaveParameterItem.Create("App.Language", "zh-cn"); Language.StringType = StringType.IsLimited; Language.ItemsSource = new Dictionary() { {"中文(简体)","zh-cn" }, {"中文(繁体)","zh-tw" }, {"English(US)","en-us" }, {"Deutsch","de-de" }, {"Руская","ru-ru" }, {"日本語","ja-jp" }, {"한국어","ko-kr" }, {"ภาษาไทย","th-th"} }; ThemeColor.PropertyChanged += Theme_PropertyChanged; ThemeName.PropertyChanged += Theme_PropertyChanged; if (Application.Current != null) { ThemeColor.ItemsSource = 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" }.ToDictionary(t => t, t => t); } 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); 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; } } }; GlobalEnv.Instance.User = NewUser; Language.PropertyChanged += Language_PropertyChanged; EnvInitFinish = true; } private static void dataBaseInit(bool v, DataBaseConfig dataBaseConfig, object config, DatabaseSelector databaseSelector, object selector) { throw new NotImplementedException(); } static Env() { //XmlUserConfig.Create(); } private static void Language_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { SetLanguage(); } public static void SetLanguage() { try { List dictionaryList = new List(); foreach (ResourceDictionary dictionary in Application.Current.Resources.MergedDictionaries) { dictionaryList.Add(dictionary); } string requestedCulture = $@"{Language.Value}.xaml"; ResourceDictionary resourceDictionary = dictionaryList.FirstOrDefault(d => d?.Source?.Segments.Last() == requestedCulture); Application.Current.Resources.MergedDictionaries.Remove(resourceDictionary); Application.Current.Resources.MergedDictionaries.Add(resourceDictionary); LanguageHelper.CurrentLanguageDictionary = resourceDictionary; LanguageHelper.DefaultLanguageDictionary = dictionaryList.FirstOrDefault(d => d?.Source?.Segments.Last() == @"zh-cn.xaml"); } 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 { ThemeManager.Current.ChangeTheme(Application.Current, $"{ThemeName.Value}.{ThemeColor.Value}"); } catch (Exception ex) { System.Diagnostics.Trace.TraceError($"{ex}"); } } public static void SetFont() { AutoSaveParameterItem DefaultFont = AutoSaveParameterItem.Create("App.DefaultFont", "Microsoft YaHei UI"); AutoSaveParameterItem DefaultFontSize = AutoSaveParameterItem.Create("App.DefaultFontSize", 14d); AutoSaveParameterItem DefaultFontWeight = AutoSaveParameterItem.Create("App.DefaultFontWeight", 400); Application.Current.Resources["DefaultFontWeight"] = FontWeight.FromOpenTypeWeight(DefaultFontWeight.Value); Application.Current.Resources["DefaultFontSize"] = DefaultFontSize.Value; Application.Current.Resources["DefaultFont"] = new FontFamily(DefaultFont.Value); } 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; if (Path.GetFileName(databasepath).ToUpper() == "LOCALAPP.DB") { res = new MemoryStream(LocalResource.LocalApp); } else if (Path.GetFileName(databasepath).ToUpper() == "QWPLATFORM.DB") { res = new MemoryStream(LocalResource.QwPlatform); } 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; } } } }